pyte-0.4.8/0000755000076500000240000000000012264723152014027 5ustar superbobrystaff00000000000000pyte-0.4.8/AUTHORS0000644000076500000240000000020212264723075015075 0ustar superbobrystaff00000000000000Authors ======= - George Shuklin - Sergei Lebedev Contributors ------------ - Alexey Shamrin - Steve Cohen - Jonathan Slenders pyte-0.4.8/CHANGES0000644000076500000240000000776212264723075015042 0ustar superbobrystaff00000000000000pyte Changelog ============== Here you can see the full list of changes between each pyte release. Version 0.4.8 ------------- - `pyte.screens.Screen` does NOT inherit from builtin `list`, use `screen.buffer` to access individual characters directly. This is a backward INCOMPATIBLE change. - `pyte.screens.Char._asdict` was broken on Python 3.3 because of the changes in `namedtuple` implementation. - `pyte.charsets.LAT1_MAP` was an iterator because of the change in map semantics in Python 3 - Changed `pyte.screens.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 `pyte.screens.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 - Created MANIFEST.in file - Added CentOS 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 nows 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, especialy 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 implemnted yet: setting alternate font, setting and resetting mappings, blinking text. - Added a couple of trivial usage examples in the `examples/` dir. pyte-0.4.8/docs/0000755000076500000240000000000012264723152014757 5ustar superbobrystaff00000000000000pyte-0.4.8/docs/_static/0000755000076500000240000000000012264723152016405 5ustar superbobrystaff00000000000000pyte-0.4.8/docs/_static/rtd.css0000644000076500000240000003563412047255265017727 0ustar superbobrystaff00000000000000/* * rtd.css * ~~~~~~~~~~~~~~~ * * Sphinx stylesheet -- sphinxdoc theme. Originally created by * Armin Ronacher for Werkzeug. * * Customized for ReadTheDocs by Eric Pierce & Eric Holscher * * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* RTD colors * light blue: #e8ecef * medium blue: #8ca1af * dark blue: #465158 * dark grey: #444444 * * white hover: #d1d9df; * medium blue hover: #697983; * green highlight: #8ecc4c * light blue (project bar): #e8ecef */ @import url("basic.css"); /* PAGE LAYOUT -------------------------------------------------------------- */ body { font: 100%/1.5 "ff-meta-web-pro-1","ff-meta-web-pro-2",Arial,"Helvetica Neue",sans-serif; text-align: center; color: black; background-color: #465158; padding: 0; margin: 0; } div.document { text-align: left; background-color: #e8ecef; } div.bodywrapper { background-color: #ffffff; border-left: 1px solid #ccc; border-bottom: 1px solid #ccc; margin: 0 0 0 16em; } div.body { margin: 0; padding: 0.5em 1.3em; max-width: 55em; min-width: 20em; } div.related { font-size: 1em; background-color: #465158; } div.documentwrapper { float: left; width: 100%; background-color: #e8ecef; } /* HEADINGS --------------------------------------------------------------- */ h1 { margin: 0; padding: 0.7em 0 0.3em 0; font-size: 1.5em; line-height: 1.15; color: #111; clear: both; } h2 { margin: 2em 0 0.2em 0; font-size: 1.35em; padding: 0; color: #465158; } h3 { margin: 1em 0 -0.3em 0; font-size: 1.2em; color: #6c818f; } div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a { color: black; } h1 a.anchor, h2 a.anchor, h3 a.anchor, h4 a.anchor, h5 a.anchor, h6 a.anchor { display: none; margin: 0 0 0 0.3em; padding: 0 0.2em 0 0.2em; color: #aaa !important; } h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { display: inline; } h1 a.anchor:hover, h2 a.anchor:hover, h3 a.anchor:hover, h4 a.anchor:hover, h5 a.anchor:hover, h6 a.anchor:hover { color: #777; background-color: #eee; } /* LINKS ------------------------------------------------------------------ */ /* Normal links get a pseudo-underline */ a { color: #444; text-decoration: none; border-bottom: 1px solid #ccc; } /* Links in sidebar, TOC, index trees and tables have no underline */ .sphinxsidebar a, .toctree-wrapper a, .indextable a, #indices-and-tables a { color: #444; text-decoration: none; border-bottom: none; } /* Most links get an underline-effect when hovered */ a:hover, div.toctree-wrapper a:hover, .indextable a:hover, #indices-and-tables a:hover { color: #111; text-decoration: none; border-bottom: 1px solid #111; } /* Footer links */ div.footer a { color: #86989B; text-decoration: none; border: none; } div.footer a:hover { color: #a6b8bb; text-decoration: underline; border: none; } /* Permalink anchor (subtle grey with a red hover) */ div.body a.headerlink { color: #ccc; font-size: 1em; margin-left: 6px; padding: 0 4px 0 4px; text-decoration: none; border: none; } div.body a.headerlink:hover { color: #c60f0f; border: none; } /* NAVIGATION BAR --------------------------------------------------------- */ div.related ul { height: 2.5em; } div.related ul li { margin: 0; padding: 0.65em 0; float: left; display: block; color: white; /* For the >> separators */ font-size: 0.8em; } div.related ul li.right { float: right; margin-right: 5px; color: transparent; /* Hide the | separators */ } /* "Breadcrumb" links in nav bar */ div.related ul li a { order: none; background-color: inherit; font-weight: bold; margin: 6px 0 6px 4px; line-height: 1.75em; color: #ffffff; padding: 0.4em 0.8em; border: none; border-radius: 3px; } /* previous / next / modules / index links look more like buttons */ div.related ul li.right a { margin: 0.375em 0; background-color: #697983; text-shadow: 0 1px rgba(0, 0, 0, 0.5); border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; } /* All navbar links light up as buttons when hovered */ div.related ul li a:hover { background-color: #8ca1af; color: #ffffff; text-decoration: none; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; } /* Take extra precautions for tt within links */ a tt, div.related ul li a tt { background: inherit !important; color: inherit !important; } /* SIDEBAR ---------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 0; } div.sphinxsidebar { margin: 0; margin-left: -100%; float: left; top: 3em; left: 0; padding: 0 1em; width: 14em; font-size: 1em; text-align: left; background-color: #e8ecef; } div.sphinxsidebar img { max-width: 12em; } div.sphinxsidebar h3, div.sphinxsidebar h4 { margin: 1.2em 0 0.3em 0; font-size: 1em; padding: 0; color: #222222; font-family: "ff-meta-web-pro-1", "ff-meta-web-pro-2", "Arial", "Helvetica Neue", sans-serif; } div.sphinxsidebar h3 a { color: #444444; } div.sphinxsidebar ul, div.sphinxsidebar p { margin-top: 0; padding-left: 0; line-height: 130%; background-color: #e8ecef; } /* No bullets for nested lists, but a little extra indentation */ div.sphinxsidebar ul ul { list-style-type: none; margin-left: 1.5em; padding: 0; } /* A little top/bottom padding to prevent adjacent links' borders * from overlapping each other */ div.sphinxsidebar ul li { padding: 1px 0; } /* A little left-padding to make these align with the ULs */ div.sphinxsidebar p.topless { padding-left: 0 0 0 1em; } /* Make these into hidden one-liners */ div.sphinxsidebar ul li, div.sphinxsidebar p.topless { white-space: nowrap; overflow: hidden; } /* ...which become visible when hovered */ div.sphinxsidebar ul li:hover, div.sphinxsidebar p.topless:hover { overflow: visible; } /* Search text box and "Go" button */ #searchbox { margin-top: 2em; margin-bottom: 1em; background: #ddd; padding: 0.5em; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } #searchbox h3 { margin-top: 0; } /* Make search box and button abut and have a border */ input, div.sphinxsidebar input { border: 1px solid #999; float: left; } /* Search textbox */ input[type="text"] { margin: 0; padding: 0 3px; height: 20px; width: 144px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; -moz-border-radius-topleft: 3px; -moz-border-radius-bottomleft: 3px; -webkit-border-top-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; } /* Search button */ input[type="submit"] { margin: 0 0 0 -1px; /* -1px prevents a double-border with textbox */ height: 22px; color: #444; background-color: #e8ecef; padding: 1px 4px; font-weight: bold; border-top-right-radius: 3px; border-bottom-right-radius: 3px; -moz-border-radius-topright: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; } input[type="submit"]:hover { color: #ffffff; background-color: #8ecc4c; } div.sphinxsidebar p.searchtip { clear: both; padding: 0.5em 0 0 0; background: #ddd; color: #666; font-size: 0.9em; } /* Sidebar links are unusual */ div.sphinxsidebar li a, div.sphinxsidebar p a { background: #e8ecef; /* In case links overlap main content */ border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: 1px solid transparent; /* To prevent things jumping around on hover */ padding: 0 5px 0 5px; } div.sphinxsidebar li a:hover, div.sphinxsidebar p a:hover { color: #111; text-decoration: none; border: 1px solid #888; } /* Tweak any link appearing in a heading */ div.sphinxsidebar h3 a { } /* OTHER STUFF ------------------------------------------------------------ */ cite, code, tt { font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.95em; letter-spacing: 0.01em; } tt { background-color: #f2f2f2; color: #444; } tt.descname, tt.descclassname, tt.xref { border: 0; } hr { border: 1px solid #abc; margin: 2em; } pre, #_fontwidthtest { font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; margin: 1em 2em; font-size: 0.95em; letter-spacing: 0.015em; line-height: 120%; padding: 0.5em; border: 1px solid #ccc; background-color: #eee; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } pre a { color: inherit; text-decoration: underline; } td.linenos pre { padding: 0.5em 0; } div.quotebar { background-color: #f8f8f8; max-width: 250px; float: right; padding: 2px 7px; border: 1px solid #ccc; } div.topic { background-color: #f8f8f8; } table { border-collapse: collapse; margin: 0 -0.5em 0 -0.5em; } table td, table th { padding: 0.2em 0.5em 0.2em 0.5em; } /* ADMONITIONS AND WARNINGS ------------------------------------------------- */ /* Shared by admonitions and warnings */ div.admonition, div.warning { font-size: 0.9em; margin: 2em; padding: 0; /* border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; */ } div.admonition p, div.warning p { margin: 0.5em 1em 0.5em 1em; padding: 0; } div.admonition pre, div.warning pre { margin: 0.4em 1em 0.4em 1em; } div.admonition p.admonition-title, div.warning p.admonition-title { margin: 0; padding: 0.1em 0 0.1em 0.5em; color: white; font-weight: bold; font-size: 1.1em; text-shadow: 0 1px rgba(0, 0, 0, 0.5); } div.admonition ul, div.admonition ol, div.warning ul, div.warning ol { margin: 0.1em 0.5em 0.5em 3em; padding: 0; } /* Admonitions only */ div.admonition { border: 1px solid #609060; background-color: #e9ffe9; } div.admonition p.admonition-title { background-color: #70A070; border-bottom: 1px solid #609060; } /* Warnings only */ div.warning { border: 1px solid #900000; background-color: #ffe9e9; } div.warning p.admonition-title { background-color: #b04040; border-bottom: 1px solid #900000; } div.versioninfo { margin: 1em 0 0 0; border: 1px solid #ccc; background-color: #DDEAF0; padding: 8px; line-height: 1.3em; font-size: 0.9em; } .viewcode-back { font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; } div.viewcode-block:target { background-color: #f4debf; border-top: 1px solid #ac9; border-bottom: 1px solid #ac9; } dl { margin: 1em 0 2.5em 0; } /* Highlight target when you click an internal link */ dt:target { background: #ffe080; } /* Don't highlight whole divs */ div.highlight { background: transparent; } /* But do highlight spans (so search results can be highlighted) */ span.highlight { background: #ffe080; } div.footer { background-color: #465158; color: #eeeeee; padding: 0 2em 2em 2em; clear: both; font-size: 0.8em; text-align: center; } p { margin: 0.8em 0 0.5em 0; } .section p img { margin: 1em 2em; } /* MOBILE LAYOUT -------------------------------------------------------------- */ @media screen and (max-width: 600px) { h1, h2, h3, h4, h5 { position: relative; } ul { padding-left: 1.75em; } div.bodywrapper a.headerlink, #indices-and-tables h1 a { color: #e6e6e6; font-size: 80%; float: right; line-height: 1.8; position: absolute; right: -0.7em; visibility: inherit; } div.bodywrapper h1 a.headerlink, #indices-and-tables h1 a { line-height: 1.5; } pre { font-size: 0.7em; overflow: auto; word-wrap: break-word; white-space: pre-wrap; } div.related ul { height: 2.5em; padding: 0; text-align: left; } div.related ul li { clear: both; color: #465158; padding: 0.2em 0; } div.related ul li:last-child { border-bottom: 1px dotted #8ca1af; padding-bottom: 0.4em; margin-bottom: 1em; width: 100%; } div.related ul li a { color: #465158; padding-right: 0; } div.related ul li a:hover { background: inherit; color: inherit; } div.related ul li.right { clear: none; padding: 0.65em 0; margin-bottom: 0.5em; } div.related ul li.right a { color: #fff; padding-right: 0.8em; } div.related ul li.right a:hover { background-color: #8ca1af; } div.body { clear: both; min-width: 0; word-wrap: break-word; } div.bodywrapper { margin: 0 0 0 0; } div.sphinxsidebar { float: none; margin: 0; width: auto; } div.sphinxsidebar input[type="text"] { height: 2em; line-height: 2em; width: 70%; } div.sphinxsidebar input[type="submit"] { height: 2em; margin-left: 0.5em; width: 20%; } div.sphinxsidebar p.searchtip { background: inherit; margin-bottom: 1em; } div.sphinxsidebar ul li, div.sphinxsidebar p.topless { white-space: normal; } .bodywrapper img { display: block; margin-left: auto; margin-right: auto; max-width: 100%; } div.documentwrapper { float: none; } div.admonition, div.warning, pre, blockquote { margin-left: 0em; margin-right: 0em; } .body p img { margin: 0; } #searchbox { background: transparent; } .related:not(:first-child) li { display: none; } .related:not(:first-child) li.right { display: block; } div.footer { padding: 1em; } .rtd_doc_footer .badge { float: none; margin: 1em auto; position: static; } .rtd_doc_footer .badge.revsys-inline { margin-right: auto; margin-bottom: 2em; } table.indextable { display: block; width: auto; } .indextable tr { display: block; } .indextable td { display: block; padding: 0; width: auto !important; } .indextable td dt { margin: 1em 0; } ul.search { margin-left: 0.25em; } ul.search li div.context { font-size: 90%; line-height: 1.1; margin-bottom: 1; margin-left: 0; } } pyte-0.4.8/docs/api.rst0000644000076500000240000000066512047255265016275 0ustar superbobrystaff00000000000000.. _api: API reference ============= .. automodule:: pyte .. automodule:: pyte.streams :members: .. automodule:: pyte.screens :members: :exclude-members: Margins, Savepoint, _Char, Char, History, take .. automodule:: pyte.modes :members: .. automodule:: pyte.control :members: .. automodule:: pyte.escape :members: .. automodule:: pyte.graphics :members: .. automodule:: pyte.charsets :members: pyte-0.4.8/docs/changelog.rst0000644000076500000240000000003012047255265017435 0ustar superbobrystaff00000000000000.. include:: ../CHANGES pyte-0.4.8/docs/conf.py0000644000076500000240000001347512264723075016274 0ustar superbobrystaff00000000000000# -*- 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.viewcode'] # 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, Selectel' # 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.4.8' # The full version, including alpha/beta/rc tags. release = '0.4.8' # 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 = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' html_style = 'rtd.css' # 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.4.8/docs/index.rst0000644000076500000240000000171112047255265016624 0ustar superbobrystaff00000000000000.. pyte documentation master file, created by sphinx-quickstart on Fri Apr 8 12:49:51 2011. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. .. 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: * `Selectel `_ -- hey, we wrote this thing :) * `Ajenti `_ -- easy to use weadmin panel for Linux and BSD uses ``pyte`` for its terminal plugin. * `Neutron IDE `_ -- personal cloud IDE. 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 minimal examples in the ``examples/`` directory. .. toctree:: :hidden: tutorial api changelog pyte-0.4.8/docs/tutorial.rst0000644000076500000240000000660412047255265017366 0ustar superbobrystaff00000000000000.. _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 on screen. The `Stream` is the stream processor. It manages the state of the input and dispatches events to anything that's listening about things that are going on. 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: >>> import pyte >>> screen = pyte.Screen(80, 24) >>> stream = pyte.Stream() >>> stream.attach(screen) >>> stream.feed("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"`. pyte-0.4.8/examples/0000755000076500000240000000000012264723152015645 5ustar superbobrystaff00000000000000pyte-0.4.8/examples/debug.py0000644000076500000240000001156712125110401017276 0ustar superbobrystaff00000000000000# -*- 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 sys sys.path.append("..") 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.DebugStream() screen = pyte.Screen(80, 24) stream.attach(screen) stream.feed(blob) pyte-0.4.8/examples/helloworld.py0000644000076500000240000000110512125110401020346 0ustar superbobrystaff00000000000000# -*- 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 sys sys.path.append("..") import pyte if __name__ == "__main__": stream = pyte.Stream() screen = pyte.Screen(80, 24) stream.attach(screen) stream.feed("Hello World!") for idx, line in enumerate(screen.display, 1): print("{0:2d} {1} ¶".format(idx, line)) pyte-0.4.8/examples/inception.py0000644000076500000240000000263112125110401020170 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- """ inception ~~~~~~~~~ A terminal emulator within a terminal emulator within a terminal emulator -- 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 sys.path.append("..") if sys.version_info[0] == 2: input = raw_input import pyte from pyte import modes as mo def print_screen(screen, text): print(pyte.ctrl.ESC + pyte.esc.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__": stream = pyte.Stream() # v -- means scroll whole page. screen = pyte.HistoryScreen(80, 12, ratio=1) screen.set_mode(mo.LNM) stream.attach(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.4.8/LICENSE0000644000076500000240000001674312047255265015053 0ustar superbobrystaff00000000000000 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.4.8/MANIFEST.in0000644000076500000240000000034112125110401015542 0ustar superbobrystaff00000000000000include MANIFEST.in include AUTHORS include CHANGES include LICENSE include README recursive-include docs *.rst include docs/conf.py include docs/_static/rtd.css recursive-include examples *.py recursive-include tests *.py pyte-0.4.8/PKG-INFO0000644000076500000240000000615212264723152015130 0ustar superbobrystaff00000000000000Metadata-Version: 1.1 Name: pyte Version: 0.4.8 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.4.8 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 `setuptools `_ you can use ``easy_install -U pyte``. Otherwise, you can 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 Library or Lesser General Public License (LGPL) Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Topic :: Terminals :: Terminal Emulators/X Terminals pyte-0.4.8/pyte/0000755000076500000240000000000012264723152015010 5ustar superbobrystaff00000000000000pyte-0.4.8/pyte/__init__.py0000644000076500000240000000311312125110401017076 0ustar superbobrystaff00000000000000# -*- 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-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ("Screen", "DiffScreen", "HistoryScreen", "Stream", "ByteStream", "DebugStream", "ctrl", "esc", "mo", "g", "cs") from . import ( control as ctrl, charsets as cs, escape as esc, graphics as g, modes as mo ) from .screens import Screen, DiffScreen, HistoryScreen from .streams import Stream, ByteStream, DebugStream if __debug__: import sys if sys.version_info[0] == 2: str = unicode def dis(chars): """A :func:`dis.dis` for terminals. >>> dis(u"\u0007") BELL >>> dis(u"\x9b20m") SELECT-GRAPHIC-RENDITION 20 """ if isinstance(chars, str): chars = chars.encode("utf-8") return DebugStream().feed(chars) pyte-0.4.8/pyte/__main__.py0000644000076500000240000000115512125110401017063 0ustar superbobrystaff00000000000000# -*- 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 by Selectel, see AUTHORS for more details. :license: LGPL, see LICENSE for more details. """ if __name__ == "__main__": import sys import pyte if len(sys.argv) == 1: pyte.dis(sys.stdin.read()) else: pyte.dis("".join(sys.argv[1:])) pyte-0.4.8/pyte/charsets.py0000644000076500000240000001651612264723075017213 0ustar superbobrystaff00000000000000# -*- 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-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals import sys if sys.version_info[0] == 2: chr = unichr #: Latin1. LAT1_MAP = list(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.4.8/pyte/control.py0000644000076500000240000000305012125110401017017 0ustar superbobrystaff00000000000000# -*- 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-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals #: *Space*: Not suprisingly -- ``" "``. SP = " " #: *Null*: Does nothing. NUL = "\u0000" #: *Bell*: Beeps. BEL = "\u0007" #: *Backspace*: Backspace one column, but not past the begining of the #: line. BS = "\u0008" #: *Horizontal tab*: Move cursor to the next tab stop, or to the end #: of the line if there is no earlier tab stop. HT = "\u0009" #: *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 = "\u000b" #: *Form feed*: Same as :data:`LF`. FF = "\u000c" #: *Carriage return*: Move cursor to left margin on current line. CR = "\r" #: *Shift out*: Activate G1 character set. SO = "\u000e" #: *Shift in*: Activate G0 character set. SI = "\u000f" #: *Cancel*: Interrupt escape sequence. If received during an escape or #: control sequence, cancels the sequence and displays substitution #: character. CAN = "\u0018" #: *Substitute*: Same as :data:`CAN`. SUB = "\u001a" #: *Escape*: Starts an escape sequence. ESC = "\u001b" #: *Delete*: Is ingored. DEL = "\u007f" #: *Control sequence introducer*: An equavalent for ``ESC [``. CSI = "\u009b" pyte-0.4.8/pyte/escape.py0000644000076500000240000000772012125110401016607 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- """ pyte.escape ~~~~~~~~~~~ This module defines bot CSI and non-CSI escape sequences, recognized by :class:`~pyte.streams.Stream` and subclasses. :copyright: (c) 2011-2013 by Selectel, 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" #: *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" #: *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.4.8/pyte/graphics.py0000644000076500000240000000312212125110401017137 0ustar superbobrystaff00000000000000# -*- 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-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ import itertools #: 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, example: #: #: >>> FG[30] #: 'black' #: >>> FG[38] #: 'default' FG = { 30: "black", 31: "red", 32: "green", 33: "brown", 34: "blue", 35: "magenta", 36: "cyan", 37: "white", 39: "default" # white. } #: A mapping of ANSI background color codes to color names, example: #: #: >>> BG[40] #: 'black' #: >>> BG[48] #: 'default' BG = { 40: "black", 41: "red", 42: "green", 43: "brown", 44: "blue", 45: "magenta", 46: "cyan", 47: "white", 49: "default" # black. } # Reverse mapping of all available attributes -- keep this private! _SGR = dict((v, k) for k, v in itertools.chain(BG.items(), FG.items(), TEXT.items())) pyte-0.4.8/pyte/modes.py0000644000076500000240000000344212125110401016453 0ustar superbobrystaff00000000000000# -*- 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-2013 by Selectel, 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.4.8/pyte/screens.py0000644000076500000240000011252512264723075017036 0ustar superbobrystaff00000000000000# -*- 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-2013 Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals, division import copy import math import operator import sys from collections import deque, namedtuple from itertools import islice, repeat from . import modes as mo, graphics as g, charsets as cs if sys.version_info[0] == 2: from future_builtins import map range = xrange def take(n, iterable): """Returns first n items of the iterable as a list.""" return list(islice(iterable, n)) #: 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" ]) #: A container for a single character, field names are *hopefully* #: self-explanatory. _Char = namedtuple("_Char", [ "data", "fg", "bg", "bold", "italics", "underscore", "strikethrough", "reverse", ]) class Char(_Char): """A wrapper around :class:`_Char`, providing some useful defaults for most of the attributes. """ __slots__ = () def __new__(cls, data, fg="default", bg="default", bold=False, italics=False, underscore=False, reverse=False, strikethrough=False): return _Char.__new__(cls, data, fg, bg, bold, italics, underscore, reverse, strikethrough) class Cursor(object): """Screen cursor. :param int x: horizontal cursor position. :param int y: vertical cursor position. :param pyte.screens.Char attrs: cursor attributes (see :meth:`~pyte.screens.Screen.selectel_graphic_rendition` for details). """ def __init__(self, x, y, attrs=Char(" ")): self.x, self.y, self.attrs, self.hidden = x, y, attrs, False 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 it's own and given explicit commands, or it can be attached to a stream and will respond to events. .. attribute:: buffer A ``lines x columns`` :class:`~pyte.screens.Char` matrix. .. attribute:: cursor Reference to the :class:`~pyte.screens.Cursor` object, holding cursor position and attributes. .. attribute:: margins Top and bottom screen margins, defining the scrolling region; the actual values are top and bottom line. .. 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 columnns 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. .. 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``. """ #: A plain empty character with default foreground and background #: colors. default_char = Char(data=" ", fg="default", bg="default") #: An inifinite sequence of default characters, used for populating #: new lines and columns. default_line = repeat(default_char) def __init__(self, columns, lines): self.savepoints = [] self.lines, self.columns = lines, columns self.buffer = [] self.reset() def __repr__(self): return ("{0}({1}, {2})".format(self.__class__.__name__, self.columns, self.lines)) def __before__(self, command): """Hook, called **before** a command is dispatched to the :class:`Screen` instance. :param str command: command name, for example ``"LINEFEED"``. """ def __after__(self, command): """Hook, called **after** a command is dispatched to the :class:`Screen` instance. :param str command: command name, for example ``"LINEFEED"``. """ @property def size(self): """Returns screen size -- ``(lines, columns)``""" return self.lines, self.columns @property def display(self): """Returns a :func:`list` of screen lines as unicode strings.""" return ["".join(map(operator.attrgetter("data"), line)) for line in self.buffer] def reset(self): """Resets the terminal to its initial state. * Scroll 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". .. note:: Neither VT220 nor VT102 manuals mentioned that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that. """ self.buffer[:] = (take(self.columns, self.default_line) for _ in range(self.lines)) self.mode = set([mo.DECAWM, mo.DECTCEM]) self.margins = Margins(0, self.lines - 1) # According to VT220 manual and ``linux/drivers/tty/vt.c`` # the default G0 charset is latin-1, but for reasons unknown # latin-1 breaks ascii-graphics; so G0 defaults to cp437. self.charset = 0 self.g0_charset = cs.IBMPC_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(7, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position() def resize(self, lines=None, columns=None): """Resize the screen to the given dimensions. 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. .. note:: According to `xterm`, we should also reset origin mode and screen margins, see ``xterm/screen.c:1761``. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. """ lines = lines or self.lines columns = columns or self.columns # First resize the lines: diff = self.lines - lines # a) if the current display size is less than the requested # size, add lines to the bottom. if diff < 0: self.buffer.extend(take(self.columns, self.default_line) for _ in range(diff, 0)) # b) if the current display size is greater than requested # size, take lines off the top. elif diff > 0: self.buffer[:diff] = () # Then resize the columns: diff = self.columns - columns # a) if the current display size is less than the requested # size, expand each line to the new size. if diff < 0: for y in range(lines): self.buffer[y].extend(take(abs(diff), self.default_line)) # b) if the current display size is greater than requested # size, trim each line from the right to the new size. elif diff > 0: for line in self.buffer: del line[columns:] self.lines, self.columns = lines, columns self.margins = Margins(0, self.lines - 1) self.reset_mode(mo.DECOM) def set_margins(self, top=None, bottom=None): """Selects top and bottom margins for the scrolling region. Margins determine which screen lines move during scrolling (see :meth:`index` and :meth:`reverse_index`). Characters added outside the scrolling region do not cause the screen to scroll. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled. """ if top is None or bottom is None: return # 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]. top = max(0, min(top - 1, self.lines - 1)) 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_charset(self, code, mode): """Set active ``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 set, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported. """ if code in cs.MAPS: setattr(self, {"(": "g0_charset", ")": "g1_charset"}[mode], cs.MAPS[code]) def set_mode(self, *modes, **kwargs): """Sets (enables) 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] 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.resize(columns=132) self.erase_in_display(2) self.cursor_position() # According to `vttest`, DECOM should also home the cursor, see # vttest/main.c:303. if mo.DECOM in modes: self.cursor_position() # Mark all displayed characters as reverse. if mo.DECSCNM in modes: self.buffer[:] = ([char._replace(reverse=True) for char in line] for line in self.buffer) self.select_graphic_rendition(g._SGR["+reverse"]) # Make the cursor visible. if mo.DECTCEM in modes: self.cursor.hidden = False def reset_mode(self, *modes, **kwargs): """Resets (disables) 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 distingiushed from non # private ones. if kwargs.get("private"): modes = [mode << 5 for mode in modes] self.mode.difference_update(modes) # Lines below follow the logic in :meth:`set_mode`. if mo.DECCOLM in modes: self.resize(columns=80) self.erase_in_display(2) self.cursor_position() if mo.DECOM in modes: self.cursor_position() if mo.DECSCNM in modes: self.buffer[:] = ([char._replace(reverse=False) for char in line] for line in self.buffer) self.select_graphic_rendition(g._SGR["-reverse"]) # Hide the cursor. if mo.DECTCEM in modes: self.cursor.hidden = True def shift_in(self): """Activates ``G0`` character set.""" self.charset = 0 def shift_out(self): """Activates ``G1`` character set.""" self.charset = 1 def draw(self, char): """Display a character at the current cursor position and advance the cursor if :data:`~pyte.modes.DECAWM` is set. :param str char: a character to display. """ # Translating a given character. char = char.translate([self.g0_charset, self.g1_charset][self.charset]) # 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.carriage_return() self.linefeed() else: self.cursor.x -= 1 # 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: self.insert_characters(1) self.buffer[self.cursor.y][self.cursor.x] = self.cursor.attrs \ ._replace(data=char) # .. note:: We can't use :meth:`cursor_forward()`, because that # way, we'll never know when to linefeed. self.cursor.x += 1 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 if self.cursor.y == bottom: self.buffer.pop(top) self.buffer.insert(bottom, take(self.columns, self.default_line)) 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 if self.cursor.y == top: self.buffer.pop(bottom) self.buffer.insert(top, take(self.columns, self.default_line)) else: self.cursor_up() def linefeed(self): """Performs an index and, if :data:`~pyte.modes.LNM` is set, a carriage return. """ self.index() if mo.LNM in self.mode: self.carriage_return() self.ensure_bounds() 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 it's 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_bounds(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): """Inserts 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 delete. """ count = count or 1 top, bottom = self.margins # If cursor is outside scrolling margins it -- do nothin'. if top <= self.cursor.y <= bottom: # v +1, because range() is exclusive. for line in range(self.cursor.y, min(bottom + 1, self.cursor.y + count)): self.buffer.pop(bottom) self.buffer.insert(line, take(self.columns, self.default_line)) self.carriage_return() def delete_lines(self, count=None): """Deletes 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 # If cursor is outside scrolling margins it -- do nothin'. if top <= self.cursor.y <= bottom: # v -- +1 to include the bottom margin. for _ in range(min(bottom - self.cursor.y + 1, count)): self.buffer.pop(self.cursor.y) self.buffer.insert(bottom, list( repeat(self.cursor.attrs, self.columns))) self.carriage_return() def insert_characters(self, count=None): """Inserts 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. """ count = count or 1 for _ in range(min(self.columns - self.cursor.y, count)): self.buffer[self.cursor.y].insert(self.cursor.x, self.cursor.attrs) self.buffer[self.cursor.y].pop() def delete_characters(self, count=None): """Deletes 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. """ count = count or 1 for _ in range(min(self.columns - self.cursor.x, count)): self.buffer[self.cursor.y].pop(self.cursor.x) self.buffer[self.cursor.y].append(self.cursor.attrs) def erase_characters(self, count=None): """Erases 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. .. warning:: Even though *ALL* of the VTXXX manuals state that character attributes **should be reset to defaults**, ``libvte``, ``xterm`` and ``ROTE`` completely ignore this. Same applies too all ``erase_*()`` and ``delete_*()`` methods. """ count = count or 1 for column in range(self.cursor.x, min(self.cursor.x + count, self.columns)): self.buffer[self.cursor.y][column] = self.cursor.attrs def erase_in_line(self, type_of=0, private=False): """Erases a line in a specific way. :param int type_of: 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`` character attributes aren left unchanged **not implemented**. """ interval = ( # a) erase from the cursor to the end of line, including # the cursor, range(self.cursor.x, self.columns), # b) erase from the beginning of the line to the cursor, # including it, range(0, self.cursor.x + 1), # c) erase the entire line. range(0, self.columns) )[type_of] for column in interval: self.buffer[self.cursor.y][column] = self.cursor.attrs def erase_in_display(self, type_of=0, private=False): """Erases display in a specific way. :param int type_of: 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`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` character attributes aren left unchanged **not implemented**. """ interval = ( # a) erase from cursor to the end of the display, including # the cursor, range(self.cursor.y + 1, self.lines), # b) erase from the beginning of the display to the cursor, # including it, range(0, self.cursor.y), # c) erase the whole display. range(0, self.lines) )[type_of] for line in interval: self.buffer[line][:] = \ (self.cursor.attrs for _ in range(self.columns)) # In case of 0 or 1 we have to erase the line with the cursor. if type_of in [0, 1]: self.erase_in_line(type_of) def set_tab_stop(self): """Sest a horizontal tab stop at cursor position.""" self.tabstops.add(self.cursor.x) def clear_tab_stop(self, type_of=None): """Clears a horizontal tab stop in a specific way, depending on the ``type_of`` value: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops. """ if not type_of: # Clears a horizontal tab stop at cursor position, if it's # present, or silently fails if otherwise. self.tabstops.discard(self.cursor.x) elif type_of == 3: self.tabstops = set() # Clears all horizontal tab stops. def ensure_bounds(self, use_margins=None): """Ensure that current cursor position is within 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: top, bottom = self.margins else: top, bottom = 0, self.lines - 1 self.cursor.x = min(max(0, self.cursor.x), self.columns - 1) self.cursor.y = min(max(top, self.cursor.y), bottom) def cursor_up(self, count=None): """Moves cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip. """ self.cursor.y -= count or 1 self.ensure_bounds(use_margins=True) def cursor_up1(self, count=None): """Moves 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): """Moves cursor down the indicated # of lines in same column. Cursor stops at bottom margin. :param int count: number of lines to skip. """ self.cursor.y += count or 1 self.ensure_bounds(use_margins=True) def cursor_down1(self, count=None): """Moves 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): """Moves cursor left the indicated # of columns. Cursor stops at left margin. :param int count: number of columns to skip. """ self.cursor.x -= count or 1 self.ensure_bounds() def cursor_forward(self, count=None): """Moves 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_bounds() 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 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, self.cursor.y = column, line self.ensure_bounds() def cursor_to_column(self, column=None): """Moves 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_bounds() def cursor_to_line(self, line=None): """Moves 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_bounds() 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.""" for line in self.buffer: for column, char in enumerate(line): line[column] = char._replace(data="E") def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """ replace = {} for attr in attrs or [0]: if attr in g.FG: replace["fg"] = g.FG[attr] elif attr in g.BG: replace["bg"] = g.BG[attr] elif attr in g.TEXT: attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith("+") elif not attr: replace = self.default_char._asdict() self.cursor.attrs = self.cursor.attrs._replace(**replace) 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. .. attribute:: dirty A set of line numbers, which should be re-drawn. >>> screen = DiffScreen(80, 24) >>> screen.dirty.clear() >>> screen.draw(u"!") >>> screen.dirty set([0]) """ def __init__(self, *args): self.dirty = set() super(DiffScreen, self).__init__(*args) def set_mode(self, *modes, **kwargs): if mo.DECSCNM >> 5 in modes and kwargs.get("private"): self.dirty.update(range(self.lines)) super(DiffScreen, self).set_mode(*modes, **kwargs) def reset_mode(self, *modes, **kwargs): if mo.DECSCNM >> 5 in modes and kwargs.get("private"): self.dirty.update(range(self.lines)) super(DiffScreen, self).reset_mode(*modes, **kwargs) def reset(self): self.dirty.update(range(self.lines)) super(DiffScreen, self).reset() def resize(self, *args, **kwargs): self.dirty.update(range(self.lines)) super(DiffScreen, self).resize(*args, **kwargs) def draw(self, *args): self.dirty.add(self.cursor.y) super(DiffScreen, self).draw(*args) def index(self): if self.cursor.y == self.margins.bottom: self.dirty.update(range(self.lines)) super(DiffScreen, self).index() def reverse_index(self): if self.cursor.y == self.margins.top: self.dirty.update(range(self.lines)) super(DiffScreen, self).reverse_index() def insert_lines(self, *args): self.dirty.update(range(self.cursor.y, self.lines)) super(DiffScreen, self).insert_lines(*args) def delete_lines(self, *args): self.dirty.update(range(self.cursor.y, self.lines)) super(DiffScreen, self).delete_lines(*args) def insert_characters(self, *args): self.dirty.add(self.cursor.y) super(DiffScreen, self).insert_characters(*args) def delete_characters(self, *args): self.dirty.add(self.cursor.y) super(DiffScreen, self).delete_characters(*args) def erase_characters(self, *args): self.dirty.add(self.cursor.y) super(DiffScreen, self).erase_characters(*args) def erase_in_line(self, *args): self.dirty.add(self.cursor.y) super(DiffScreen, self).erase_in_line(*args) def erase_in_display(self, type_of=0): self.dirty.update(( range(self.cursor.y + 1, self.lines), range(0, self.cursor.y), range(0, self.lines) )[type_of]) super(DiffScreen, self).erase_in_display(type_of) def alignment_display(self): self.dirty.update(range(self.lines)) super(DiffScreen, self).alignment_display() History = namedtuple("History", "top bottom ratio size position") class HistoryScreen(DiffScreen): """A 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" """ def __init__(self, columns, lines, history=100, ratio=.5): self.history = History(deque(maxlen=history // 2), deque(maxlen=history), float(ratio), history, history) super(HistoryScreen, self).__init__(columns, lines) def __before__(self, command): """Ensures a screen is at the bottom of the history buffer.""" if command not in ["prev_page", "next_page"]: while self.history.position < self.history.size: self.next_page() super(HistoryScreen, self).__before__(command) def __after__(self, command): """Ensures all lines on a screen have proper width (:attr:`columns`). Extra characters are truncated, missing characters are filled with whitespace. """ if command in ["prev_page", "next_page"]: for idx, line in enumerate(self.buffer): if len(line) > self.columns: self.buffer[idx] = line[:self.columns] elif len(line) < self.columns: self.buffer[idx] = line + take(self.columns - len(line), self.default_line) # If we're at the bottom of the history buffer and `DECTCEM` # mode is set -- show the cursor. self.cursor.hidden = not ( abs(self.history.position - self.history.size) < self.lines and mo.DECTCEM in self.mode ) super(HistoryScreen, self).__after__(command) 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.history.top.clear() self.history.bottom.clear() self.history = self.history._replace(position=self.history.size) def index(self): """Overloaded to update top history with the removed lines.""" top, bottom = self.margins 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 if self.cursor.y == top: self.history.bottom.append(self.buffer[bottom]) super(HistoryScreen, self).reverse_index() def prev_page(self): """Moves 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(reversed(self.buffer[-mid:])) self.history = self.history \ ._replace(position=self.history.position - self.lines) self.buffer[:] = list(reversed([ self.history.top.pop() for _ in range(mid) ])) + self.buffer[:-mid] self.dirty = set(range(self.lines)) def next_page(self): """Moves 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[:mid]) self.history = self.history \ ._replace(position=self.history.position + self.lines) self.buffer[:] = self.buffer[mid:] + [ self.history.bottom.popleft() for _ in range(mid) ] self.dirty = set(range(self.lines)) pyte-0.4.8/pyte/streams.py0000644000076500000240000003154312125110401017025 0ustar superbobrystaff00000000000000# -*- 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 >>> >>> class Dummy(object): ... def __init__(self): ... self.y = 0 ... ... def cursor_up(self, count=None): ... self.y += count or 1 ... >>> dummy = Dummy() >>> stream = pyte.Stream() >>> stream.attach(dummy) >>> stream.feed(u"\u001B[5A") # Move the cursor up 5 rows. >>> dummy.y 5 :copyright: (c) 2011-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals import os import codecs import sys from . import control as ctrl, escape as esc if sys.version_info[0] == 2: str = unicode class Stream(object): """A stream is a state machine that parses a stream of characters and dispatches events based on what it sees. .. note:: Stream only accepts strings as input, but if, for some reason, you need to feed it with bytes, consider using :class:`~pyte.streams.ByteStream` instead. .. seealso:: `man console_codes `_ For details on console codes listed bellow in :attr:`basic`, :attr:`escape`, :attr:`csi` and :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.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.DECSTBM: "set_margins", esc.HPA: "cursor_to_column", } def __init__(self): self.handlers = { "stream": self._stream, "escape": self._escape, "arguments": self._arguments, "sharp": self._sharp, "charset": self._charset } self.listeners = [] self.reset() def reset(self): """Reset state to ``"stream"`` and empty parameter attributes.""" self.state = "stream" self.flags = {} self.params = [] self.current = "" def consume(self, char): """Consume a single string character and advance the state as necessary. :param str char: a character to consume. """ if not isinstance(char, str): raise TypeError("%s requires str input" % self.__class__.__name__) try: self.handlers.get(self.state)(char) except TypeError: pass except KeyError: if __debug__: self.flags["state"] = self.state self.flags["unhandled"] = char self.dispatch("debug", *self.params) self.reset() else: raise def feed(self, chars): """Consume a string and advance the state as necessary. :param str chars: a string to feed from. """ if not isinstance(chars, str): raise TypeError("%s requires str input" % self.__class__.__name__) for char in chars: self.consume(char) def attach(self, screen, only=()): """Adds a given screen to the listeners queue. :param pyte.screens.Screen screen: a screen to attach to. :param list only: a list of events you want to dispatch to a given screen (empty by default, which means -- dispatch all events). """ self.listeners.append((screen, set(only))) def detach(self, screen): """Removes a given screen from the listeners queue and failes silently if it's not attached. :param pyte.screens.Screen screen: a screen to detach. """ for idx, (listener, _) in enumerate(self.listeners): if screen is listener: self.listeners.pop(idx) def dispatch(self, event, *args, **kwargs): """Dispatch an event. Event handlers are looked up implicitly in the listeners' ``__dict__``, so, if a listener only wants to handle ``DRAW`` events it should define a ``draw()`` method or pass ``only=["draw"]`` argument to :meth:`attach`. .. warning:: If any of the attached listeners throws an exception, the subsequent callbacks are be aborted. :param str event: event to dispatch. :param list args: arguments to pass to event handlers. """ for listener, only in self.listeners: if only and event not in only: continue try: handler = getattr(listener, event) except AttributeError: continue if hasattr(listener, "__before__"): listener.__before__(event) handler(*args, **self.flags) if hasattr(listener, "__after__"): listener.__after__(event) else: if kwargs.get("reset", True): self.reset() # State transformers. # ................... def _stream(self, char): """Process a character when in the default ``"stream"`` state.""" if char in self.basic: self.dispatch(self.basic[char]) elif char == ctrl.ESC: self.state = "escape" elif char == ctrl.CSI: self.state = "arguments" elif char not in [ctrl.NUL, ctrl.DEL]: self.dispatch("draw", char) def _escape(self, char): """Handle characters seen when in an escape sequence. 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. """ if char == "#": self.state = "sharp" elif char == "[": self.state = "arguments" elif char in "()": self.state = "charset" self.flags["mode"] = char else: self.dispatch(self.escape[char]) def _sharp(self, char): """Parse arguments of a `"#"` seqence.""" self.dispatch(self.sharp[char]) def _charset(self, char): """Parse ``G0`` or ``G1`` charset code.""" self.dispatch("set_charset", char) def _arguments(self, char): """Parse arguments of an escape sequence. 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 Reference `_ For details on the characters valid for use as arguments. """ if char == "?": self.flags["private"] = True elif char in [ctrl.BEL, ctrl.BS, ctrl.HT, ctrl.LF, ctrl.VT, ctrl.FF, ctrl.CR]: # Not sure why, but those seem to be allowed between CSI # sequence arguments. self.dispatch(self.basic[char], reset=False) elif char == ctrl.SP: pass elif char in [ctrl.CAN, ctrl.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. self.dispatch("draw", char) self.state = "stream" elif char.isdigit(): self.current += char else: self.params.append(min(int(self.current or 0), 9999)) if char == ";": self.current = "" else: self.dispatch(self.csi[char], *self.params) class ByteStream(Stream): """A stream, which takes bytes (instead of strings) as input and tries to decode them using a given list of possible encodings. It uses :class:`codecs.IncrementalDecoder` internally, so broken bytes is not an issue. By default, the following decoding strategy is used: * First, try strict ``"utf-8"``, proceed if recieved and :exc:`UnicodeDecodeError` ... * Try strict ``"cp437"``, failed? move on ... * Use ``"utf-8"`` with invalid bytes replaced -- this one will allways succeed. >>> stream = ByteStream() >>> stream.feed(b"foo".decode("utf-8")) Traceback (most recent call last): File "", line 1, in File "pyte/streams.py", line 323, in feed "%s requires input in bytes" % self.__class__.__name__) TypeError: ByteStream requires input in bytes >>> stream.feed(b"foo") :param list encodings: a list of ``(encoding, errors)`` pairs, where the first element is encoding name, ex: ``"utf-8"`` and second defines how decoding errors should be handeld; see :meth:`str.decode` for possible values. """ def __init__(self, encodings=None): encodings = encodings or [ ("utf-8", "strict"), ("cp437", "strict"), ("utf-8", "replace") ] self.buffer = b"", 0 self.decoders = [codecs.getincrementaldecoder(encoding)(errors) for encoding, errors in encodings] super(ByteStream, self).__init__() def feed(self, chars): if not isinstance(chars, bytes): raise TypeError( "%s requires input in bytes" % self.__class__.__name__) for decoder in self.decoders: decoder.setstate(self.buffer) try: chars = decoder.decode(chars) except UnicodeDecodeError: continue self.buffer = decoder.getstate() return super(ByteStream, self).feed(chars) else: raise class DebugStream(ByteStream): """Stream, which dumps a subset of the dispatched events to a given file-like object (:data:`sys.stdout` by default). >>> stream = DebugStream() >>> stream.feed("\x1b[1;24r\x1b[4l\x1b[24;1H\x1b[0;10m") 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). """ def __init__(self, to=sys.stdout, only=(), *args, **kwargs): super(DebugStream, self).__init__(*args, **kwargs) def safe_str(chunk): if isinstance(chunk, bytes): chunk = chunk.decode("utf-8") elif not isinstance(chunk, str): chunk = str(chunk) return chunk class Bugger(object): __before__ = __after__ = lambda *args: None def __getattr__(self, event): def inner(*args, **flags): to.write(event.upper() + " ") to.write("; ".join(map(safe_str, args))) to.write(" ") to.write(", ".join("{0}: {1}".format(name, safe_str(arg)) for name, arg in flags.items())) to.write(os.linesep) return inner self.attach(Bugger(), only=only) pyte-0.4.8/pyte.egg-info/0000755000076500000240000000000012264723152016502 5ustar superbobrystaff00000000000000pyte-0.4.8/pyte.egg-info/dependency_links.txt0000644000076500000240000000000112264723152022550 0ustar superbobrystaff00000000000000 pyte-0.4.8/pyte.egg-info/PKG-INFO0000644000076500000240000000615212264723152017603 0ustar superbobrystaff00000000000000Metadata-Version: 1.1 Name: pyte Version: 0.4.8 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.4.8 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 `setuptools `_ you can use ``easy_install -U pyte``. Otherwise, you can 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 Library or Lesser General Public License (LGPL) Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Topic :: Terminals :: Terminal Emulators/X Terminals pyte-0.4.8/pyte.egg-info/SOURCES.txt0000644000076500000240000000107312264723152020367 0ustar superbobrystaff00000000000000AUTHORS CHANGES LICENSE MANIFEST.in README setup.py docs/api.rst docs/changelog.rst docs/conf.py docs/index.rst docs/tutorial.rst docs/_static/rtd.css examples/debug.py examples/helloworld.py examples/inception.py pyte/__init__.py pyte/__main__.py pyte/charsets.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/top_level.txt tests/__init__.py tests/test_diff.py tests/test_history.py tests/test_screen.py tests/test_stream.pypyte-0.4.8/pyte.egg-info/top_level.txt0000644000076500000240000000000512264723152021227 0ustar superbobrystaff00000000000000pyte pyte-0.4.8/README0000644000076500000240000000365512264723075014724 0ustar superbobrystaff00000000000000.. -*- mode: rst -*- :: _ | | _ __ _ _ | |_ ___ | '_ \ | | | || __|/ _ \ | |_) || |_| || |_| __/ | .__/ \__, | \__|\___| | | __/ | |_| |___/ 0.4.8 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 `setuptools `_ you can use ``easy_install -U pyte``. Otherwise, you can 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.4.8/setup.cfg0000644000076500000240000000007312264723152015650 0ustar superbobrystaff00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pyte-0.4.8/setup.py0000755000076500000240000000327412264723075015556 0ustar superbobrystaff00000000000000#! /usr/bin/env python # -*- coding: utf-8 -*- import os import sys from setuptools import setup from setuptools.command.test import test as TestCommand 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 Library or Lesser General Public License (LGPL)", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Terminals :: Terminal Emulators/X Terminals", ) class PyTest(TestCommand): """Unfortunately :mod:`setuptools` support only :mod:`unittest` based tests, thus, we have to overider build-in ``test`` command to run :mod:`pytest`. """ def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest sys.exit(pytest.main(self.test_args + ["./tests"])) setup(name="pyte", version="0.4.8", packages=["pyte"], cmdclass={"test": PyTest}, 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.4.8/tests/0000755000076500000240000000000012264723152015171 5ustar superbobrystaff00000000000000pyte-0.4.8/tests/__init__.py0000644000076500000240000000326512047255265017314 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- from collections import defaultdict from pyte import Stream, ByteStream class TestMixin(object): """A mixin which allows explicit subscription to a subset of events.""" def connect(self, event, callback): """Add an event listener for a particular event. Depending on the event, there may or may not be parameters passed to the callback. Some escape sequences might also have default values, but providing these defaults is responsibility of the callback. :param unicode event: event to listen for. :param callable callback: callable to invoke when a given event occurs. """ self.listeners[event].append(callback) def dispatch(self, event, *args, **kwargs): """Dispatch an event. .. note:: If any callback throws an exception, the subsequent callbacks are be aborted. :param unicode event: event to dispatch. :param bool reset: reset stream state after all callback are executed. :param list args: arguments to pass to event handlers. """ for callback in self.listeners.get(event, []): callback(*args, **self.flags) else: if kwargs.get("reset", True): self.reset() class TestStream(TestMixin, Stream): def __init__(self, *args, **kwargs): Stream.__init__(self, *args, **kwargs) self.listeners = defaultdict(lambda: []) class TestByteStream(TestMixin, ByteStream): def __init__(self, *args, **kwargs): ByteStream.__init__(self, *args, **kwargs) self.listeners = defaultdict(lambda: []) pyte-0.4.8/tests/test_diff.py0000644000076500000240000000633612047255265017526 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals from pyte import DiffScreen, 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 = 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() 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 = DiffScreen(80, 24) # a) draw(). screen.dirty.clear() screen.draw("f") assert len(screen.dirty) is 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) is 1 assert screen.cursor.y in screen.dirty def test_modes(): # Making sure `DECSCNM` triggers a screen to be fully re-drawn. screen = 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 = 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 = 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 = 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 = 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)) pyte-0.4.8/tests/test_history.py0000644000076500000240000003002212264723075020304 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import operator import os import sys if sys.version_info[0] == 2: from future_builtins import map str = unicode from pyte import HistoryScreen, Stream, ctrl, modes as mo def chars(lines): return ["".join(map(operator.attrgetter("data"), line)) for line in lines] def test_index(): screen = 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 is not len(screen.buffer) - 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(len(screen.buffer) * screen.lines): screen.index() assert len(screen.history.top) == 25 # pages // 2 * lines def test_reverse_index(): screen = 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 is not 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 = 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(len(screen.buffer) * 10): for ch in str(idx): screen.draw(ch) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 40 assert len(screen.buffer) == screen.lines assert screen.display == [ "37 ", "38 ", "39 ", " " ] assert chars(screen.history.top)[-4:] == [ "33 ", "34 ", "35 ", "36 " ] # a) first page up. screen.prev_page() assert screen.history.position == 36 assert len(screen.buffer) == screen.lines assert screen.display == [ "35 ", "36 ", "37 ", "38 " ] assert chars(screen.history.top)[-4:] == [ "31 ", "32 ", "33 ", "34 " ] assert len(screen.history.bottom) == 2 assert chars(screen.history.bottom) == [ "39 ", " ", ] # b) second page up. screen.prev_page() assert screen.history.position == 32 assert len(screen.buffer) == screen.lines assert screen.display == [ "33 ", "34 ", "35 ", "36 ", ] assert len(screen.history.bottom) == 4 assert chars(screen.history.bottom) == [ "37 ", "38 ", "39 ", " ", ] # c) same with odd number of lines. screen = HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(len(screen.buffer) * 10): for ch in str(idx): screen.draw(ch) 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 == 45 assert len(screen.buffer) == screen.lines assert screen.display == [ "43 ", "44 ", "45 ", "46 ", "47 " ] assert len(screen.history.bottom) == 3 assert chars(screen.history.bottom) == [ "48 ", "49 ", " ", ] # d) same with cursor in the middle of the screen. screen = HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(len(screen.buffer) * 10): for ch in str(idx): screen.draw(ch) 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 == [ "21 ", "22 ", "23 ", "24 ", "25 " ] 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 ", " " ] # e) same with cursor near the middle of the screen. screen = HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(len(screen.buffer) * 10): for ch in str(idx): screen.draw(ch) 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 == [ "21 ", "22 ", "23 ", "24 ", "25 " ] 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 = 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(len(screen.buffer) * 5): for ch in str(idx): screen.draw(ch) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert len(screen.buffer) == screen.lines 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 == 45 assert screen.history.top assert chars(screen.history.bottom) == [ "23 ", "24 ", " " ] assert len(screen.buffer) == screen.lines 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 == 45 assert len(screen.buffer) == screen.lines assert screen.display == [ "18 ", "19 ", "20 ", "21 ", "22 " ] def test_ensure_width(): screen = HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) stream = Stream() stream.attach(screen) stream.escape["N"] = "next_page" stream.escape["P"] = "prev_page" for idx in range(len(screen.buffer) * 5): for ch in str(idx) + os.linesep: stream.feed(ch) assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ] # a) shrinking the screen, expecting the lines displayed to # be truncated. screen.resize(5, 2) stream.feed(ctrl.ESC + "P") assert all(len(l) is not 2 for l in screen.history.top) assert all(len(l) is 2 for l in screen.history.bottom) assert screen.display == [ "18", "19", "20", "21", "22" ] # b) expading the screen, expecting the lines displayed to # be filled with whitespace characters. screen.resize(5, 10) stream.feed(ctrl.ESC + "N") assert all(len(l) is 10 for l in list(screen.history.top)[-3:]) assert all(len(l) is not 10 for l in screen.history.bottom) assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ] def test_not_enough_lines(): screen = HistoryScreen(5, 5, history=6) screen.set_mode(mo.LNM) for idx in range(len(screen.buffer)): for ch in str(idx): screen.draw(ch) 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) == [" "] 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(): screen = HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) stream = Stream() stream.attach(screen) stream.escape["N"] = "next_page" stream.escape["P"] = "prev_page" for idx in range(len(screen.buffer) * 5): for ch in str(idx) + os.linesep: stream.feed(ch) 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(): screen = HistoryScreen(5, 5, history=50) stream = Stream() stream.attach(screen) stream.escape["N"] = "next_page" stream.escape["P"] = "prev_page" for idx in range(len(screen.buffer) * 5): for ch in str(idx) + os.linesep: stream.feed(ch) 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 pyte-0.4.8/tests/test_screen.py0000644000076500000240000010600312264723075020065 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import copy import sys if sys.version_info[0] == 2: from future_builtins import map str = unicode import pytest from pyte import Screen, Stream, mo 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 # Tests. def test_remove_non_existant_attribute(): screen = Screen(2, 2) assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(24) # underline-off. assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 assert not screen.cursor.attrs.underscore def test_attributes(): screen = Screen(2, 2) assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(1) # Bold # Still default, since we haven't written anything. assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 assert screen.cursor.attrs.bold screen.draw("f") assert screen.buffer == [ [Char("f", "default", "default", bold=True), screen.default_char], [screen.default_char, screen.default_char] ] def test_colors(): screen = Screen(2, 2) assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(30) # black foreground screen.select_graphic_rendition(40) # black background assert screen.cursor.attrs.fg == "black" assert screen.cursor.attrs.bg == "black" screen.select_graphic_rendition(31) # red foreground assert screen.cursor.attrs.fg == "red" assert screen.cursor.attrs.bg == "black" def test_reset_resets_colors(): screen = Screen(2, 2) assert screen.buffer == [[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_multi_attribs(): screen = Screen(2, 2) assert screen.buffer == [[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 = Screen(2, 2) screen.set_mode(mo.LNM) assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(1) screen.draw("f") screen.draw("o") screen.draw("o") assert screen.buffer == [ [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 screen.buffer == [ [Char("f"), Char("o", bold=True)], [Char("o", bold=True), screen.default_char ], ] def test_resize(): screen = Screen(2, 2) screen.set_mode(mo.DECOM) screen.set_margins(0, 1) assert screen.size == (2, 2) assert screen.columns == 2 assert len(screen.buffer[0]) == 2 assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 screen.resize(3, 3) assert screen.size == (3, 3) assert len(screen.buffer) == 3 assert len(screen.buffer[0]) == 3 assert screen.buffer == [[screen.default_char, screen.default_char, screen.default_char]] * 3 assert mo.DECOM not in screen.mode assert screen.margins == (0, 2) screen.resize(2, 2) assert screen.size == (2, 2) assert len(screen.buffer) == 2 assert len(screen.buffer[0]) == 2 assert screen.buffer == [[screen.default_char, screen.default_char]] * 2 # quirks: # a) if the current display is thinner than the requested size, # new columns should be added to the right. screen = update(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(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(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(Screen(2, 2), ["bo", "sh"], [None, None]) screen.resize(1, 2) assert screen.display == ["sh"] def test_draw(): # ``DECAWM`` on (default). screen = 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 = 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_carriage_return(): screen = Screen(3, 3) screen.cursor.x = 2 screen.carriage_return() assert screen.cursor.x == 0 def test_index(): screen = update(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 screen.buffer == [ [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 screen.buffer == [ [Char("o", fg="red"), Char("t", fg="red")], [screen.default_char, screen.default_char] ] # c) same with margins screen = update(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 screen.buffer == [ [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 screen.buffer == [ [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 screen.buffer == [ [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 screen.buffer == [ [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(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 screen.buffer == [ [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 screen.buffer == [ [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], ] # c) same with margins screen = update(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 screen.buffer == [ [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 screen.buffer == [ [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 screen.buffer == [ [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 screen.buffer == [ [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(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_tabstops(): screen = Screen(10, 10) # Making sure initial tabstops are in place ... assert screen.tabstops == set([7]) # ... 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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(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 screen.buffer == [ [screen.default_char] * 3, [Char("s"), Char("a"), Char("m")], [Char("i", fg="red"), Char("s", fg="red"), Char(" ", fg="red")], ] screen = update(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 screen.buffer == [ [screen.default_char] * 3, [screen.default_char] * 3, [Char("s"), Char("a"), Char("m")] ] # b) with margins screen = update(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 screen.buffer == [ [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(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 screen.buffer == [ [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 screen.buffer == [ [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(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 screen.buffer == [ [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(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 screen.buffer == [ [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(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 screen.buffer == [ [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 screen.buffer == [ [Char("f"), Char("o"), Char("o")], [screen.default_char] * 3, [screen.default_char] * 3, ] # b) with margins screen = update(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 screen.buffer == [ [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(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 screen.buffer == [ [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(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 screen.buffer == [ [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(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 screen.buffer == [ [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(Screen(3, 3), ["sam", "is ", "foo"], 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 screen.buffer[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 screen.buffer[2] == [Char("f"), screen.default_char, Char("o")] # c) inserting more than we have screen.insert_characters(10) assert screen.buffer[2] == [Char("f"), screen.default_char, screen.default_char] # d) 0 is 1 screen = update(Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.cursor_position() screen.insert_characters() assert screen.buffer[0] == [ screen.default_char, Char("s", fg="red"), Char("a", fg="red") ] screen = update(Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.cursor_position() screen.insert_characters(1) assert screen.buffer[0] == [ screen.default_char, Char("s", fg="red"), Char("a", fg="red") ] def test_delete_characters(): screen = update(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 screen.buffer[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(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 screen.buffer[0] == [ Char("1", fg="red"), Char("5", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(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 screen.buffer[0] == [ Char("1", fg="red"), Char("2", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(Screen(5, 1), ["12345"], colored=[0]) screen.delete_characters(4) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["5 "] assert screen.buffer[0] == [ Char("5", fg="red"), screen.default_char, screen.default_char, screen.default_char, screen.default_char ] def test_erase_character(): screen = update(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 screen.buffer[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(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 screen.buffer[0] == [ Char("1", fg="red"), screen.default_char, screen.default_char, screen.default_char, Char("5", "red") ] screen = update(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 screen.buffer[0] == [ Char("1", fg="red"), Char("2", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(Screen(5, 1), ["12345"], colored=[0]) screen.erase_characters(4) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == [" 5"] assert screen.buffer[0] == [ screen.default_char, screen.default_char, screen.default_char, screen.default_char, Char("5", fg="red") ] def test_erase_in_line(): screen = update(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 screen.buffer[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 screen.buffer[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 screen.buffer[0] == [screen.default_char] * 5 def test_erase_in_display(): screen = update(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 screen.buffer[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 screen.buffer[: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 screen.buffer == [[screen.default_char] * 5] * 5 def test_cursor_up(): screen = 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 = 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 = 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_forward(): screen = 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 = 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 = Screen(4, 2) stream = Stream() stream.attach(screen) try: stream.feed("тест") except UnicodeDecodeError: pytest.fail("Check your code -- we do accept unicode.") assert screen.display == ["тест", " "] def test_alignment_display(): screen = 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 = Screen(10, 10) assert screen.margins == (0, 9) # 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 screen.set_margins() assert screen.margins != (None, None) assert screen.margins == (0, 4) def test_hide_cursor(): screen = 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 pyte-0.4.8/tests/test_stream.py0000644000076500000240000001232712125110401020061 0ustar superbobrystaff00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import operator import sys if sys.version_info[0] == 2: from cStringIO import StringIO else: from io import StringIO import pytest from pyte import ctrl, esc from pyte.streams import DebugStream from . import TestStream, TestByteStream class counter(object): def __init__(self): self.count = 0 def __call__(self, *args): 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(): stream = TestStream() for cmd, event in stream.escape.items(): handler = counter() stream.connect(event, handler) stream.consume(ctrl.ESC) assert stream.state == "escape" assert not handler.count stream.consume(cmd) assert stream.state == "stream" assert handler.count == 1 # ``linefeed``s is somewhat an exception, there's three ways to # trigger it. handler = counter() stream.connect("linefeed", handler) stream.feed(ctrl.LF + ctrl.VT + ctrl.FF) assert handler.count == 3 assert stream.state == "stream" def test_unknown_sequences(): handler = argcheck() stream = TestStream() stream.connect("debug", handler) try: stream.feed(ctrl.CSI + "6;Z") except Exception as e: pytest.fail("No exception should've raised, got: %s" % e) else: assert handler.count == 1 assert handler.args == (6, 0) assert handler.kwargs == {"unhandled": "Z", "state": "arguments"} def test_non_csi_sequences(): stream = TestStream() for cmd, event in stream.csi.items(): # a) single param handler = argcheck() stream.connect(event, handler) stream.consume(ctrl.ESC) assert stream.state == "escape" stream.consume("[") assert stream.state == "arguments" stream.consume("5") stream.consume(cmd) assert handler.count == 1 assert handler.args == (5, ) assert stream.state == "stream" # b) multiple params, and starts with CSI, not ESC [ handler = argcheck() stream.connect(event, handler) stream.consume(ctrl.CSI) assert stream.state == "arguments" stream.consume("5") stream.consume(";") stream.consume("12") stream.consume(cmd) assert handler.count == 1 assert handler.args == (5, 12) assert stream.state == "stream" def test_mode_csi_sequences(): bugger = counter() stream = TestStream() stream.connect("debug", bugger) # a) set_mode handler = argcheck() stream.connect("set_mode", handler) stream.feed(ctrl.CSI + "?9;2h") assert not bugger.count assert handler.count == 1 assert handler.args == (9, 2) assert handler.kwargs == {"private": True} # a) reset_mode handler = argcheck() stream.connect("reset_mode", handler) stream.feed(ctrl.CSI + "?9;2l") assert not bugger.count assert handler.count == 1 assert handler.args == (9, 2) def test_byte_stream(): def validator(char): assert "\ufffd" not in char stream = TestByteStream(encodings=[("utf_8", "replace")]) stream.connect("draw", validator) for byte in "Garðabær".encode("utf_8"): if sys.version_info[0] == 3: # HACK(Sergei): in Python 3 a _byte_ is just an `int``, while # in Python 2 it's an instance of `str``. byte = bytes([byte]) stream.feed(byte) def test_missing_params(): handler = argcheck() stream = TestStream() stream.connect("cursor_position", handler) stream.feed(ctrl.CSI + ";" + esc.HVP) assert handler.count == 1 assert handler.args == (0, 0) def test_overflow(): handler = argcheck() stream = TestStream() stream.connect("cursor_position", handler) stream.feed(ctrl.CSI + "999999999999999;99999999999999" + esc.HVP) assert handler.count == 1 assert handler.args == (9999, 9999) def test_interrupt(): bugger, handler = argstore(), argcheck() stream = TestStream() stream.connect("draw", bugger) stream.connect("cursor_position", handler) stream.feed(ctrl.CSI + "10;" + ctrl.SUB + "10" + esc.HVP) assert not handler.count assert bugger.seen == [ ctrl.SUB, "1", "0", esc.HVP ] def test_control_characters(): handler = argcheck() stream = TestStream() stream.connect("cursor_position", handler) stream.feed(ctrl.CSI + "10;\t\t\n\r\n10" + esc.HVP) assert handler.count == 1 assert handler.args == (10, 10) def test_debug_stream(): tests = [ (b"foo", "DRAW f\nDRAW o\nDRAW o"), (b"\x1b[1;24r\x1b[4l\x1b[24;1H", "SET_MARGINS 1; 24\nRESET_MODE 4\nCURSOR_POSITION 24; 1"), ] for input, expected in tests: output = StringIO() stream = DebugStream(to=output) stream.feed(input) lines = [l.rstrip() for l in output.getvalue().splitlines()] assert lines == expected.splitlines()