mirror of
https://github.com/joouha/euporie.git
synced 2021-05-12 23:12:12 +03:00
Initial commit
This commit is contained in:
276
.gitignore
vendored
Normal file
276
.gitignore
vendored
Normal file
@@ -0,0 +1,276 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
31
.pre-commit-config.yaml
Normal file
31
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,31 @@
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.4.0
|
||||
hooks:
|
||||
- id: fix-byte-order-marker
|
||||
- id: fix-encoding-pragma
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v2.2.1
|
||||
hooks:
|
||||
- id: prettier
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: isort
|
||||
name: isort
|
||||
entry: poetry run isort
|
||||
args: ["--profile", "black", "--filter-files"]
|
||||
language: system
|
||||
types: [python]
|
||||
- id: black
|
||||
name: black
|
||||
entry: poetry run black
|
||||
language: system
|
||||
types: [python]
|
||||
- id: flake8
|
||||
name: flake8
|
||||
entry: poetry run flake8
|
||||
language: system
|
||||
types: [python]
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
182
README.md
Normal file
182
README.md
Normal file
@@ -0,0 +1,182 @@
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550683-79526700-b039-11eb-8a83-1828c6ee8125.png" alt="screenshot 1" width="50%" align="right" />
|
||||
|
||||
# Euporie
|
||||
|
||||
# About
|
||||
|
||||
Euporie is a text-based user interface for running and editing Jupyter notebooks.
|
||||
|
||||
# Install
|
||||
|
||||
Euporie is on pypi, so can be installed using pip:
|
||||
|
||||
```bash
|
||||
pip install euporie
|
||||
```
|
||||
|
||||
If you are using Windows, you may wish to install some optional python dependencies to render images and HTML tables:
|
||||
|
||||
```bash
|
||||
pip install euporie[tables,images]
|
||||
```
|
||||
|
||||
# Screenshots
|
||||
|
||||
<p align="center">
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550685-7a839400-b039-11eb-98ac-8adb9ea2cfc3.png" alt="screenshot 2" width="19%" />
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550686-7a839400-b039-11eb-8c6f-65c3cedf2f25.png" alt="screenshot 3" width="19%" />
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550687-7b1c2a80-b039-11eb-867b-d5e9d8671495.png" alt="screenshot 4" width="19%" />
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550688-7bb4c100-b039-11eb-9419-a10c8c0f9b21.png" alt="screenshot 5" width="19%" />
|
||||
<img src="https://user-images.githubusercontent.com/12154190/117550689-7bb4c100-b039-11eb-9d90-44df4c0e0f03.png" alt="screenshot 6" width="19%" />
|
||||
</p>
|
||||
|
||||
# Features
|
||||
|
||||
- Execute notebooks in the terminal
|
||||
- Autocompletion in code cells
|
||||
- Rich output support, including:
|
||||
- Markdown
|
||||
- Tables
|
||||
- Images
|
||||
- Open multiple notebooks side-by-side
|
||||
- Good performance with large notebook files
|
||||
|
||||
## Image Support
|
||||
|
||||
Euporie will attempt to render images in the best possible way it can. The following methods are supported:
|
||||
|
||||
- **Sixel**
|
||||
|
||||
If supported by your teminal, euporie can show graphical images in cell outputs
|
||||
This requires one of the following:
|
||||
|
||||
[`imagemagik`](https://www.imagemagick.org)
|
||||
[`timg`](https://github.com/adzierzanowski/timg)
|
||||
[`teimpy`](https://github.com/ar90n/teimpy)
|
||||
|
||||
- **Kitty's terminal image protocal**
|
||||
|
||||
If your terminal supports [kitty's terminal graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol.html), euporie will use it to render images
|
||||
|
||||
- **Ansi art**
|
||||
|
||||
This requires one of the following:
|
||||
|
||||
[`timg`](https://github.com/hzeller/timg)
|
||||
[`catimg`](https://github.com/posva/catimg)
|
||||
[`icat`](https://github.com/atextor/icat)
|
||||
[`timg`](https://github.com/adzierzanowski/timg)
|
||||
[`tiv`](https://github.com/radare/tiv)
|
||||
[`viu`](https://github.com/atanunq/viu)
|
||||
[`img2unicode`](https://github.com/matrach/img2unicode)
|
||||
[`jp2a`](https://csl.name/jp2a/)
|
||||
[`img2txt`](http://caca.zoy.org/wiki/libcaca)
|
||||
|
||||
The kitty & sixel image rendering methods will fall back to ansi art images when rendering images in partially obscured cells, to prevent clipped images destroying the user interface.
|
||||
|
||||
For SVG support, [`cairosvg`](https://cairosvg.org/) or [`imagemagik`](https://www.imagemagick.org) are required.
|
||||
|
||||
## HTML Support
|
||||
|
||||
Euporie will attempt to render HTML outputs. This requires one of the following:
|
||||
|
||||
[`w3m`](http://w3m.sourceforge.net/)
|
||||
[`elinks`](http://elinks.or.cz/)
|
||||
[`lynx`](https://lynx.browser.org/)
|
||||
[`links`](http://links.twibright.com/)
|
||||
[`mtable`](https://github.com/liuyug/mtable)
|
||||
|
||||
_Note: only HTML tables will be displayed if `mtable` is used_
|
||||
|
||||
If none of these commands are found in your `$PATH`, the plain text representation will be used.
|
||||
|
||||
## Key Bindings
|
||||
|
||||
| Command | Key Binding |
|
||||
| ------------------------------- | ----------------------------------------- |
|
||||
| Quit | `Ctrl + q` |
|
||||
| Close notebook | `Ctrl + w` |
|
||||
| Select next cell | `Up`, `k` |
|
||||
| Select previous cell | `Down`, `j` |
|
||||
| Page up (move up 5 cells) | `Pgup` |
|
||||
| Page down (move down 5 cells) | `PgDown` |
|
||||
| Scroll up | `[` |
|
||||
| Scroll down | `]` |
|
||||
| Enter edit mode | `Enter` |
|
||||
| Exit edit mode | `Esc`\*, `Esc, Esc` |
|
||||
| Edit cell in `$EDITOR` | `e` |
|
||||
| Run cell | `Ctrl + Enter`\*\*, `Ctrl + Space`, `F20` |
|
||||
| Run cell and select next cell | `Shift + Enter`\*\*, `F21` |
|
||||
| Insert cell above selected cell | `a` |
|
||||
| Insert cell below selected cell | `b` |
|
||||
| Toggle line numbers | `l` |
|
||||
| Copy cell | `c` |
|
||||
| Cut cell | `x` |
|
||||
| Paste cell | `v` |
|
||||
| Delete cell | `dd` |
|
||||
|
||||
> \* There is a slight delay detecting an escape key-event. To exit edit mode quickly, double-press the escape key.
|
||||
>
|
||||
> \*\* These entries require key remapping in your terminal in order to work - see below).
|
||||
|
||||
When in edit mode, emacs style key-bindings apply.
|
||||
|
||||
### Key Remapping
|
||||
|
||||
By default, VT100 terminal emulators do not distinguish between `Enter`, `Ctrl + Enter` & `Shift + Enter`. In order to work around this, it is possible to re-map these key bindings so they produce the escape code of another key. To replicate the `Ctrl + Enter` & `Shift + Enter` of Jupyter, you will need to remap the following shortcuts in your terminal:
|
||||
|
||||
| Key Combination | Output |
|
||||
| --------------- | ------------ |
|
||||
| `Ctrl + Enter` | `Ctrl + F20` |
|
||||
| `Shift + Enter` | `F21` |
|
||||
|
||||
#### xterm
|
||||
|
||||
Add the following to your `~/.Xresources`
|
||||
|
||||
```
|
||||
*.vt100.translations: #override \n\
|
||||
Ctrl <Key>Return: string("\033\[19;6~") \n\
|
||||
Shift <Key>Return: string("\033\[20;2~") \n\
|
||||
```
|
||||
|
||||
#### konsole
|
||||
|
||||
In the menu, navigate to:
|
||||
|
||||
`Settings` -> `Edit Current Profile` -> `Keyboard` -> `Edit`
|
||||
|
||||
Change the existing entry for `Return+Shift` to `Return+Shift+Ctrl` (or whatever you prefer), then add the following entries:
|
||||
|
||||
| Key combination | Output |
|
||||
| --------------- | ----------- |
|
||||
| `Return+Ctrl` | `\E\[19;6~` |
|
||||
| `Return+Shift` | `\E\[20;2~` |
|
||||
|
||||
# Roadmap
|
||||
|
||||
- Add a configuration file to expose configurable settings
|
||||
- Add ability to dump formatted notebooks
|
||||
- Add command line argument parsing
|
||||
- Render outputs asynchronously in a separate thread
|
||||
- Cell attachements
|
||||
- LaTeX
|
||||
- Widgets
|
||||
|
||||
# Related projects
|
||||
|
||||
- https://github.com/davidbrochart/nbterm
|
||||
|
||||
An alternative effort sponsored by QuantStack
|
||||
|
||||
- https://github.com/chentau/nbtui
|
||||
|
||||
A cli Jupyter notebook viewer with support for kitty's terminal graphics protocol
|
||||
|
||||
- https://github.com/mosiman/jupytui
|
||||
|
||||
A cli Jupyter notebook viewer
|
||||
|
||||
- https://kracekumar.com/post/jut/
|
||||
|
||||
Another cli Jupyter notebook viewer
|
||||
9
euporie/__init__.py
Normal file
9
euporie/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
|
||||
__version__ = "0.1.1"
|
||||
|
||||
if os.name == "nt":
|
||||
logo = "⚈"
|
||||
else:
|
||||
logo = "\ufe0f🟠⃘"
|
||||
5
euporie/__main__.py
Normal file
5
euporie/__main__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from .app import App
|
||||
|
||||
if __name__ == "__main__":
|
||||
App.launch()
|
||||
130
euporie/ansi.py
Normal file
130
euporie/ansi.py
Normal file
@@ -0,0 +1,130 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import Generator
|
||||
|
||||
from prompt_toolkit.formatted_text import ANSI as PTANSI
|
||||
|
||||
|
||||
class ANSI(PTANSI):
|
||||
"""
|
||||
Converts ANSI text into formatted text, preserving all control sequences.
|
||||
"""
|
||||
|
||||
def _parse_corot(self) -> Generator[None, str, None]:
|
||||
"""
|
||||
Coroutine that parses the ANSI escape sequences.
|
||||
|
||||
This is modified version of the ANSI parser from prompt_toolkit retains
|
||||
all CSI escape sequences.
|
||||
"""
|
||||
style = ""
|
||||
formatted_text = self._formatted_text
|
||||
|
||||
while True:
|
||||
|
||||
char = yield
|
||||
sequence = char
|
||||
|
||||
# Everything between \001 and \002 should become a ZeroWidthEscape.
|
||||
if char == "\001":
|
||||
sequence = ""
|
||||
while char != "\002":
|
||||
char = yield
|
||||
if char == "\002":
|
||||
formatted_text.append(("[ZeroWidthEscape]", sequence))
|
||||
break
|
||||
else:
|
||||
sequence += char
|
||||
continue
|
||||
|
||||
elif char in ("\x1b", "\x9b"):
|
||||
|
||||
# Got a CSI sequence, try to compile a control sequence
|
||||
char = yield
|
||||
|
||||
# Check for sixels
|
||||
if char == "P":
|
||||
# Got as DEC code
|
||||
sequence += char
|
||||
# We expect "p1;p2;p3;q" + sixel data + "\x1b\"
|
||||
char = yield
|
||||
while char != "\x1b":
|
||||
sequence += char
|
||||
char = yield
|
||||
sequence += char
|
||||
char = yield
|
||||
if ord(char) == 0x5C:
|
||||
sequence += char
|
||||
formatted_text.append(("[ZeroWidthEscape]", sequence))
|
||||
# char = yield
|
||||
continue
|
||||
|
||||
elif (char == "[" and sequence == "\x1b") or sequence == "\x9b":
|
||||
if sequence == "\x1b":
|
||||
sequence += char
|
||||
char = yield
|
||||
|
||||
# Next are any number (including none) of "parameter bytes"
|
||||
params = []
|
||||
current = ""
|
||||
while 0x30 <= ord(char) <= 0x3F:
|
||||
# Parse list of integer parameters
|
||||
sequence += char
|
||||
if char.isdigit():
|
||||
current += char
|
||||
else:
|
||||
params.append(min(int(current or 0), 9999))
|
||||
if char == ";":
|
||||
current = ""
|
||||
char = yield
|
||||
if current:
|
||||
params.append(min(int(current or 0), 9999))
|
||||
# then any number of "intermediate bytes"
|
||||
while 0x20 <= ord(char) <= 0x2F:
|
||||
sequence += char
|
||||
char = yield
|
||||
# finally by a single "final byte"
|
||||
if 0x40 <= ord(char) <= 0x7E:
|
||||
sequence += char
|
||||
# Check if that escape sequence was a style:
|
||||
if char == "m":
|
||||
self._select_graphic_rendition(params)
|
||||
style = self._create_style_string()
|
||||
# Otherwise print a zero-width control sequence
|
||||
else:
|
||||
formatted_text.append(("[ZeroWidthEscape]", sequence))
|
||||
continue
|
||||
|
||||
formatted_text.append((style, sequence))
|
||||
|
||||
|
||||
# ===========================
|
||||
# Original Copyright Notice
|
||||
# ===========================
|
||||
#
|
||||
# Copyright (c) 2014, Jonathan Slenders
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
#
|
||||
# * Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# * Neither the name of the {organization} nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
422
euporie/app.py
Normal file
422
euporie/app.py
Normal file
@@ -0,0 +1,422 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from prompt_toolkit.application import Application
|
||||
from prompt_toolkit.enums import EditingMode
|
||||
from prompt_toolkit.filters import Condition, Filter
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
|
||||
from prompt_toolkit.layout.containers import (
|
||||
ConditionalContainer,
|
||||
Float,
|
||||
FloatContainer,
|
||||
HSplit,
|
||||
VSplit,
|
||||
Window,
|
||||
WindowAlign,
|
||||
)
|
||||
from prompt_toolkit.layout.controls import FormattedTextControl
|
||||
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
||||
from prompt_toolkit.layout.layout import Layout
|
||||
from prompt_toolkit.layout.menus import CompletionsMenu
|
||||
from prompt_toolkit.styles import BaseStyle, Style, default_ui_style, merge_styles
|
||||
from prompt_toolkit.styles.pygments import style_from_pygments_cls
|
||||
from prompt_toolkit.widgets import Button, Dialog, MenuContainer, MenuItem
|
||||
from pygments.styles import get_style_by_name
|
||||
|
||||
from euporie import logo
|
||||
from euporie.config import config
|
||||
from euporie.notebook import Notebook
|
||||
from euporie.term import TermAppMixin
|
||||
|
||||
|
||||
class App(Application, TermAppMixin):
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
||||
self.open_paths = []
|
||||
self.files = []
|
||||
self.last_selected_index: int = 0
|
||||
|
||||
self.include_default_pygments_style = False
|
||||
|
||||
self.ttimeoutlen = 0.1
|
||||
|
||||
self.file_open = Condition(lambda: self.files)
|
||||
|
||||
super().__init__(
|
||||
layout=self.layout(),
|
||||
enable_page_navigation_bindings=True,
|
||||
mouse_support=True,
|
||||
key_bindings=self.keybindings(),
|
||||
full_screen=True,
|
||||
style=None,
|
||||
editing_mode=self.edit_mode,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def edit_mode(self):
|
||||
if config.editing_mode == "emacs":
|
||||
return EditingMode.EMACS
|
||||
elif config.editing_mode == "vi":
|
||||
return EditingMode.VI
|
||||
else:
|
||||
# Set default to emacs. Sorry.
|
||||
return EditingMode.EMACS
|
||||
|
||||
def _create_merged_style(
|
||||
self, include_default_pygments_style: Filter = None
|
||||
) -> BaseStyle:
|
||||
|
||||
# Calculate colors based on terminal background colour if we can
|
||||
if self.bg_color:
|
||||
from prompt_toolkit.styles import (
|
||||
DEFAULT_ATTRS,
|
||||
AdjustBrightnessStyleTransformation,
|
||||
)
|
||||
|
||||
tr = AdjustBrightnessStyleTransformation(
|
||||
min_brightness=0.05, max_brightness=0.92
|
||||
)
|
||||
dim_bg = "#{}".format(
|
||||
tr.transform_attrs(
|
||||
DEFAULT_ATTRS._replace(color=self.bg_color.lstrip("#"))
|
||||
).color
|
||||
)
|
||||
else:
|
||||
dim_bg = "default"
|
||||
|
||||
style_dict = {
|
||||
**dict(default_ui_style().style_rules),
|
||||
"logo": "fg:#ff0000",
|
||||
"background": "fg:#444444",
|
||||
"menu-bar": "fg:#ffffff bg:#222222",
|
||||
"menu-bar.item": "bg:#444444",
|
||||
"menu": "fg:#ffffff bg:#222222",
|
||||
# "cell": "#4e4e4e",
|
||||
"cell-border": "fg:#4e4e4e",
|
||||
"cell-border-selected": "fg:#00afff",
|
||||
"cell-border-edit": "fg:#00ff00",
|
||||
"cell-input": "fg:default",
|
||||
"line-number": f"fg:#888888 bg:{dim_bg}",
|
||||
"line-number.current": "bold",
|
||||
"cursor-line": f"bg:{dim_bg}",
|
||||
"cell-output": "fg:default",
|
||||
"cell-input-prompt": "fg:darkblue",
|
||||
"cell-output-prompt": "fg:darkred",
|
||||
"scrollbar.background": "bg:#444444",
|
||||
"scrollbar.button": "bg:#aaaaaa",
|
||||
"scrollbar.arrow": "fg: #aaaaaa bg:#444444",
|
||||
"dialog shadow": "bg:#888888",
|
||||
"dialog.body": "bg:#b0b0b0 #000000",
|
||||
"hr": "fg:#666666",
|
||||
}
|
||||
|
||||
return merge_styles(
|
||||
[
|
||||
style_from_pygments_cls(get_style_by_name(config.pygments_style)),
|
||||
Style.from_dict(style_dict),
|
||||
]
|
||||
)
|
||||
|
||||
def layout(self):
|
||||
|
||||
kernel_status_repr = {
|
||||
"starting": "◍",
|
||||
"idle": "○",
|
||||
"busy": "●",
|
||||
"error": "☹",
|
||||
}
|
||||
|
||||
def get_statusbar_text():
|
||||
kernel_status = kernel_status_repr.get(self.file.kernel_status, "◌")
|
||||
selected_cell = self.file.page.selected_index + 1
|
||||
dirt = "*" if self.file.dirty else ""
|
||||
return [
|
||||
("class:menu-bar.item", f" Cell {selected_cell} "),
|
||||
("", " "),
|
||||
("class:menu-bar.item bold", f" {dirt}{self.file.path.name} "),
|
||||
("", " "),
|
||||
("class:menu-bar.item", f" {self.file.kernel_name} {kernel_status} "),
|
||||
]
|
||||
|
||||
status_bar_text = FormattedTextControl(
|
||||
get_statusbar_text, focusable=True, show_cursor=False
|
||||
)
|
||||
self.status_bar = ConditionalContainer(
|
||||
Window(
|
||||
content=status_bar_text,
|
||||
height=D.exact(1),
|
||||
style="class:menu-bar",
|
||||
dont_extend_width=True,
|
||||
align=WindowAlign.RIGHT,
|
||||
),
|
||||
filter=self.file_open,
|
||||
)
|
||||
|
||||
self.body_container = MenuContainer(
|
||||
body=HSplit([VSplit(self.files)]),
|
||||
menu_items=[
|
||||
MenuItem(
|
||||
" File ",
|
||||
children=[
|
||||
MenuItem(
|
||||
"New", handler=lambda: self.open_file("Untitled.ipynb")
|
||||
),
|
||||
MenuItem("-", disabled=True),
|
||||
MenuItem("Save", handler=lambda: self.file.save()),
|
||||
MenuItem("Close", handler=self.close_file),
|
||||
MenuItem("-", disabled=True),
|
||||
MenuItem("Exit", handler=self.try_to_exit),
|
||||
],
|
||||
),
|
||||
MenuItem(
|
||||
" Edit ",
|
||||
children=[
|
||||
MenuItem("Cut", handler=lambda: self.file.cut()),
|
||||
MenuItem("Copy", handler=lambda: self.file.copy()),
|
||||
MenuItem("Paste", handler=lambda: self.file.paste()),
|
||||
],
|
||||
),
|
||||
MenuItem(
|
||||
" Kernel ",
|
||||
children=[
|
||||
MenuItem(
|
||||
"Restart Kernel", handler=lambda: self.file.restart_kernel()
|
||||
),
|
||||
MenuItem(
|
||||
"Change Kernel...",
|
||||
handler=lambda: self.file.change_kernel(),
|
||||
),
|
||||
],
|
||||
),
|
||||
MenuItem(
|
||||
" Help ",
|
||||
children=[
|
||||
MenuItem("About", handler=self.about),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
self.logo = FormattedTextControl(
|
||||
[("", f" {logo} ")],
|
||||
focusable=True,
|
||||
show_cursor=False,
|
||||
style="class:menu-bar.item,logo",
|
||||
)
|
||||
|
||||
# Add logo and status bar into menubar
|
||||
self.body_container.container.content.children = [
|
||||
VSplit(
|
||||
[
|
||||
Window(self.logo, height=D.exact(1), dont_extend_width=True),
|
||||
self.body_container.window,
|
||||
self.status_bar,
|
||||
]
|
||||
),
|
||||
self.body_container.container.content.children[1],
|
||||
]
|
||||
|
||||
self.root_container = FloatContainer(
|
||||
content=self.body_container,
|
||||
floats=[
|
||||
Float(
|
||||
xcursor=True,
|
||||
ycursor=True,
|
||||
content=CompletionsMenu(max_height=16, scroll_offset=1),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
# Focus status_bar_text so notebook is selected on tab
|
||||
return Layout(self.root_container, focused_element=status_bar_text)
|
||||
|
||||
def keybindings(self):
|
||||
kb = KeyBindings()
|
||||
|
||||
in_edit_mode = Condition(
|
||||
lambda: self.file and self.file.cell and self.file.cell.is_editing()
|
||||
)
|
||||
|
||||
kb.add("tab", filter=~in_edit_mode)(focus_next)
|
||||
kb.add("s-tab", filter=~in_edit_mode)(focus_previous)
|
||||
|
||||
@kb.add("c-q")
|
||||
def exit(event):
|
||||
self.try_to_exit()
|
||||
|
||||
@kb.add("c-w")
|
||||
def close(event):
|
||||
self.close_file(self.file)
|
||||
|
||||
@kb.add("c-n")
|
||||
def new(event):
|
||||
self.open_file("Untitled.ipynb")
|
||||
|
||||
return kb
|
||||
|
||||
@property
|
||||
def selected_index(self):
|
||||
# Detect if focused file has changed
|
||||
# Find index of selected child
|
||||
for i, file in enumerate(self.files):
|
||||
if self.layout.has_focus(file):
|
||||
break
|
||||
else:
|
||||
i = self.last_selected_index
|
||||
# This will perform change the position when the new child is selected
|
||||
self.last_selected_index = i
|
||||
return self.last_selected_index
|
||||
|
||||
@selected_index.setter
|
||||
def selected_index(self, new_index):
|
||||
# Only update the selected file if it was not selected before
|
||||
if new_index != self.last_selected_index:
|
||||
# Ensure selected index is a valid child
|
||||
new_index = min(max(new_index, 0), len(self.files) - 1)
|
||||
self.select_notebook(new_index)
|
||||
|
||||
# Focus new child if not already focused
|
||||
child = self.get_child(new_index)
|
||||
if not self.layout.has_focus(child):
|
||||
self.layout.focus(child)
|
||||
|
||||
# Track which child was selected
|
||||
self.last_selected_index = new_index
|
||||
|
||||
def try_to_exit(self):
|
||||
"""
|
||||
Check for unsaved files before closing.
|
||||
|
||||
Creates a chain of close file commands, where the callback for each triggers
|
||||
the closure of the next. The closing process can be cancelled anywhere along
|
||||
the chain.
|
||||
"""
|
||||
|
||||
if self.files:
|
||||
|
||||
def final_cb():
|
||||
"""Really exit after the last file in the chain is closed."""
|
||||
self.cleanup_closed_file(self.files[0])
|
||||
self.exit()
|
||||
|
||||
def create_cb(close_file, cleanup_file, cb):
|
||||
"""Generate a file close chaining callbacks.
|
||||
|
||||
Cleans up after the previously closed file, and requests to close the
|
||||
next file in the chain.
|
||||
"""
|
||||
|
||||
def inner():
|
||||
self.cleanup_closed_file(cleanup_file)
|
||||
close_file.close(cb=cb)
|
||||
|
||||
return inner
|
||||
|
||||
cb = final_cb
|
||||
for close_file, cleanup_file in zip(self.files, self.files[1:]):
|
||||
cb = create_cb(close_file, cleanup_file, cb)
|
||||
self.files[-1].close(cb)
|
||||
else:
|
||||
self.exit()
|
||||
|
||||
def open_file(self, path):
|
||||
path = Path(path).expanduser()
|
||||
open_paths = [x.path for x in self.files]
|
||||
if path in open_paths:
|
||||
self.active_notebook = open_paths.index(path)
|
||||
else:
|
||||
self.open_paths.append(path)
|
||||
self.files.append(Notebook(path))
|
||||
self.active_notebook_index = len(self.files)
|
||||
|
||||
self.body_container.body.children[0] = VSplit(self.files)
|
||||
|
||||
def close_file(self, file=None):
|
||||
if file is None:
|
||||
file = self.file
|
||||
if file:
|
||||
self.file.close(lambda: self.cleanup_closed_file(file))
|
||||
|
||||
def cleanup_closed_file(self, file):
|
||||
# Remove file
|
||||
self.files.remove(file)
|
||||
# Update body container to reflect new file list
|
||||
self.body_container.body.children[0] = VSplit(self.files)
|
||||
# Focus another file if one exists
|
||||
if self.files:
|
||||
self.file.page.focus()
|
||||
# If a file is not open, the status bar is not shown, so focus the logo, so
|
||||
# pressing tab focuses the menu
|
||||
else:
|
||||
self.layout.focus(self.logo)
|
||||
|
||||
@property
|
||||
def file(self):
|
||||
if self.files:
|
||||
index = min(self.selected_index, len(self.files) - 1)
|
||||
return self.files[index]
|
||||
|
||||
def dialog(self, title, body, buttons):
|
||||
def make_handler(cb):
|
||||
def inner():
|
||||
self.root_container.floats.remove(dialog)
|
||||
self.layout.focus(focused)
|
||||
if cb:
|
||||
cb()
|
||||
|
||||
return inner
|
||||
|
||||
focused = self.layout.current_control
|
||||
|
||||
button_widgets = [
|
||||
Button(text, make_handler(cb), left_symbol="[", right_symbol="]")
|
||||
for text, cb in buttons.items()
|
||||
]
|
||||
|
||||
dialog = Float(
|
||||
Dialog(
|
||||
title=title,
|
||||
body=body,
|
||||
buttons=button_widgets,
|
||||
modal=True,
|
||||
with_background=True,
|
||||
)
|
||||
)
|
||||
self.root_container.floats.append(
|
||||
dialog,
|
||||
)
|
||||
self.layout.focus(button_widgets[0])
|
||||
|
||||
def about(self):
|
||||
self.dialog(
|
||||
title="About",
|
||||
body=Window(
|
||||
FormattedTextControl(
|
||||
[
|
||||
("class:logo", logo),
|
||||
(
|
||||
"bold",
|
||||
"euporie\n\n",
|
||||
),
|
||||
("", "A command line editor for Jupyter notebooks\n"),
|
||||
("class:hr", "─" * 43 + "\n\n"),
|
||||
("", "Created by Josiah Outram Halstead\n"),
|
||||
("", "© 2021"),
|
||||
]
|
||||
),
|
||||
dont_extend_height=True,
|
||||
),
|
||||
buttons={"OK": None},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def launch(cls):
|
||||
app = cls()
|
||||
for path in sys.argv[1:]:
|
||||
app.open_file(path)
|
||||
app.run()
|
||||
return app
|
||||
20
euporie/box.py
Normal file
20
euporie/box.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from prompt_toolkit.widgets import base
|
||||
|
||||
|
||||
class Border:
|
||||
"Box drawing characters. (Thin)"
|
||||
HORIZONTAL = "─"
|
||||
VERTICAL = "│"
|
||||
TOP_LEFT = "╭"
|
||||
TOP_RIGHT = "╮"
|
||||
BOTTOM_LEFT = "╰"
|
||||
BOTTOM_RIGHT = "╯"
|
||||
SPLIT_BOTTOM = "┴"
|
||||
SPLIT_TOP = "┬"
|
||||
SPLIT_LEFT = "├"
|
||||
SPLIT_RIGHT = "┤"
|
||||
CROSS = "┼"
|
||||
|
||||
|
||||
base.Border = Border
|
||||
435
euporie/cell.py
Normal file
435
euporie/cell.py
Normal file
@@ -0,0 +1,435 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
from functools import partial
|
||||
|
||||
import nbformat
|
||||
from prompt_toolkit.application.current import get_app
|
||||
from prompt_toolkit.filters import Condition
|
||||
from prompt_toolkit.formatted_text.base import StyleAndTextTuples
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
from prompt_toolkit.layout.containers import (
|
||||
ConditionalContainer,
|
||||
Container,
|
||||
Float,
|
||||
FloatContainer,
|
||||
HSplit,
|
||||
VSplit,
|
||||
Window,
|
||||
)
|
||||
from prompt_toolkit.layout.controls import FormattedTextControl
|
||||
from prompt_toolkit.lexers import DynamicLexer, PygmentsLexer
|
||||
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
|
||||
from prompt_toolkit.search import start_search
|
||||
from prompt_toolkit.widgets import Label, SearchToolbar, TextArea
|
||||
from pygments.lexers import get_lexer_by_name
|
||||
|
||||
from euporie.box import Border
|
||||
from euporie.output import Output
|
||||
|
||||
|
||||
class ClickArea:
|
||||
"""Any empty widget which focuses `target` when clicked.
|
||||
|
||||
Designed to be used as an overlay for clickable widgets in a FloatContainer.
|
||||
"""
|
||||
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
self.window = Window(
|
||||
FormattedTextControl(
|
||||
self._get_text_fragments,
|
||||
focusable=False,
|
||||
),
|
||||
dont_extend_width=False,
|
||||
dont_extend_height=False,
|
||||
)
|
||||
|
||||
def _get_text_fragments(self) -> StyleAndTextTuples:
|
||||
def handler(mouse_event: MouseEvent) -> None:
|
||||
if mouse_event.event_type == MouseEventType.MOUSE_UP:
|
||||
get_app().layout.focus(self.target)
|
||||
|
||||
return [("class:cell-clickarea", "", handler)]
|
||||
|
||||
def __pt_container__(self) -> Container:
|
||||
return self.window
|
||||
|
||||
|
||||
class Cell:
|
||||
def __init__(self, index, json, notebook):
|
||||
self.index = index
|
||||
self.json = json
|
||||
self.nb = notebook
|
||||
self.rendered = True
|
||||
self.editing = False
|
||||
self.kb = KeyBindings()
|
||||
self._drawing_position = None
|
||||
|
||||
self.state = "idle"
|
||||
|
||||
ft = FormattedTextControl(
|
||||
Border.TOP_LEFT,
|
||||
focusable=True,
|
||||
show_cursor=False,
|
||||
)
|
||||
self.control = Window(ft, width=1, height=0, style=self.border_style)
|
||||
|
||||
self.show_input = Condition(
|
||||
lambda: (
|
||||
(self.json.get("cell_type") != "markdown")
|
||||
| ((self.json.get("cell_type") == "markdown") & ~self.rendered)
|
||||
)
|
||||
)
|
||||
self.show_output = Condition(
|
||||
lambda: (
|
||||
(self.json.get("cell_type") != "markdown") & bool(self.outputs)
|
||||
| ((self.json.get("cell_type") == "markdown") & self.rendered)
|
||||
)
|
||||
)
|
||||
self.scroll_input = Condition(
|
||||
lambda: (self.json.get("cell_type") == "markdown") & ~self.rendered
|
||||
)
|
||||
self.wrap_input = Condition(lambda: self.json.get("cell_type") == "markdown")
|
||||
self.is_editing = Condition(lambda: self.editing)
|
||||
self.show_prompt = Condition(lambda: self.cell_type == "code")
|
||||
self.is_focused = Condition(lambda: self.focused)
|
||||
self.obscured = Condition(
|
||||
lambda: (
|
||||
self._drawing_position is None
|
||||
or (
|
||||
self._drawing_position.top < 0
|
||||
or self._drawing_position.parent_height
|
||||
< self._drawing_position.top + self._drawing_position.height
|
||||
)
|
||||
)
|
||||
)
|
||||
self.show_input_line_numbers = Condition(
|
||||
lambda: self.nb.line_numbers and self.json.get("cell_type") == "code"
|
||||
)
|
||||
|
||||
self.load()
|
||||
self.load_keybindings()
|
||||
|
||||
def load_keybindings(self):
|
||||
@self.kb.add("e", filter=~self.is_editing)
|
||||
async def edit_in_editor(event):
|
||||
self.editing = True
|
||||
await self.input_box.buffer.open_in_editor()
|
||||
self.nb.dirty = True
|
||||
self.editing = False
|
||||
|
||||
@self.kb.add("enter", filter=~self.is_editing)
|
||||
def enter_edit_mode(event):
|
||||
self.editing = True
|
||||
self.container.modal = True
|
||||
get_app().layout.focus(self.input_box)
|
||||
self.rendered = False
|
||||
|
||||
@self.kb.add("escape", "escape") # , eager=True)
|
||||
@self.kb.add("escape") # , eager=True)
|
||||
def exit_edit_mode(event):
|
||||
self.editing = False
|
||||
self.input = self.input_box.text
|
||||
self.nb.dirty = True
|
||||
self.container.modal = False
|
||||
# give focus back to selected cell (this might have changed!)
|
||||
get_app().layout.focus(self.nb.cell.control)
|
||||
|
||||
@self.kb.add("c-space")
|
||||
@self.kb.add("c-f20")
|
||||
def run_or_render(event):
|
||||
self.input = self.input_box.text
|
||||
self.nb.dirty = True
|
||||
exit_edit_mode(event)
|
||||
if self.cell_type == "markdown":
|
||||
self.output_box.children = self.rendered_outputs
|
||||
self.rendered = True
|
||||
elif self.cell_type == "code":
|
||||
self.state = "queued"
|
||||
self.run()
|
||||
|
||||
@self.kb.add("f21")
|
||||
def run_then_next(event):
|
||||
self.nb.page.selected_index += 1
|
||||
run_or_render(event)
|
||||
|
||||
@self.kb.add("c-f", filter=self.is_editing)
|
||||
def find(event):
|
||||
start_search(self.input_box.control)
|
||||
|
||||
@self.kb.add("c-g", filter=self.is_editing)
|
||||
def find_next(event):
|
||||
search_state = get_app().current_search_state
|
||||
cursor_position = self.input_box.buffer.get_search_position(
|
||||
search_state, include_current_position=False
|
||||
)
|
||||
self.input_box.buffer.cursor_position = cursor_position
|
||||
|
||||
@self.kb.add("c-z", filter=self.is_editing)
|
||||
def undo(event):
|
||||
self.input_box.buffer.undo()
|
||||
|
||||
def run(self):
|
||||
self.clear_output()
|
||||
if self.nb.kc:
|
||||
# Execute input and wait for responses in kernel thread
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.nb.kc._async_execute_interactive(
|
||||
code=self.input,
|
||||
allow_stdin=False,
|
||||
output_hook=self.ran,
|
||||
),
|
||||
self.nb.kernel_loop,
|
||||
)
|
||||
|
||||
def ran(self, msg):
|
||||
msg_type = msg.get("header", {}).get("msg_type")
|
||||
|
||||
if msg_type == "status":
|
||||
self.state = msg.get("content", {}).get("execution_state")
|
||||
self.nb.kernel_status = self.state
|
||||
|
||||
elif msg_type == "execute_input":
|
||||
self.json["execution_count"] = msg.get("content", {}).get("execution_count")
|
||||
|
||||
elif msg_type in ("stream", "error", "display_data", "execute_result"):
|
||||
self.json["outputs"].append(nbformat.v4.output_from_msg(msg))
|
||||
|
||||
# Redraw cell with new outputs / prompt
|
||||
self.load()
|
||||
# Tell the app that the display needs updating
|
||||
get_app().invalidate()
|
||||
|
||||
def set_cell_type(self, cell_type):
|
||||
if cell_type == "code":
|
||||
self.json.setdefault("execution_count", None)
|
||||
self.json["cell_type"] = cell_type
|
||||
self.load()
|
||||
|
||||
def mouse_click(self):
|
||||
get_app().layout.focus(self.control)
|
||||
|
||||
def load(self):
|
||||
|
||||
fill = partial(Window, style=self.border_style)
|
||||
|
||||
self.search_control = SearchToolbar()
|
||||
|
||||
self.input_box = TextArea(
|
||||
text=self.input,
|
||||
# Does not accept conditions
|
||||
scrollbar=self.scroll_input(),
|
||||
wrap_lines=self.wrap_input,
|
||||
# Does not accept conditions
|
||||
line_numbers=self.show_input_line_numbers(),
|
||||
read_only=~self.is_editing,
|
||||
focusable=self.is_editing,
|
||||
lexer=DynamicLexer(
|
||||
lambda: PygmentsLexer(
|
||||
get_lexer_by_name(self.language).__class__,
|
||||
sync_from_start=False,
|
||||
)
|
||||
if self.cell_type != "raw"
|
||||
else None
|
||||
),
|
||||
search_field=self.search_control,
|
||||
completer=self.nb.completer,
|
||||
complete_while_typing=False,
|
||||
style="class:cell-input",
|
||||
)
|
||||
self.input_box.window.cursorline = self.is_editing
|
||||
|
||||
self.output_box = HSplit(
|
||||
self.rendered_outputs,
|
||||
style="class:cell-output",
|
||||
)
|
||||
|
||||
top_border = VSplit(
|
||||
[
|
||||
self.control,
|
||||
ConditionalContainer(
|
||||
content=fill(
|
||||
char=Border.HORIZONTAL, width=len(self.prompt), height=1
|
||||
),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
ConditionalContainer(
|
||||
content=fill(width=1, height=1, char=Border.SPLIT_TOP),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
fill(char=Border.HORIZONTAL, height=1),
|
||||
fill(width=1, height=1, char=Border.TOP_RIGHT),
|
||||
],
|
||||
height=1,
|
||||
)
|
||||
input_row = ConditionalContainer(
|
||||
VSplit(
|
||||
[
|
||||
fill(width=1, char=Border.VERTICAL),
|
||||
ConditionalContainer(
|
||||
content=Label(
|
||||
self.prompt,
|
||||
width=len(self.prompt),
|
||||
style="class:cell-input-prompt",
|
||||
),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
ConditionalContainer(
|
||||
content=fill(width=1, char=Border.VERTICAL),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
HSplit([self.input_box, self.search_control]),
|
||||
fill(width=1, char=Border.VERTICAL),
|
||||
],
|
||||
),
|
||||
filter=self.show_input,
|
||||
)
|
||||
middle_line = ConditionalContainer(
|
||||
content=VSplit(
|
||||
[
|
||||
fill(width=1, height=1, char=Border.SPLIT_LEFT),
|
||||
ConditionalContainer(
|
||||
content=fill(char=Border.HORIZONTAL, width=len(self.prompt)),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
ConditionalContainer(
|
||||
content=fill(width=1, height=1, char=Border.CROSS),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
fill(char=Border.HORIZONTAL),
|
||||
fill(width=1, height=1, char=Border.SPLIT_RIGHT),
|
||||
],
|
||||
height=1,
|
||||
),
|
||||
filter=self.show_input & self.show_output,
|
||||
)
|
||||
output_row = ConditionalContainer(
|
||||
VSplit(
|
||||
[
|
||||
fill(width=1, char=Border.VERTICAL),
|
||||
ConditionalContainer(
|
||||
content=Label(
|
||||
self.prompt,
|
||||
width=len(self.prompt),
|
||||
style="class:cell-output-prompt",
|
||||
),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
ConditionalContainer(
|
||||
fill(width=1, char=" "), filter=~self.show_prompt
|
||||
),
|
||||
ConditionalContainer(
|
||||
content=fill(width=1, char=Border.VERTICAL),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
self.output_box,
|
||||
ConditionalContainer(
|
||||
fill(width=1, char=" "), filter=~self.show_prompt
|
||||
),
|
||||
fill(width=1, char=Border.VERTICAL),
|
||||
],
|
||||
),
|
||||
filter=self.show_output,
|
||||
)
|
||||
bottom_border = VSplit(
|
||||
[
|
||||
fill(width=1, height=1, char=Border.BOTTOM_LEFT),
|
||||
ConditionalContainer(
|
||||
content=fill(char=Border.HORIZONTAL, width=len(self.prompt)),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
ConditionalContainer(
|
||||
content=fill(width=1, height=1, char=Border.SPLIT_BOTTOM),
|
||||
filter=self.show_prompt,
|
||||
),
|
||||
fill(char=Border.HORIZONTAL),
|
||||
fill(width=1, height=1, char=Border.BOTTOM_RIGHT),
|
||||
],
|
||||
height=1,
|
||||
)
|
||||
|
||||
self.container = FloatContainer(
|
||||
content=HSplit(
|
||||
[top_border, input_row, middle_line, output_row, bottom_border],
|
||||
key_bindings=self.kb,
|
||||
),
|
||||
floats=[
|
||||
Float(
|
||||
transparent=True,
|
||||
left=0,
|
||||
right=0,
|
||||
top=0,
|
||||
bottom=0,
|
||||
content=ConditionalContainer(
|
||||
ClickArea(self), filter=~self.is_focused
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
def border_style(self):
|
||||
if self.focused:
|
||||
if self.editing:
|
||||
return "class:frame.border,cell-border-edit"
|
||||
else:
|
||||
return "class:frame.border,cell-border-selected"
|
||||
else:
|
||||
return "class:frame.border,cell-border"
|
||||
|
||||
@property
|
||||
def language(self):
|
||||
if self.cell_type == "markdown":
|
||||
return "markdown"
|
||||
else:
|
||||
return self.nb.json.metadata.get("language_info", {}).get("name", "python")
|
||||
|
||||
@property
|
||||
def focused(self):
|
||||
return get_app().layout.has_focus(self.container)
|
||||
|
||||
@property
|
||||
def cell_type(self):
|
||||
return self.json.get("cell_type", "code")
|
||||
|
||||
@property
|
||||
def prompt(self):
|
||||
if self.state in ("busy", "queued"):
|
||||
prompt = "*"
|
||||
else:
|
||||
prompt = self.json.get("execution_count", "")
|
||||
if prompt is None:
|
||||
prompt = " "
|
||||
if prompt:
|
||||
prompt = f"[{prompt}]"
|
||||
return prompt
|
||||
|
||||
@property
|
||||
def input(self):
|
||||
return self.json.get("source", "")
|
||||
|
||||
@input.setter
|
||||
def input(self, value):
|
||||
self.json["source"] = value
|
||||
|
||||
def clear_output(self):
|
||||
self.json["outputs"] = []
|
||||
self.load()
|
||||
|
||||
@property
|
||||
def outputs(self):
|
||||
if self.cell_type == "markdown":
|
||||
return [
|
||||
{"data": {"text/x-markdown": self.input}, "output_type": "markdown"}
|
||||
]
|
||||
else:
|
||||
return self.json.get("outputs", [])
|
||||
|
||||
@property
|
||||
def rendered_outputs(self):
|
||||
rendered_outputs = []
|
||||
for i, output_json in enumerate(self.outputs):
|
||||
rendered_outputs.append(Output(i, output_json, parent=self))
|
||||
return rendered_outputs
|
||||
|
||||
def __pt_container__(self) -> "Container":
|
||||
return self.container
|
||||
17
euporie/config.py
Normal file
17
euporie/config.py
Normal file
@@ -0,0 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from collections import namedtuple
|
||||
|
||||
defaults = {
|
||||
"max_notebook_width": 120,
|
||||
"show_background": True,
|
||||
"background_character": "·",
|
||||
"pygments_style": "native",
|
||||
"editing_mode": "emacs",
|
||||
}
|
||||
|
||||
Config = namedtuple(
|
||||
"config", **dict(zip(["field_names", "defaults"], zip(*defaults.items())))
|
||||
)
|
||||
|
||||
|
||||
config = Config()
|
||||
89
euporie/control.py
Normal file
89
euporie/control.py
Normal file
@@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from prompt_toolkit.cache import SimpleCache
|
||||
from prompt_toolkit.layout.controls import UIContent, UIControl
|
||||
|
||||
from euporie.render import HTMLRenderer, ImageRenderer, RichRenderer, SVGRenderer
|
||||
|
||||
from .ansi import ANSI
|
||||
|
||||
|
||||
class Control(UIControl):
|
||||
"""Displays the output of a renderer re-draws it's contents on resize."""
|
||||
|
||||
def __init__(self, data, render_args={}):
|
||||
self.data = data
|
||||
self.render_args = render_args
|
||||
|
||||
self.renderer_instance = self.renderer.select()
|
||||
self.rendered_lines = None
|
||||
|
||||
self._format_cache = SimpleCache(maxsize=20)
|
||||
self._content_cache = SimpleCache(maxsize=20)
|
||||
|
||||
def preferred_height(
|
||||
self,
|
||||
width: int,
|
||||
max_available_height: int,
|
||||
wrap_lines: bool,
|
||||
get_line_prefix,
|
||||
):
|
||||
if not self.rendered_lines:
|
||||
self.rendered_lines = self._format_cache.get(
|
||||
(width, max_available_height),
|
||||
lambda: self.render(width, max_available_height),
|
||||
)
|
||||
return len(self.rendered_lines)
|
||||
|
||||
def create_content(self, width, height):
|
||||
|
||||
self.rendered_lines = self._format_cache.get(
|
||||
(width,),
|
||||
lambda: self.render(width, height),
|
||||
)
|
||||
|
||||
def get_content():
|
||||
return UIContent(
|
||||
get_line=lambda i: ANSI(self.rendered_lines[i]).__pt_formatted_text__(),
|
||||
line_count=len(self.rendered_lines),
|
||||
)
|
||||
|
||||
return self._content_cache.get((width,), get_content)
|
||||
|
||||
def render(self, width, height):
|
||||
result = self.renderer_instance.render(
|
||||
self.data, width=width, height=height, render_args=self.render_args
|
||||
)
|
||||
if isinstance(result, str):
|
||||
result = result.rstrip().split("\n")
|
||||
return result
|
||||
|
||||
|
||||
class RichControl(Control):
|
||||
renderer = RichRenderer
|
||||
|
||||
|
||||
class SVGControl(Control):
|
||||
renderer = SVGRenderer
|
||||
|
||||
|
||||
class HTMLControl(Control):
|
||||
renderer = HTMLRenderer
|
||||
|
||||
|
||||
class ImageControl(Control):
|
||||
renderer = ImageRenderer
|
||||
|
||||
def create_content(self, width, height):
|
||||
cell_obscured = self.render_args["cell"].obscured()
|
||||
self.rendered_lines = self._format_cache.get(
|
||||
(cell_obscured, width),
|
||||
lambda: self.render(width, height),
|
||||
)
|
||||
|
||||
def get_content():
|
||||
return UIContent(
|
||||
get_line=lambda i: ANSI(self.rendered_lines[i]).__pt_formatted_text__(),
|
||||
line_count=len(self.rendered_lines),
|
||||
)
|
||||
|
||||
return self._content_cache.get((cell_obscured, width), get_content)
|
||||
30
euporie/libs/commonmark_extensions/LICENSE
Normal file
30
euporie/libs/commonmark_extensions/LICENSE
Normal file
@@ -0,0 +1,30 @@
|
||||
Copyright (c) 2017 GovReady PBC
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
* Neither the names of Bibek Kafle, Roland Shoemaker nor the names of other
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
308
euporie/libs/commonmark_extensions/tables.py
Normal file
308
euporie/libs/commonmark_extensions/tables.py
Normal file
@@ -0,0 +1,308 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Mokey-patch the reMaybeSpecial regex to add our table symbol |.
|
||||
# This regex is apparently just an optimization so this should not
|
||||
# affect CommonMark parser instances that do not recognize tables.
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
import commonmark
|
||||
import commonmark.blocks
|
||||
import commonmark.node
|
||||
|
||||
commonmark.blocks.reMaybeSpecial = re.compile(r"^[#`~*+_=<>0-9-|]")
|
||||
|
||||
|
||||
# Define a new BlockStarts class that implements a table method
|
||||
# to detect and parse table starts, modeled after the blockquote.
|
||||
class BlockStarts(commonmark.blocks.BlockStarts):
|
||||
def __init__(self):
|
||||
self.METHODS = ["table"] + self.METHODS
|
||||
|
||||
@staticmethod
|
||||
def table(parser, container):
|
||||
if (
|
||||
not parser.indented
|
||||
and commonmark.blocks.peek(parser.current_line, parser.next_nonspace) == "|"
|
||||
):
|
||||
parser.advance_next_nonspace()
|
||||
parser.advance_offset(1, False)
|
||||
parser.close_unmatched_blocks()
|
||||
parser.add_child("table", parser.next_nonspace)
|
||||
parser.tip.string_content = "|"
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
# Define a new Table class that handles incoming table lines, modeled
|
||||
# a bit after the Blockquote, which allows continuation lines so long as
|
||||
# they start with the symbol. Also has accepts_lines to suck in everything
|
||||
# within it as raw data. Accept : as a continuation symbol for
|
||||
# Github-flavored Markdown table column alignment.
|
||||
class Table(commonmark.blocks.Block):
|
||||
accepts_lines = True
|
||||
|
||||
@staticmethod
|
||||
def continue_(parser=None, container=None):
|
||||
ln = parser.current_line
|
||||
if (
|
||||
not parser.indented
|
||||
and commonmark.blocks.peek(ln, parser.next_nonspace) == "|"
|
||||
):
|
||||
parser.advance_next_nonspace()
|
||||
parser.advance_offset(1, False)
|
||||
container.string_content += "|"
|
||||
elif not parser.indented and commonmark.blocks.peek(
|
||||
ln, parser.next_nonspace
|
||||
) not in ("", ">", "`", None):
|
||||
pass
|
||||
else:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def finalize(parser=None, block=None):
|
||||
# Split the table content into rows and columns,
|
||||
# with each line a new row.
|
||||
#
|
||||
# Note that the | in the first column is not a
|
||||
# part of string_content because it was removed
|
||||
# when we slurped in the table.
|
||||
table = [[""]]
|
||||
escape = False
|
||||
newrowbars = False # noqa F841
|
||||
ignore_pipe = True
|
||||
for c in block.string_content.rstrip():
|
||||
# \-escaping
|
||||
if escape:
|
||||
table[-1][-1] += c
|
||||
escape = False
|
||||
elif c == "\\":
|
||||
escape = True
|
||||
|
||||
# New cell is begun by a bar. Right-strip the cell we're
|
||||
# ending.
|
||||
elif c == "|":
|
||||
if ignore_pipe:
|
||||
ignore_pipe = False
|
||||
continue
|
||||
table[-1][-1] = table[-1][-1].rstrip()
|
||||
table[-1].append("")
|
||||
|
||||
# New row is begun by a newline.
|
||||
# Since there's always a pipe at the end of a line,
|
||||
# pop last cell if empty.
|
||||
elif c == "\n":
|
||||
if table[-1][-1].strip() == "":
|
||||
table[-1].pop(-1)
|
||||
table.append([""])
|
||||
ignore_pipe = True
|
||||
continue
|
||||
|
||||
# Ignore space at start of cell. An escaped space
|
||||
# can force a space.
|
||||
elif c in (" ", "\t") and table[-1][-1] == "":
|
||||
pass
|
||||
|
||||
# Content.
|
||||
else:
|
||||
table[-1][-1] += c
|
||||
|
||||
ignore_pipe = False
|
||||
|
||||
# Remove the last cell if it's empty since it's caused
|
||||
# by the final pipe at the end of the last line.
|
||||
if table[-1][-1].strip() == "":
|
||||
table[-1].pop(-1)
|
||||
|
||||
# Re-flow the table into a <thead> part and a <tbody> part,
|
||||
# and if the separator row uses ='s instead of -'s then
|
||||
# treat subsequent rows as multiline rows that must be
|
||||
# separated by ='s.
|
||||
column_properties = defaultdict(lambda: {})
|
||||
table_parts = [[]] # [thead, tbody] or just [tbody]
|
||||
multiline = False
|
||||
newrow = False
|
||||
for row in table:
|
||||
if len(list(filter(lambda cell: not re.match(r"[-=:]+$", cell), row))) == 0:
|
||||
# This row has cells of just dahses.
|
||||
if len(table_parts) == 1:
|
||||
if len(row) != len(table_parts[0][0]):
|
||||
block.t = "paragraph"
|
||||
return
|
||||
# The first time, we shift to the tbody.
|
||||
table_parts.append([])
|
||||
|
||||
# We also pick out column properties from the
|
||||
# placement of a colon.
|
||||
for i, cell in enumerate(row):
|
||||
if cell.startswith(":") and cell.endswith(":"):
|
||||
column_properties[i]["align"] = "center"
|
||||
elif cell.startswith(":"):
|
||||
column_properties[i]["align"] = "left"
|
||||
elif cell.endswith(":"):
|
||||
column_properties[i]["align"] = "right"
|
||||
|
||||
# If ='s were used, then the table is parsed in
|
||||
# multiline mode.
|
||||
if "=" in "".join(row):
|
||||
multiline = True
|
||||
|
||||
elif multiline:
|
||||
# Subsequent times we just note that we're starting a new row
|
||||
# in multiline mode.
|
||||
newrow = True
|
||||
|
||||
elif not multiline or newrow or len(table_parts[-1]) == 0:
|
||||
# Append a new row.
|
||||
table_parts[-1].append(row)
|
||||
newrow = False
|
||||
|
||||
# Fill in empty rows if fewer than the header.
|
||||
if len(table_parts) > 1 and len(table_parts[0][0]) > len(
|
||||
table_parts[-1][-1]
|
||||
):
|
||||
table_parts[-1][-1].extend(
|
||||
[
|
||||
""
|
||||
for _ in range(
|
||||
len(table_parts[0][0]) - len(table_parts[-1][-1])
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
# Remove excess cells if more than number of columns
|
||||
if len(table_parts) > 1 and len(table_parts[0][0]) < len(
|
||||
table_parts[-1][-1]
|
||||
):
|
||||
table_parts[-1][-1] = table_parts[-1][-1][: len(table_parts[0][0])]
|
||||
|
||||
else:
|
||||
# Multline mode. Merge this row with the previous one.
|
||||
for i in range(len(row)):
|
||||
if i < len(table_parts[-1][-1]):
|
||||
table_parts[-1][-1][i] += "\n" + row[i]
|
||||
else:
|
||||
table_parts[-1][-1].append(row[i])
|
||||
|
||||
# Remove the last table part (probably tbody) if there is no content.
|
||||
if table_parts[-1] == []:
|
||||
table_parts.pop(-1)
|
||||
|
||||
# Parse the Markdown in each cell using a new parser
|
||||
# instance for each cell.
|
||||
if not multiline:
|
||||
# Just parse the inlines in each cell using the parser's
|
||||
# inline_parser function. Wrap each cell string content
|
||||
# in a Node first.
|
||||
def inner_parser(cell):
|
||||
node = commonmark.node.Node("document", 0)
|
||||
para = commonmark.node.Node("paragraph", 0)
|
||||
para.string_content = cell
|
||||
node.append_child(para)
|
||||
parser.inline_parser.parse(para)
|
||||
return node
|
||||
|
||||
else:
|
||||
# Parse each cell using the full Markdown parser,
|
||||
# by instantiating a new instance of the same
|
||||
# parser class first, using the same options.
|
||||
inner_parser = type(parser)(options=parser.options).parse
|
||||
|
||||
for part in table_parts:
|
||||
for row in part:
|
||||
for i, cell in enumerate(row):
|
||||
row[i] = inner_parser(cell)
|
||||
|
||||
# Store the parsed table on the node.
|
||||
block.column_properties = column_properties
|
||||
block.table = table_parts
|
||||
|
||||
|
||||
commonmark.blocks.Table = Table
|
||||
|
||||
|
||||
# Create a new parser sub-class that adds the new block-start
|
||||
# for tables.
|
||||
class ParserWithTables(commonmark.Parser):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.block_starts = BlockStarts()
|
||||
if hasattr(self, "blocks"):
|
||||
self.blocks["table"] = commonmark.blocks.Table
|
||||
|
||||
|
||||
# Define a new renderer that extends the HtmlRenderer and
|
||||
# adds table rendering.
|
||||
class RendererWithTables(commonmark.HtmlRenderer):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def make_table_node(self, node):
|
||||
return "<table>"
|
||||
|
||||
def table(self, node, entering):
|
||||
if entering:
|
||||
self.lit(self.make_table_node(node) + "\n")
|
||||
for i, part in enumerate(node.table):
|
||||
if i == 0:
|
||||
part_tag = "thead"
|
||||
else:
|
||||
part_tag = "tbody"
|
||||
self.lit("<" + part_tag + ">\n")
|
||||
for row in part:
|
||||
self.lit("<tr>\n")
|
||||
for colidx, cell in enumerate(row):
|
||||
if part_tag == "thead":
|
||||
col_tag = "th"
|
||||
if self.options.get("table_th_scope"):
|
||||
col_attrs = ' scope="col"'
|
||||
else:
|
||||
col_attrs = ""
|
||||
else:
|
||||
col_tag = "td"
|
||||
col_attrs = ""
|
||||
|
||||
if (
|
||||
colidx in node.column_properties
|
||||
and "align" in node.column_properties[colidx]
|
||||
):
|
||||
col_attrs += (
|
||||
' align="'
|
||||
+ node.column_properties[colidx]["align"]
|
||||
+ '"'
|
||||
)
|
||||
|
||||
self.lit("<" + col_tag + col_attrs + ">")
|
||||
|
||||
import copy
|
||||
|
||||
inner_renderer = copy.copy(self)
|
||||
cell = inner_renderer.render(cell)
|
||||
|
||||
# If the cell is just one <p>, unwrap it.
|
||||
m = re.match("<p>(.*)</p>$", cell)
|
||||
if m:
|
||||
cell = m.group(1)
|
||||
|
||||
self.lit(cell)
|
||||
self.lit("</" + col_tag + ">\n")
|
||||
self.lit("</tr>\n")
|
||||
self.lit("</" + part_tag + ">\n")
|
||||
self.lit("</table>\n")
|
||||
|
||||
|
||||
# Define a new helper method that would be an in-place replacement
|
||||
# for commonmark.commonmark.
|
||||
def commonmark_to_html(markup):
|
||||
parser = ParserWithTables()
|
||||
ast = parser.parse(markup)
|
||||
return RendererWithTables().render(ast)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the parser on STDIN and write to STDOUT.
|
||||
import sys
|
||||
|
||||
parser = ParserWithTables()
|
||||
ast = parser.parse(sys.stdin.read())
|
||||
print(RendererWithTables().render(ast))
|
||||
13
euporie/main.py
Normal file
13
euporie/main.py
Normal file
@@ -0,0 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
|
||||
from .app import App
|
||||
|
||||
|
||||
def main():
|
||||
"""Launch the application."""
|
||||
asyncio.run(App.launch())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
55
euporie/mdtable.py
Normal file
55
euporie/mdtable.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import Any
|
||||
|
||||
import rich.markdown
|
||||
from rich.console import Console, ConsoleOptions, RenderResult
|
||||
from rich.table import Table as RichTable
|
||||
|
||||
from euporie.config import config
|
||||
from euporie.libs.commonmark_extensions.tables import ParserWithTables
|
||||
|
||||
rich.markdown.Parser = ParserWithTables
|
||||
|
||||
|
||||
class Table(rich.markdown.MarkdownElement):
|
||||
"""A table."""
|
||||
|
||||
style_name = "markdown.table"
|
||||
new_line = False
|
||||
|
||||
@classmethod
|
||||
def create(cls, markdown: rich.markdown.Markdown, table: Any) -> "Table":
|
||||
return cls(table)
|
||||
|
||||
def __init__(self, contents) -> None:
|
||||
self.contents = contents.table
|
||||
self.column_properties = contents.column_properties
|
||||
self.elements = []
|
||||
|
||||
def __rich_console__(
|
||||
self, console: Console, options: ConsoleOptions
|
||||
) -> RenderResult:
|
||||
|
||||
table = RichTable()
|
||||
|
||||
def node_to_text(node, justify=None):
|
||||
"""Create a rich markdown object, then add the parsed node to it."""
|
||||
node_md = rich.markdown.Markdown(
|
||||
"",
|
||||
code_theme=config.pygments_style,
|
||||
justify=justify,
|
||||
)
|
||||
node_md.parsed = node
|
||||
return node_md
|
||||
|
||||
for i, col in enumerate(self.contents[0][0]):
|
||||
justify = self.column_properties.get(i, {}).get("align")
|
||||
table.add_column(node_to_text(col, justify=justify), justify=justify)
|
||||
|
||||
for row in self.contents[1]:
|
||||
table.add_row(*[node_to_text(cell, justify=justify) for cell in row])
|
||||
|
||||
yield table
|
||||
|
||||
|
||||
rich.markdown.Markdown.elements["table"] = Table
|
||||
336
euporie/notebook.py
Normal file
336
euporie/notebook.py
Normal file
@@ -0,0 +1,336 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
import copy
|
||||
import threading
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
import nbformat
|
||||
from jupyter_client import KernelManager
|
||||
from jupyter_client.kernelspec import KernelSpecManager
|
||||
from prompt_toolkit.application.current import get_app
|
||||
from prompt_toolkit.completion.base import CompleteEvent, Completer, Completion
|
||||
from prompt_toolkit.document import Document
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
from prompt_toolkit.layout.containers import Container, HSplit, Window
|
||||
from prompt_toolkit.layout.controls import FormattedTextControl
|
||||
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
||||
from prompt_toolkit.layout.margins import NumberedMargin
|
||||
from prompt_toolkit.widgets import Box, Label, RadioList
|
||||
|
||||
from euporie.config import config
|
||||
|
||||
from .cell import Cell
|
||||
from .scroll import ScrollingContainer
|
||||
|
||||
|
||||
class KernelCompleter(Completer):
|
||||
def __init__(self, nb):
|
||||
self.nb = nb
|
||||
|
||||
def get_completions(self):
|
||||
pass
|
||||
|
||||
async def get_completions_async(
|
||||
self, document: Document, complete_event: CompleteEvent
|
||||
):
|
||||
if self.nb.kc:
|
||||
msg_id = self.nb.kc.complete(
|
||||
code=document.text,
|
||||
cursor_pos=document.cursor_position,
|
||||
)
|
||||
msg = await self.nb.kc._async_get_shell_msg()
|
||||
if msg["parent_header"].get("msg_id") == msg_id:
|
||||
# run_in_terminal(lambda: print(msg))
|
||||
content = msg.get("content", {})
|
||||
rel_start_position = (
|
||||
content.get("cursor_start", 0) - document.cursor_position
|
||||
)
|
||||
for match in content.get("matches", []):
|
||||
yield Completion(match, start_position=rel_start_position)
|
||||
|
||||
|
||||
class Notebook:
|
||||
def __init__(self, path):
|
||||
|
||||
self.char_px_y = 32
|
||||
self.char_px_x = 15
|
||||
|
||||
self.output_cache = {}
|
||||
|
||||
self.dirty = False
|
||||
self.kernel_status = "starting"
|
||||
self.line_numbers = True
|
||||
|
||||
self.path = Path(path).expanduser()
|
||||
if self.path.exists():
|
||||
self.json = nbformat.read(self.path, as_version=4)
|
||||
else:
|
||||
self.json = nbformat.v4.new_notebook()
|
||||
# Ensure there is always at least one cell
|
||||
if not self.json.setdefault("cells", []):
|
||||
self.json["cells"] = [nbformat.v4.new_code_cell()]
|
||||
|
||||
self.page = ScrollingContainer(
|
||||
children=self.cell_renderers,
|
||||
max_content_width=D(preferred=config.max_notebook_width),
|
||||
)
|
||||
self.container = Box(self.page, padding=0, padding_left=1)
|
||||
self.container.container.key_bindings = self.keybindings()
|
||||
|
||||
self.clipboard = []
|
||||
|
||||
self.completer = KernelCompleter(self)
|
||||
self.km = self.kc = None
|
||||
|
||||
def setup_loop():
|
||||
"""Set up a thread with an event loop to listen for kernel responses."""
|
||||
# Create and set kernel loop
|
||||
self.kernel_loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self.kernel_loop)
|
||||
# Start kernel
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.start_kernel(),
|
||||
self.kernel_loop,
|
||||
)
|
||||
# Now we wait
|
||||
self.kernel_loop.run_forever()
|
||||
|
||||
# Run the kernel event loop in a new thread
|
||||
self.kernel_thread = threading.Thread(target=setup_loop)
|
||||
self.kernel_thread.start()
|
||||
|
||||
async def start_kernel(self):
|
||||
|
||||
if not self.kernel_name:
|
||||
self.change_kernel()
|
||||
return
|
||||
|
||||
# Create a kernel manager for this notebook
|
||||
self.km = KernelManager(kernel_name=self.kernel_name)
|
||||
try:
|
||||
await self.km._async_start_kernel()
|
||||
except Exception as e:
|
||||
get_app().dialog("Error Starting Kernel", Label(e.__repr__()), {"OK": None})
|
||||
self.kc = None
|
||||
self.kernel_status = "error"
|
||||
else:
|
||||
self.kc = self.km.client()
|
||||
self.kc.start_channels()
|
||||
self.kernel_status = "idle"
|
||||
get_app().invalidate()
|
||||
|
||||
def restart_kernel(self):
|
||||
async def restart():
|
||||
if self.km:
|
||||
await self.km._async_shutdown_kernel()
|
||||
await self.start_kernel()
|
||||
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
restart(),
|
||||
self.kernel_loop,
|
||||
)
|
||||
|
||||
@property
|
||||
def kernel_name(self):
|
||||
return self.json.get("metadata", {}).get("kernelspec", {}).get("name")
|
||||
|
||||
def change_kernel(self):
|
||||
def change_kernel_cb():
|
||||
name = options.current_value
|
||||
spec = kernel_specs.get(name, {}).get("spec", {})
|
||||
self.json.setdefault("metadata", {})["kernelspec"] = {
|
||||
"display_name": spec["display_name"],
|
||||
"language": spec["language"],
|
||||
"name": name,
|
||||
}
|
||||
self.restart_kernel()
|
||||
|
||||
if self.km:
|
||||
kernel_specs = self.km.kernel_spec_manager.get_all_specs()
|
||||
else:
|
||||
kernel_specs = KernelSpecManager().get_all_specs()
|
||||
options = RadioList(
|
||||
[
|
||||
(
|
||||
kernel_name,
|
||||
kernel_spec.get("spec", {}).get("display_name", kernel_name),
|
||||
)
|
||||
for kernel_name, kernel_spec in kernel_specs.items()
|
||||
]
|
||||
)
|
||||
get_app().dialog(
|
||||
title="Select Kernel",
|
||||
body=HSplit(
|
||||
[
|
||||
Label("Please select a kernel:"),
|
||||
options,
|
||||
]
|
||||
),
|
||||
buttons={
|
||||
"Select": change_kernel_cb,
|
||||
"Cancel": None,
|
||||
},
|
||||
)
|
||||
|
||||
@property
|
||||
def cell_renderers(self):
|
||||
return [
|
||||
partial(Cell, i, cell_json, self)
|
||||
for i, cell_json in enumerate(self.json["cells"])
|
||||
]
|
||||
|
||||
def keybindings(self):
|
||||
kb = KeyBindings()
|
||||
|
||||
@kb.add("c-s")
|
||||
def save(event):
|
||||
self.save()
|
||||
|
||||
@kb.add("a")
|
||||
def add_above(event):
|
||||
self.add(0)
|
||||
|
||||
@kb.add("b")
|
||||
def add_below(event):
|
||||
self.add(1)
|
||||
|
||||
@kb.add("d", "d")
|
||||
def delete(event):
|
||||
self.delete()
|
||||
|
||||
@kb.add("x")
|
||||
def cut(event):
|
||||
self.cut()
|
||||
|
||||
@kb.add("c")
|
||||
def copy(event):
|
||||
self.copy()
|
||||
|
||||
@kb.add("v")
|
||||
def paste(event):
|
||||
self.paste()
|
||||
|
||||
@kb.add("m")
|
||||
def to_markdown(event):
|
||||
self.cell.set_cell_type("markdown")
|
||||
self.cell.clear_output()
|
||||
|
||||
@kb.add("y")
|
||||
def to_code(event):
|
||||
self.cell.set_cell_type("code")
|
||||
|
||||
@kb.add("r")
|
||||
def to_raw(event):
|
||||
self.cell.set_cell_type("raw")
|
||||
self.cell.clear_output()
|
||||
|
||||
@kb.add("l")
|
||||
def line_nos(event):
|
||||
self.line_numbers = not self.line_numbers
|
||||
for cell in self.page.child_cache.values():
|
||||
cell.input_box.window.left_margins = (
|
||||
[NumberedMargin()] if self.line_numbers else []
|
||||
)
|
||||
|
||||
return kb
|
||||
|
||||
@property
|
||||
def cell(self):
|
||||
return self.page.get_child()
|
||||
|
||||
def add(self, offset):
|
||||
index = self.page.selected_index + offset
|
||||
self.json["cells"].insert(
|
||||
index,
|
||||
nbformat.v4.new_code_cell(),
|
||||
)
|
||||
self.dirty = True
|
||||
self.refresh(index=index)
|
||||
|
||||
def cut(self, index=None):
|
||||
if index is None:
|
||||
index = self.page.selected_index
|
||||
self.copy(index)
|
||||
self.delete(index)
|
||||
|
||||
def copy(self, index=None):
|
||||
if index is None:
|
||||
index = self.page.selected_index
|
||||
self.clipboard = copy.deepcopy(self.json["cells"][index : index + 1])
|
||||
|
||||
def paste(self, index=None):
|
||||
if index is None:
|
||||
index = self.page.selected_index
|
||||
self.json["cells"][index + 1 : index + 1] = copy.deepcopy(self.clipboard)
|
||||
self.dirty = True
|
||||
self.refresh(index + 1)
|
||||
|
||||
def delete(self, index=None):
|
||||
if len(self.json["cells"]) > 1:
|
||||
if index is None:
|
||||
index = self.page.selected_index
|
||||
del self.json["cells"][index]
|
||||
self.dirty = True
|
||||
self.refresh()
|
||||
|
||||
def refresh(self, index=None):
|
||||
if index is None:
|
||||
index = self.page.selected_index
|
||||
self.page.children = self.cell_renderers
|
||||
self.page.reset()
|
||||
self.page._set_selected_index(index, force=True)
|
||||
|
||||
def save(self):
|
||||
self.json = nbformat.from_dict(self.json)
|
||||
nbformat.write(nb=self.json, fp=self.path)
|
||||
self.dirty = False
|
||||
|
||||
def close(self, cb):
|
||||
if self.dirty:
|
||||
self.unsaved(cb)
|
||||
else:
|
||||
self.really_close(cb)
|
||||
|
||||
def really_close(self, cb):
|
||||
# Tell the kernel to shutdown
|
||||
if self.kc is not None:
|
||||
self.kc.shutdown()
|
||||
# Tell the event loop in the kernel monitoring thread to shutdown
|
||||
self.kernel_loop.call_soon_threadsafe(self.kernel_loop.stop)
|
||||
# Close the kernel monitoring thread
|
||||
self.kernel_thread.join()
|
||||
# Tell the app we've closed
|
||||
cb()
|
||||
|
||||
def unsaved(self, cb):
|
||||
app = get_app()
|
||||
|
||||
def yes_cb():
|
||||
self.save()
|
||||
self.really_close(cb)
|
||||
|
||||
def no_cb():
|
||||
self.really_close(cb)
|
||||
|
||||
app.dialog(
|
||||
title="Unsaved Changes",
|
||||
body=Window(
|
||||
FormattedTextControl(
|
||||
[
|
||||
("bold", self.path.name),
|
||||
("", " has unsaved changes\n"),
|
||||
("", "Do you want to save your changes?"),
|
||||
]
|
||||
),
|
||||
dont_extend_height=True,
|
||||
),
|
||||
buttons={
|
||||
"Yes": yes_cb,
|
||||
"No": no_cb,
|
||||
"Cancel": None,
|
||||
},
|
||||
)
|
||||
|
||||
def __pt_container__(self) -> Container:
|
||||
return self.container
|
||||
136
euporie/output.py
Normal file
136
euporie/output.py
Normal file
@@ -0,0 +1,136 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from pathlib import PurePath
|
||||
|
||||
from prompt_toolkit.layout import Container, Window
|
||||
from prompt_toolkit.layout.controls import FormattedTextControl
|
||||
from prompt_toolkit.widgets import Label, TextArea
|
||||
from rich.markdown import Markdown
|
||||
|
||||
from euporie import mdtable # noqa F401
|
||||
from euporie.ansi import ANSI
|
||||
from euporie.config import config
|
||||
from euporie.control import HTMLControl, ImageControl, RichControl, SVGControl
|
||||
|
||||
BLING_SCORES = {
|
||||
"image/*": 0,
|
||||
"text/html": 1,
|
||||
"text/x-markdown": 2,
|
||||
"text/x-python-traceback": 3,
|
||||
"text/stderr": 4,
|
||||
"text/*": 5,
|
||||
"*": 6,
|
||||
}
|
||||
|
||||
|
||||
def bling(item):
|
||||
mime, _ = item
|
||||
for bling_path, score in BLING_SCORES.items():
|
||||
if PurePath(mime).match(bling_path):
|
||||
return score
|
||||
|
||||
|
||||
class Output:
|
||||
def __init__(self, index, json, parent=None):
|
||||
self.index = index
|
||||
self.json = json
|
||||
self.parent = parent
|
||||
self.style = ""
|
||||
self.content = None
|
||||
|
||||
# Sort data first so there is more bling first
|
||||
for mime, datum in sorted(self.data.items(), key=bling):
|
||||
|
||||
mime_path = PurePath(mime)
|
||||
|
||||
if mime_path.match("image/svg+xml"):
|
||||
control = SVGControl(
|
||||
datum,
|
||||
render_args=dict(cell=self.parent, output_index=index),
|
||||
)
|
||||
if control.renderer:
|
||||
self.content = Window(control, height=control.rendered_lines)
|
||||
break
|
||||
|
||||
if mime_path.match("image/*"):
|
||||
control = ImageControl(
|
||||
datum,
|
||||
render_args=dict(cell=self.parent, output_index=index),
|
||||
)
|
||||
if control.renderer:
|
||||
self.content = Window(control, height=control.rendered_lines)
|
||||
break
|
||||
|
||||
if mime_path.match("text/html"):
|
||||
control = HTMLControl(datum)
|
||||
if control.renderer:
|
||||
self.content = Window(control, height=control.rendered_lines)
|
||||
break
|
||||
else:
|
||||
continue # Use plain text rendering instead
|
||||
|
||||
if mime_path.match("text/x-markdown"):
|
||||
control = RichControl(
|
||||
Markdown(
|
||||
datum,
|
||||
code_theme=config.pygments_style,
|
||||
inline_code_theme=config.pygments_style,
|
||||
)
|
||||
)
|
||||
self.content = Window(control, height=control.rendered_lines)
|
||||
break
|
||||
|
||||
if mime_path.match("text/x-python-traceback"):
|
||||
control = FormattedTextControl(ANSI(datum))
|
||||
self.content = Window(control)
|
||||
break
|
||||
|
||||
if mime_path.match("text/stderr"):
|
||||
self.content = TextArea(
|
||||
datum.rstrip(), wrap_lines=True, style="bg:darkred"
|
||||
)
|
||||
break
|
||||
|
||||
if mime_path.match("text/*"):
|
||||
# Use formatted text so ansi colour codes are displayed as colours
|
||||
control = FormattedTextControl(ANSI(datum.rstrip()))
|
||||
self.content = Window(control, wrap_lines=True)
|
||||
break
|
||||
|
||||
else:
|
||||
datum = sorted(self.data.items(), key=bling)[-1][1]
|
||||
self.content = Label(ANSI(str(datum).rstrip()))
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
output_type = self.json.get("output_type", "unknown")
|
||||
if output_type == "stream":
|
||||
return {f'text/{self.json.get("name")}': self.json.get("text")}
|
||||
elif output_type == "error":
|
||||
return {"text/x-python-traceback": "\n".join(self.json.get("traceback"))}
|
||||
else:
|
||||
return self.json.get("data", {})
|
||||
|
||||
@property
|
||||
def metadata(self):
|
||||
return self.json.get("metadata", {})
|
||||
|
||||
def get_key_bindings(self, *args, **kwargs):
|
||||
return self.content.get_key_bindings(*args, **kwargs)
|
||||
|
||||
def get_children(self, *args, **kwargs):
|
||||
return self.content.get_children(*args, **kwargs)
|
||||
|
||||
def preferred_width(self, *args, **kwargs):
|
||||
return self.content.preferred_width(*args, **kwargs)
|
||||
|
||||
def preferred_height(self, *args, **kwargs):
|
||||
return self.content.preferred_height(*args, **kwargs)
|
||||
|
||||
def write_to_screen(self, *args, **kwargs):
|
||||
return self.content.write_to_screen(*args, **kwargs)
|
||||
|
||||
def reset(self, *args, **kwargs):
|
||||
return self.content.reset(*args, **kwargs)
|
||||
|
||||
def __pt_container__(self) -> Container:
|
||||
return self.content
|
||||
552
euporie/render.py
Normal file
552
euporie/render.py
Normal file
@@ -0,0 +1,552 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from importlib import import_module
|
||||
from math import ceil
|
||||
from shutil import which
|
||||
|
||||
import rich
|
||||
from PIL import Image
|
||||
from prompt_toolkit.application import get_app
|
||||
|
||||
from euporie.box import Border
|
||||
|
||||
|
||||
class DataRenderer:
|
||||
def __init__(self, **kwargs):
|
||||
|
||||
self.width = 1
|
||||
self.height = 1
|
||||
for kwarg, value in kwargs.items():
|
||||
setattr(self, kwarg, value)
|
||||
self.load()
|
||||
|
||||
def load(self):
|
||||
pass
|
||||
|
||||
# async def _render(self, mime, data, **kwargs):
|
||||
def render(self, data, width, height, render_args=None):
|
||||
|
||||
self.width = width
|
||||
self.height = height
|
||||
if render_args is None:
|
||||
render_args = {}
|
||||
self.render_args = render_args
|
||||
|
||||
self.load()
|
||||
ansi_data = self.process(data)
|
||||
# data = await self.process(data)
|
||||
return ansi_data
|
||||
|
||||
@classmethod
|
||||
def select(cls, *args, **kwargs):
|
||||
sub_renderers = cls.__subclasses__()
|
||||
if sub_renderers:
|
||||
for Renderer in sub_renderers:
|
||||
renderer = Renderer(*args, **kwargs)
|
||||
if not hasattr(renderer, "validate"):
|
||||
# It's just a grouping class
|
||||
continue
|
||||
if renderer.validate():
|
||||
return renderer
|
||||
else:
|
||||
renderer = cls()
|
||||
if renderer.validate():
|
||||
return renderer
|
||||
|
||||
|
||||
class SubprocessRenderMixin:
|
||||
use_tempfile = False
|
||||
to_string = True
|
||||
|
||||
def validate(self):
|
||||
return which(self.cmd[0])
|
||||
|
||||
def process(self, data):
|
||||
# async def process(self, data):
|
||||
|
||||
cmd = list(map(str, self.cmd))
|
||||
|
||||
if isinstance(data, str):
|
||||
data = data.encode()
|
||||
|
||||
if self.use_tempfile:
|
||||
# If the command cannot read from stdin, create a temporary file to pass to
|
||||
# the command
|
||||
tfile = tempfile.NamedTemporaryFile(delete=False)
|
||||
tfile.write(data)
|
||||
tfile.close()
|
||||
cmd.append(tfile.name)
|
||||
|
||||
# TODO render asynchronously
|
||||
# proc = await asyncio.create_subprocess_shell(
|
||||
# " ".join(cmd),
|
||||
# stdout=asyncio.subprocess.PIPE,
|
||||
# stdin=asyncio.subprocess.PIPE,
|
||||
# stderr=asyncio.subprocess.DEVNULL,
|
||||
# )
|
||||
# stdout, stderr = await proc.communicate(data)
|
||||
|
||||
cmd = list(cmd)
|
||||
output = subprocess.check_output(cmd, input=data)
|
||||
|
||||
# TODO Log any stderr
|
||||
# print(stderr)
|
||||
|
||||
# Clean up any temporary file
|
||||
if self.use_tempfile:
|
||||
tfile.close()
|
||||
os.unlink(tfile.name)
|
||||
|
||||
if self.to_string:
|
||||
output = output.decode()
|
||||
|
||||
return output
|
||||
|
||||
|
||||
class PythonRenderMixin:
|
||||
def validate(self):
|
||||
try:
|
||||
import_module(self.module) # noqa
|
||||
except ModuleNotFoundError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
class RichRendererMixin(DataRenderer):
|
||||
def load(self):
|
||||
self.console = rich.get_console()
|
||||
|
||||
def process(self, data):
|
||||
buffer = self.console.render(
|
||||
data,
|
||||
self.console.options.update(max_width=self.width),
|
||||
)
|
||||
self.rendered_lines = self.console._render_buffer(buffer)
|
||||
return self.rendered_lines
|
||||
|
||||
|
||||
class RichRenderer(RichRendererMixin):
|
||||
def validate(self):
|
||||
return True
|
||||
|
||||
|
||||
class HTMLRenderer(DataRenderer):
|
||||
pass
|
||||
|
||||
|
||||
class html_w3m(HTMLRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = ["w3m", "-T", "text/html", "-cols", f"{self.width}"]
|
||||
|
||||
|
||||
class html_elinks(HTMLRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = [
|
||||
"elinks",
|
||||
"-dump",
|
||||
"-dump-width",
|
||||
f"{self.width}",
|
||||
"-no-numbering",
|
||||
"-force-html",
|
||||
"-no-references",
|
||||
]
|
||||
|
||||
|
||||
class html_lynx(HTMLRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = ["lynx", "-dump", "-stdin", f"-width={self.width}"]
|
||||
|
||||
|
||||
class html_links(HTMLRenderer, SubprocessRenderMixin):
|
||||
use_tempfile = True
|
||||
|
||||
def load(self):
|
||||
self.cmd = ["links", "-width", self.width, "-dump"]
|
||||
|
||||
|
||||
class html_mtable_py(RichRendererMixin, HTMLRenderer, PythonRenderMixin):
|
||||
"""Converts HTML tables to markdown, then renders markdown with rich."""
|
||||
|
||||
module = "mtable"
|
||||
|
||||
def process(self, data):
|
||||
from mtable import MarkupTable
|
||||
|
||||
return super().process(
|
||||
rich.markdown.Markdown(
|
||||
"\n\n".join([table.to_md() for table in MarkupTable.from_html(data)])
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ImageRenderer(DataRenderer):
|
||||
def __init__(self, *args, image=None, **kwargs):
|
||||
self.image = image
|
||||
self.px = self.py = 0
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def render(self, data, width=None, height=None, render_args=None):
|
||||
|
||||
img_bytes = io.BytesIO(base64.b64decode(data))
|
||||
try:
|
||||
self.image = Image.open(img_bytes)
|
||||
except IOError:
|
||||
pass
|
||||
else:
|
||||
orig_px, orig_py = self.image.size
|
||||
|
||||
# Scale image down if it is larger than available width
|
||||
app = get_app()
|
||||
if hasattr(app, "app"):
|
||||
char_px = app.app.char_px
|
||||
char_py = app.app.char_py
|
||||
else:
|
||||
char_px, char_py = get_app().char_size_px
|
||||
|
||||
pixels_per_col = orig_px / char_px
|
||||
# Only down-scale images
|
||||
scaling_factor = min(1, width / pixels_per_col)
|
||||
# Pixel & character values need to be integers
|
||||
self.px = ceil(orig_px * scaling_factor)
|
||||
self.py = ceil(orig_py * scaling_factor)
|
||||
|
||||
width = ceil(self.px / char_px)
|
||||
height = ceil(self.py / char_py)
|
||||
|
||||
return super().render(data, width=width, height=height, render_args=render_args)
|
||||
|
||||
|
||||
class SixelMixerRenderer(ImageRenderer):
|
||||
def validate(self):
|
||||
return get_app().has_sixel_graphics
|
||||
|
||||
def process(self, data):
|
||||
"""Add in cursor movement commands to correctly place sixels"""
|
||||
output = ""
|
||||
# Add text representation
|
||||
if self.render_args.get("cell").obscured():
|
||||
output += AnsiImageRenderer.select(image=self.image).render(
|
||||
data,
|
||||
width=self.width,
|
||||
height=self.height,
|
||||
render_args=self.render_args,
|
||||
)
|
||||
else:
|
||||
output += "\n".join([" " * self.width] * self.height)
|
||||
|
||||
# data = super().process(data)
|
||||
# Save cursor position
|
||||
output += "\x1b[s"
|
||||
# Move cursor back to top left of image's space
|
||||
output += f"\x1b[{self.height-1}A\x1b[{self.width}D"
|
||||
# Add sixels
|
||||
# output += super().process(data)
|
||||
sixel = SixelRenderer.select(image=self.image).render(
|
||||
data,
|
||||
width=self.width,
|
||||
height=self.height,
|
||||
render_args=self.render_args,
|
||||
)
|
||||
output += sixel
|
||||
# Restore cursor position
|
||||
output += "\x1b[u"
|
||||
return output
|
||||
|
||||
|
||||
class SixelRenderer(DataRenderer):
|
||||
def validate(self):
|
||||
return get_app().has_sixel_graphics and super().validate()
|
||||
|
||||
|
||||
class img_sixel_imagemagik(SixelRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
if not hasattr(self, "px"):
|
||||
self.px = self.py = 0
|
||||
self.bg_color = "#FFFFFF"
|
||||
self.cmd = [
|
||||
"convert",
|
||||
"-",
|
||||
"-geometry",
|
||||
f"{self.px}x{self.py}",
|
||||
"-background",
|
||||
get_app().bg_color,
|
||||
"-flatten",
|
||||
"sixel:-",
|
||||
]
|
||||
|
||||
def process(self, data):
|
||||
data = base64.b64decode(data)
|
||||
data = super().process(data)
|
||||
return data
|
||||
|
||||
|
||||
class img_sixel_timg_py(SixelRenderer, ImageRenderer, PythonRenderMixin):
|
||||
module = "timg"
|
||||
|
||||
def process(self, data):
|
||||
import timg
|
||||
|
||||
self.image.thumbnail((self.px, self.px))
|
||||
# Set transparent colour to terminal background
|
||||
if self.image.mode in ("RGBA", "LA") or (
|
||||
self.image.mode == "P" and "transparency" in self.image.info
|
||||
):
|
||||
alpha = self.image.convert("RGBA").getchannel("A")
|
||||
bg = Image.new("RGBA", self.image.size, get_app().bg_color)
|
||||
bg.paste(self.image, mask=alpha)
|
||||
self.image = bg
|
||||
self.image = self.image.convert("P", palette=Image.ADAPTIVE, colors=16).convert(
|
||||
"RGB", palette=Image.ADAPTIVE, colors=16
|
||||
)
|
||||
data = timg.SixelMethod(self.image).to_string()
|
||||
return data
|
||||
|
||||
|
||||
class img_sixel_teimpy(SixelRenderer, ImageRenderer, PythonRenderMixin):
|
||||
module = "teimpy"
|
||||
|
||||
def process(self, data):
|
||||
import numpy as np
|
||||
import teimpy
|
||||
|
||||
# data = super().process(data)
|
||||
self.image.thumbnail((self.px, self.px))
|
||||
# Set transparent colour to terminal background
|
||||
if self.image.mode in ("RGBA", "LA") or (
|
||||
self.image.mode == "P" and "transparency" in self.image.info
|
||||
):
|
||||
alpha = self.image.convert("RGBA").getchannel("A")
|
||||
bg = Image.new("RGBA", self.image.size, get_app().bg_color)
|
||||
bg.paste(self.image, mask=alpha)
|
||||
self.image = bg.convert("RGB")
|
||||
data = teimpy.get_drawer(teimpy.Mode.SIXEL).draw(np.asarray(self.image))
|
||||
return data
|
||||
|
||||
|
||||
class img_kitty(ImageRenderer):
|
||||
def validate(self):
|
||||
return get_app().has_kitty_graphics
|
||||
|
||||
def load(self):
|
||||
pass
|
||||
|
||||
def process(self, data):
|
||||
|
||||
output = ""
|
||||
|
||||
# Create image id for kitty using Cantor pairing of cell id and output index
|
||||
a = self.render_args.get("cell").index
|
||||
b = self.render_args.get("output_index")
|
||||
image_id = int(0.5 * (a + b) * (a + b + 1) + b)
|
||||
|
||||
if self.render_args.get("cell").obscured():
|
||||
output += AnsiImageRenderer.select().render(
|
||||
data, width=self.width, height=self.height
|
||||
)
|
||||
else:
|
||||
# Delete existing image in this space
|
||||
# output += f"\001\x1b_Ga=d,d=i,i={image_id}\x1b\\\002"
|
||||
# Fill image space
|
||||
output += "\n".join([" " * self.width] * self.height)
|
||||
# Save cursor position
|
||||
output += "\x1b[s"
|
||||
# Move back to start of image position
|
||||
output += f"\x1b[{self.height-1}A\x1b[{self.width}D"
|
||||
# Send the image
|
||||
params = {
|
||||
"a": "T", # We are sending an image
|
||||
"q": 1, # No backchat
|
||||
"f": "100", # Sending a PNG image
|
||||
"t": "d", # Transferring the image directly
|
||||
"i": image_id,
|
||||
# 'p': 1,
|
||||
"m": 1, # Data will be chunked
|
||||
"c": self.width,
|
||||
"r": self.height,
|
||||
"z": -(2 ** 30) - 1, # Put image under everything
|
||||
}
|
||||
# Remove newlines from base64 image data
|
||||
data = "".join(data.split("\n"))
|
||||
while data:
|
||||
chunk, data = data[:4096], data[4096:]
|
||||
params["m"] = 1 if data else 0
|
||||
param_str = ",".join(
|
||||
[f"{key}={value}" for key, value in params.items()]
|
||||
)
|
||||
output += f"\001\x1b_G{param_str};{chunk}\x1b\\\002"
|
||||
# Restore cursor position
|
||||
output += "\x1b[u"
|
||||
return output
|
||||
|
||||
|
||||
class AnsiImageRenderer(ImageRenderer):
|
||||
def process(self, data):
|
||||
data = base64.b64decode(data)
|
||||
# if hasattr(super(), 'process'):
|
||||
data = super().process(data)
|
||||
return data
|
||||
# return data
|
||||
|
||||
|
||||
class img_ansi_timg(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
def validate(self):
|
||||
# There is a python package called timg which provided an executable
|
||||
# That's not the one we are aftere here, so check if it is installed
|
||||
try:
|
||||
import timg # noqa F401
|
||||
except ModuleNotFoundError:
|
||||
return super().validate()
|
||||
else:
|
||||
return False
|
||||
|
||||
def load(self):
|
||||
self.cmd = [
|
||||
"timg",
|
||||
f"-g{self.width}x{self.width}",
|
||||
"--compress",
|
||||
"-b",
|
||||
get_app().bg_color,
|
||||
"-pq",
|
||||
"--threads=-1",
|
||||
"-",
|
||||
]
|
||||
|
||||
|
||||
class img_ansi_catimg(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = ["catimg", "-w", self.width * 2, "-"]
|
||||
|
||||
|
||||
class img_ansi_icat(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
use_tempfile = True
|
||||
|
||||
def load(self):
|
||||
self.cmd = ["icat", "-w", self.width, "--mode", "24bit"]
|
||||
|
||||
|
||||
class ansi_tiv(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
use_tempfile = True
|
||||
|
||||
def load(self):
|
||||
self.cmd = ["tiv", "-w", self.width, "-h", self.height]
|
||||
|
||||
|
||||
class img_ansi_timg_py(AnsiImageRenderer, ImageRenderer, PythonRenderMixin):
|
||||
module = "timg"
|
||||
|
||||
def process(self, data):
|
||||
import timg
|
||||
|
||||
self.image.thumbnail((self.width * 2, self.height * 2))
|
||||
# Set transparent colour to terminal background
|
||||
if (
|
||||
bg_color := get_app().bg_color
|
||||
and self.image.mode in ("RGBA", "LA")
|
||||
or (self.image.mode == "P" and "transparency" in self.image.info)
|
||||
):
|
||||
alpha = self.image.convert("RGBA").getchannel("A")
|
||||
bg = Image.new("RGBA", self.image.size, bg_color)
|
||||
bg.paste(self.image, mask=alpha)
|
||||
self.image = bg
|
||||
self.image = self.image.convert("P", palette=Image.ADAPTIVE, colors=16).convert(
|
||||
"RGB", palette=Image.ADAPTIVE, colors=16
|
||||
)
|
||||
data = timg.Ansi24HblockMethod(self.image).to_string()
|
||||
return data
|
||||
|
||||
|
||||
class img_ansi_img2unicode_py(AnsiImageRenderer, ImageRenderer, PythonRenderMixin):
|
||||
module = "img2unicode"
|
||||
|
||||
def process(self, data):
|
||||
from img2unicode import FastQuadDualOptimizer, Renderer
|
||||
|
||||
output = io.StringIO()
|
||||
Renderer(
|
||||
FastQuadDualOptimizer(), max_w=self.width, max_h=self.height
|
||||
).render_terminal(self.image, output)
|
||||
output.seek(0)
|
||||
return output.read()
|
||||
|
||||
|
||||
class img_ansi_viu(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = ["viu", "-w", self.width, "-s", "-"]
|
||||
|
||||
|
||||
class img_ansi_jp2a(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
def load(self):
|
||||
self.cmd = ["jp2a", "--color", f"--height={self.height}", "-"]
|
||||
|
||||
|
||||
class img_ansi_img2txt(AnsiImageRenderer, ImageRenderer, SubprocessRenderMixin):
|
||||
use_tempfile = True
|
||||
|
||||
def load(self):
|
||||
self.cmd = ["img2txt", "-W", self.width, "-H", self.height]
|
||||
|
||||
|
||||
class img_ansi_placeholder(AnsiImageRenderer, ImageRenderer):
|
||||
msg = "[Image]"
|
||||
|
||||
def validate(self):
|
||||
# This is always an option
|
||||
return True
|
||||
|
||||
def process(self, data):
|
||||
b = Border
|
||||
t = len(self.msg)
|
||||
w = max(self.width, t + 4)
|
||||
h = max(3, self.height)
|
||||
output = b.TOP_LEFT + (b.HORIZONTAL * (w - 2)) + b.TOP_RIGHT + "\n"
|
||||
for i in range((h - 3) // 2 + 1):
|
||||
output += b.VERTICAL + (" " * (w - 2)) + b.VERTICAL + "\n"
|
||||
output += b.VERTICAL + " "
|
||||
output += " " * ((self.width - 4 - t) // 2)
|
||||
output += self.msg
|
||||
output += " " * ((self.width - 4 - t) - (self.width - 4 - t) // 2)
|
||||
output += " " + b.VERTICAL + "\n"
|
||||
for i in range((h - 3) - ((h - 3) // 2)):
|
||||
output += b.VERTICAL + (" " * (w - 2)) + b.VERTICAL + "\n"
|
||||
output += b.BOTTOM_LEFT + (b.HORIZONTAL * (w - 2)) + b.BOTTOM_RIGHT
|
||||
return output
|
||||
|
||||
|
||||
class SVGRenderer(DataRenderer):
|
||||
pass
|
||||
|
||||
|
||||
class svg_librsvg(SVGRenderer, PythonRenderMixin):
|
||||
module = "cairosvg"
|
||||
|
||||
def process(self, data):
|
||||
import cairosvg
|
||||
|
||||
data = cairosvg.surface.PNGSurface.convert(data, write_to=None)
|
||||
data = base64.b64encode(data)
|
||||
return ImageRenderer.select().render(
|
||||
data, self.width, self.height, self.render_args
|
||||
)
|
||||
|
||||
|
||||
class svg_imagemagik(SVGRenderer, SubprocessRenderMixin):
|
||||
to_string = False
|
||||
|
||||
def load(self):
|
||||
self.cmd = [
|
||||
"convert",
|
||||
"-",
|
||||
"PNG:-",
|
||||
]
|
||||
|
||||
def process(self, data):
|
||||
data = super().process(data)
|
||||
data = base64.b64encode(data)
|
||||
return ImageRenderer.select().render(
|
||||
data, self.width, self.height, self.render_args
|
||||
)
|
||||
563
euporie/scroll.py
Normal file
563
euporie/scroll.py
Normal file
@@ -0,0 +1,563 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from collections import namedtuple
|
||||
from typing import Callable, Dict, List, Optional, Sequence, Union
|
||||
|
||||
from prompt_toolkit.application.current import get_app
|
||||
from prompt_toolkit.data_structures import Point
|
||||
from prompt_toolkit.filters import FilterOrBool, to_filter
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
from prompt_toolkit.layout.containers import Container, Window, to_container
|
||||
from prompt_toolkit.layout.dimension import AnyDimension, Dimension, to_dimension
|
||||
from prompt_toolkit.layout.mouse_handlers import MouseHandler, MouseHandlers
|
||||
from prompt_toolkit.layout.screen import Char, Screen, WritePosition
|
||||
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
|
||||
from prompt_toolkit.utils import to_str
|
||||
|
||||
from euporie.box import Border
|
||||
from euporie.config import config
|
||||
|
||||
DrawingPosition = namedtuple(
|
||||
"DrawingPosition",
|
||||
[
|
||||
"index",
|
||||
"container",
|
||||
"top",
|
||||
"height",
|
||||
"parent_height",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class ScrollingContainer(Container):
|
||||
def __init__(
|
||||
self,
|
||||
children,
|
||||
max_content_width: AnyDimension = None,
|
||||
height: AnyDimension = None,
|
||||
z_index: Optional[int] = None,
|
||||
style: Union[str, Callable[[], str]] = "",
|
||||
show_border: FilterOrBool = True,
|
||||
):
|
||||
self.children = children
|
||||
if not isinstance(max_content_width, Dimension):
|
||||
max_content_width = Dimension(preferred=config.max_notebook_width)
|
||||
self.max_content_width = max_content_width
|
||||
self.height = height
|
||||
self.z_index = z_index
|
||||
self.style = style
|
||||
|
||||
self.kb = KeyBindings()
|
||||
self.load_key_bindings()
|
||||
|
||||
self._remaining_space_window = Window()
|
||||
|
||||
self.show_border = to_filter(show_border)
|
||||
|
||||
self.last_selected_index: int = 0
|
||||
|
||||
# Position of viewing window relative to selected child
|
||||
self.selected_child_position: int = 0
|
||||
self.child_cache = {}
|
||||
self.size_cache = {}
|
||||
self.to_draw: Sequence[DrawingPosition] = []
|
||||
|
||||
# Container methods
|
||||
|
||||
def reset(self) -> None:
|
||||
for c in self.get_children():
|
||||
c.reset()
|
||||
self.child_cache = {}
|
||||
self.size_cache = {}
|
||||
|
||||
def preferred_width(self, max_available_width: int):
|
||||
dimension = Dimension()
|
||||
# if self.max_content_width is not None:
|
||||
# dimension.max = 120
|
||||
# dimension.preferred = 120
|
||||
return dimension
|
||||
|
||||
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
|
||||
if self.height is not None:
|
||||
return to_dimension(self.height)
|
||||
# Do not report preferred_height height to children so they don't complain about
|
||||
# a lack of space
|
||||
# return to_dimension(max_available_height-2)
|
||||
return Dimension()
|
||||
|
||||
def write_to_screen(
|
||||
self,
|
||||
screen: "Screen",
|
||||
mouse_handlers: "MouseHandlers",
|
||||
write_position: "WritePosition",
|
||||
parent_style: str,
|
||||
erase_bg: bool,
|
||||
z_index: Optional[int],
|
||||
) -> None:
|
||||
"""
|
||||
Render the prompt to a `Screen` instance.
|
||||
:param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
|
||||
to which the output has to be written.
|
||||
"""
|
||||
|
||||
self.available_width = write_position.width
|
||||
self.available_height = write_position.height
|
||||
|
||||
style = parent_style + " " + to_str(self.style)
|
||||
z_index = z_index if self.z_index is None else self.z_index
|
||||
|
||||
self.content_width = min(
|
||||
self.max_content_width.preferred
|
||||
if self.max_content_width.preferred
|
||||
else self.available_width,
|
||||
write_position.width - self.show_scroll * 2,
|
||||
)
|
||||
self.content_height = self.available_height
|
||||
|
||||
self.to_draw = self.arrange_children(write_position)
|
||||
|
||||
ypos = write_position.ypos
|
||||
xpos = (
|
||||
write_position.xpos
|
||||
+ (write_position.width - self.show_scroll * 2 - self.content_width) // 2
|
||||
)
|
||||
|
||||
# Draw frame if it fits
|
||||
if (
|
||||
self.show_border()
|
||||
and self.content_width + 4 + self.show_scroll <= self.available_width
|
||||
):
|
||||
for y in range(ypos, ypos + self.content_height + 1):
|
||||
screen.data_buffer[y][xpos - 2] = Char(Border.VERTICAL)
|
||||
screen.data_buffer[y][xpos + 1 + self.content_width] = Char(
|
||||
Border.VERTICAL
|
||||
)
|
||||
|
||||
# Draw background if there is space
|
||||
if config.show_background:
|
||||
dot = Char(config.background_character, "class:background")
|
||||
for y in range(ypos, ypos + self.content_height + 1):
|
||||
for x in range(write_position.xpos, xpos - 2):
|
||||
if (x + y) % 2 == 0:
|
||||
screen.data_buffer[y][x] = dot
|
||||
for x in range(xpos + self.content_width + 2, write_position.width - 1):
|
||||
if (x + y) % 2 == 0:
|
||||
screen.data_buffer[y][x] = dot
|
||||
|
||||
# Draw child panes.
|
||||
for drawing in self.to_draw:
|
||||
|
||||
if drawing.top < 0 or drawing.top + drawing.height > self.content_height:
|
||||
# Create a virtual screen to draw partially obscured children
|
||||
temp_screen = Screen(default_char=Char(char=" ", style=parent_style))
|
||||
temp_screen.show_cursor = False
|
||||
# Create empty mouse handler array
|
||||
temp_mouse_handlers = MouseHandlers()
|
||||
# Draw child at (0,0) on temp screen
|
||||
temp_write_position = WritePosition(
|
||||
xpos=0, ypos=0, width=self.content_width, height=drawing.height
|
||||
)
|
||||
|
||||
drawing.container.write_to_screen(
|
||||
temp_screen,
|
||||
temp_mouse_handlers,
|
||||
temp_write_position,
|
||||
style,
|
||||
erase_bg,
|
||||
z_index,
|
||||
)
|
||||
temp_screen.draw_all_floats()
|
||||
|
||||
# Determin how many rows to copy
|
||||
if drawing.top < 0:
|
||||
copy_rows = drawing.top + drawing.height
|
||||
else: # drawing.top + drawing.height > self.content_height
|
||||
copy_rows = self.content_height - drawing.top
|
||||
|
||||
# Copy screen contents
|
||||
for i in range(0, copy_rows):
|
||||
|
||||
real_y = ypos + max(0, drawing.top) + i
|
||||
virt_y = 0 - min(0, drawing.top) + i
|
||||
|
||||
real_row = screen.data_buffer[real_y]
|
||||
virt_row = temp_screen.data_buffer[virt_y]
|
||||
|
||||
real_mouse_row = mouse_handlers.mouse_handlers[real_y]
|
||||
virt_mouse_row = temp_mouse_handlers.mouse_handlers[virt_y]
|
||||
|
||||
# real_escapes = screen.zero_width_escapes[real_y]
|
||||
# virt_escapes = temp_screen.zero_width_escapes[virt_y]
|
||||
|
||||
for x in range(self.content_width):
|
||||
real_row[x + xpos] = virt_row[x]
|
||||
real_mouse_row[x + xpos] = virt_mouse_row[x]
|
||||
# real_escapes[x + xpos] = virt_escapes[x]
|
||||
|
||||
# Copy cursors
|
||||
if temp_screen.show_cursor:
|
||||
screen.show_cursor = True
|
||||
for window, point in temp_screen.cursor_positions.items():
|
||||
# Check cursor is in the visibible zone on the temp screen
|
||||
if (
|
||||
0 <= point.x < self.content_width
|
||||
and 0 - min(0, drawing.top)
|
||||
<= point.y
|
||||
< 0 - min(0, drawing.top) + copy_rows
|
||||
):
|
||||
screen.cursor_positions[window] = Point(
|
||||
x=point.x + xpos,
|
||||
y=point.y + ypos + drawing.top,
|
||||
)
|
||||
|
||||
# If the cell is fully visible, simply write it to the screen
|
||||
else:
|
||||
drawing.container.write_to_screen(
|
||||
screen,
|
||||
mouse_handlers,
|
||||
WritePosition(
|
||||
xpos, ypos + drawing.top, self.content_width, drawing.height
|
||||
),
|
||||
style,
|
||||
erase_bg,
|
||||
z_index,
|
||||
)
|
||||
|
||||
# Fill empty space, and click to focus
|
||||
###
|
||||
|
||||
# Draw floats before wrapping mouse handlers
|
||||
screen.draw_all_floats()
|
||||
|
||||
# Draw scroll bar
|
||||
if self.show_scroll:
|
||||
|
||||
x = write_position.xpos + self.available_width - 1
|
||||
|
||||
def mouse_handler_scroll_up(mouse_event: MouseEvent):
|
||||
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
|
||||
self.scroll_up()
|
||||
|
||||
def mouse_handler_scroll_down(mouse_event: MouseEvent):
|
||||
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
|
||||
self.scroll_down()
|
||||
|
||||
screen.data_buffer[ypos + 0][x] = Char("▲", "class:scrollbar.arrow")
|
||||
mouse_handlers.mouse_handlers[ypos][x] = mouse_handler_scroll_up
|
||||
screen.data_buffer[ypos + self.available_height - 1][x] = Char(
|
||||
"▼", "class:scrollbar.arrow"
|
||||
)
|
||||
mouse_handlers.mouse_handlers[ypos + self.available_height - 1][
|
||||
x
|
||||
] = mouse_handler_scroll_down
|
||||
|
||||
def scrollbar_mouse_click(index):
|
||||
def mouse_handler(mouse_event: MouseEvent):
|
||||
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
|
||||
self.selected_index = index
|
||||
|
||||
return mouse_handler
|
||||
|
||||
scroll_tab_height = max(
|
||||
1, (self.available_height - 2) // len(self.children)
|
||||
)
|
||||
scroll_tab_top = (
|
||||
(self.available_height - 2 - scroll_tab_height)
|
||||
* self.to_draw[0].index
|
||||
// (len(self.children) - 1)
|
||||
if self.to_draw
|
||||
else 0
|
||||
)
|
||||
|
||||
for y in range(self.available_height - 2):
|
||||
if scroll_tab_top <= y <= scroll_tab_height + scroll_tab_top:
|
||||
style = "class:scrollbar.button"
|
||||
else:
|
||||
style = "class:scrollbar.background"
|
||||
# Set mouse click action
|
||||
child_index = int(
|
||||
y / (self.available_height - 2 - 1) * len(self.children)
|
||||
)
|
||||
mouse_handlers.mouse_handlers[ypos + y + 1][x] = scrollbar_mouse_click(
|
||||
child_index
|
||||
)
|
||||
screen.data_buffer[ypos + y + 1][x] = Char(style=style)
|
||||
|
||||
# Wrap all the mouse handlers to add mouse scrolling
|
||||
mouse_handler_wrappers: Dict[MouseHandler, MouseHandler] = {}
|
||||
|
||||
def wrap_mouse_handler(handler) -> None:
|
||||
if handler not in mouse_handler_wrappers:
|
||||
|
||||
def wrapped_mouse_handler(mouse_event: MouseEvent):
|
||||
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
|
||||
self.scroll_down()
|
||||
elif mouse_event.event_type == MouseEventType.SCROLL_UP:
|
||||
self.scroll_up()
|
||||
elif handler:
|
||||
handler(mouse_event)
|
||||
|
||||
mouse_handler_wrappers[handler] = wrapped_mouse_handler
|
||||
return mouse_handler_wrappers[handler]
|
||||
|
||||
for y in range(ypos, ypos + write_position.height):
|
||||
mouse_row = mouse_handlers.mouse_handlers[y]
|
||||
for x in range(
|
||||
write_position.xpos, write_position.xpos + write_position.width
|
||||
):
|
||||
mouse_row[x] = wrap_mouse_handler(mouse_row.get(x))
|
||||
|
||||
# If we are using kitty graphics, ensure all existing images are erased
|
||||
if get_app().has_kitty_graphics:
|
||||
screen.zero_width_escapes[ypos][xpos] = "\x1b_Ga=d\x1b\\"
|
||||
|
||||
@property
|
||||
def show_scroll(self):
|
||||
return len(self.children) > 1
|
||||
# return sum([drawing.height for drawing in self.to_draw]) > self.content_height
|
||||
|
||||
def get_children(self) -> List[Container]:
|
||||
return map(to_container, [x[1] for x in sorted(self.child_cache.items())])
|
||||
|
||||
def get_key_bindings(self):
|
||||
return self.kb
|
||||
|
||||
# End of container methods
|
||||
|
||||
def load_key_bindings(self):
|
||||
@self.kb.add("[")
|
||||
@self.kb.add("<scroll-up>")
|
||||
def su(event):
|
||||
self.scroll_up()
|
||||
|
||||
@self.kb.add("]")
|
||||
@self.kb.add("<scroll-down>")
|
||||
def sd(event):
|
||||
self.scroll_down()
|
||||
|
||||
@self.kb.add("c-up")
|
||||
@self.kb.add("home")
|
||||
def first_child(event=None):
|
||||
self.selected_index = 0
|
||||
|
||||
@self.kb.add("pageup")
|
||||
def prev_child5(event=None):
|
||||
self.selected_index -= 5
|
||||
|
||||
@self.kb.add("up")
|
||||
@self.kb.add("k")
|
||||
def prev_child(event=None):
|
||||
self.selected_index -= 1
|
||||
|
||||
@self.kb.add("down")
|
||||
@self.kb.add("j")
|
||||
def next_child(event=None):
|
||||
self.selected_index += 1
|
||||
|
||||
@self.kb.add("pagedown")
|
||||
def next_child5(event=None):
|
||||
self.selected_index += 5
|
||||
|
||||
@self.kb.add("c-down")
|
||||
@self.kb.add("end")
|
||||
def last_child(event=None):
|
||||
self.selected_index = len(self.children)
|
||||
|
||||
def get_child(self, index=None):
|
||||
if index is None:
|
||||
index = self.last_selected_index
|
||||
child = self.child_cache.get(index)
|
||||
if child is None and self.children:
|
||||
child = self.children[index]()
|
||||
self.child_cache[index] = child
|
||||
return child
|
||||
|
||||
def get_child_size(self, index, refresh=False):
|
||||
if not refresh and (size := self.size_cache.get(index)):
|
||||
return size
|
||||
else:
|
||||
child = self.get_child(index)
|
||||
container = to_container(child)
|
||||
size = container.preferred_height(
|
||||
self.content_width, self.content_height
|
||||
).preferred
|
||||
self.size_cache[index] = size
|
||||
return size
|
||||
|
||||
def arrange_children(self, write_position: "WritePosition") -> Optional[List[int]]:
|
||||
"""
|
||||
Return the heights for all rows.
|
||||
Or None when there is not enough space.
|
||||
"""
|
||||
|
||||
selected_index = self.selected_index
|
||||
|
||||
# Create a new version of the child cache
|
||||
cache = {}
|
||||
|
||||
# Get a handle on the current child
|
||||
# child = self.get_child(selected_index)
|
||||
# container = to_container(child)
|
||||
# cache[selected_index] = child
|
||||
# size = self.get_child_size(selected_index, refresh=True)
|
||||
|
||||
# Empy the list of container
|
||||
self.to_draw: Sequence["DrawingPosition"] = []
|
||||
|
||||
# Display selected child and those below it that are on screen
|
||||
if self.selected_child_position <= self.content_height:
|
||||
top = self.selected_child_position
|
||||
for i in range(self.selected_index, len(self.children)):
|
||||
size = self.get_child_size(i)
|
||||
if 0 <= top + size:
|
||||
cache[i] = self.get_child(i)
|
||||
container = to_container(cache[i])
|
||||
size = self.get_child_size(i, refresh=True)
|
||||
cache[i]._drawing_position = DrawingPosition(
|
||||
index=i,
|
||||
container=container,
|
||||
top=top,
|
||||
height=size,
|
||||
parent_height=self.content_height,
|
||||
)
|
||||
self.to_draw.append(cache[i]._drawing_position)
|
||||
top += size
|
||||
if top >= self.content_height:
|
||||
break
|
||||
|
||||
# Add children to fill space above the selected child if any are on screen
|
||||
if self.selected_child_position > 0:
|
||||
top = self.selected_child_position
|
||||
for i in range(selected_index - 1, -1, -1):
|
||||
size = self.get_child_size(i)
|
||||
if top >= 0:
|
||||
cache[i] = self.get_child(i)
|
||||
container = to_container(cache[i])
|
||||
size = self.get_child_size(i, refresh=True)
|
||||
cache[i]._drawing_position = DrawingPosition(
|
||||
index=i,
|
||||
container=container,
|
||||
top=top - size,
|
||||
height=size,
|
||||
parent_height=self.content_height,
|
||||
)
|
||||
self.to_draw.append(cache[i]._drawing_position)
|
||||
top -= size
|
||||
if top <= 0:
|
||||
break
|
||||
|
||||
# Add additional children to cache
|
||||
if cache:
|
||||
next_child_index = min(len(self.children) - 1, max(cache.keys()) + 1)
|
||||
if next_child_index not in cache:
|
||||
cache[next_child_index] = self.get_child(next_child_index)
|
||||
prev_child_index = max(0, min(cache.keys()) - 1)
|
||||
if prev_child_index not in cache:
|
||||
cache[prev_child_index] = self.get_child(prev_child_index)
|
||||
# Ensure the selected child is in the cache
|
||||
if self.selected_index not in cache:
|
||||
cache[self.selected_index] = self.get_child(self.selected_index)
|
||||
# Replace the cache
|
||||
self.child_cache = cache
|
||||
|
||||
# Sort drawings
|
||||
self.to_draw = sorted(self.to_draw, key=lambda x: x.index)
|
||||
|
||||
return self.to_draw
|
||||
|
||||
def select_child(self, new_index=None):
|
||||
|
||||
# Get the height and position of the newly selected child
|
||||
# Check if the newly selected child is currently in view
|
||||
drawing = {drawing.index: drawing for drawing in self.to_draw}.get(new_index)
|
||||
# If it is displayed on the screen, we already have that information
|
||||
if drawing:
|
||||
new_child_height = drawing.height
|
||||
new_top = drawing.top
|
||||
# If it is not displayed on the screen, we can load it from the child cache or
|
||||
# render it to calculate it's size. If it's not drawn, we pretend its position
|
||||
# is off the top of the screen or below the bottom, depending on if it is above
|
||||
# or below the currently selected child.
|
||||
else:
|
||||
new_child_height = self.get_child_size(
|
||||
new_index,
|
||||
)
|
||||
# If the children do not overflow the screen, move to the position of the
|
||||
# lowest child instead of the bottom of the screen
|
||||
new_top = (
|
||||
min(
|
||||
max([drawing.top + drawing.height for drawing in self.to_draw]),
|
||||
self.content_height,
|
||||
)
|
||||
if new_index > self.last_selected_index
|
||||
else 0
|
||||
)
|
||||
|
||||
# If the newly selected is off the top of the display, position it at the top
|
||||
if new_top < 0:
|
||||
self.selected_child_position = 0
|
||||
# If it is off the bottom of the screen, move it fully into view at the bottom
|
||||
elif new_top > self.content_height - new_child_height:
|
||||
self.selected_child_position = max(
|
||||
0, self.content_height - new_child_height
|
||||
)
|
||||
# Otherwise, it is fully on screen, so move the selection to it's position
|
||||
else:
|
||||
self.selected_child_position = new_top
|
||||
|
||||
def scroll_up(self, event=None) -> None:
|
||||
for drawing in self.to_draw:
|
||||
if drawing.index == 0:
|
||||
if drawing.top + 1 > 0:
|
||||
return
|
||||
break
|
||||
self.selected_child_position += 1
|
||||
|
||||
def scroll_down(self, event=None) -> None:
|
||||
for drawing in self.to_draw:
|
||||
if drawing.index == len(self.children) - 1:
|
||||
if drawing.top + drawing.height < self.content_height // 2:
|
||||
return
|
||||
break
|
||||
self.selected_child_position -= 1
|
||||
|
||||
@property
|
||||
def show_scrollbar(self):
|
||||
return sum([x.height for x in self.to_draw]) >= self.content_height
|
||||
|
||||
@property
|
||||
def selected_index(self):
|
||||
app = get_app()
|
||||
# Detect if focused child element has changed
|
||||
if app.layout.has_focus(self):
|
||||
# Find index of selected child
|
||||
for child in self.child_cache.values():
|
||||
if app.layout.has_focus(child):
|
||||
break
|
||||
# This will perform change the position when the new child is selected
|
||||
self.selected_index = child.index
|
||||
return self.last_selected_index
|
||||
|
||||
@selected_index.setter
|
||||
def selected_index(self, new_index):
|
||||
self._set_selected_index(new_index)
|
||||
|
||||
def _set_selected_index(self, new_index, force=False):
|
||||
# Only update the selected child if it was not selected before
|
||||
if force or new_index != self.last_selected_index:
|
||||
# Ensure selected index is a valid child
|
||||
new_index = min(max(new_index, 0), len(self.children) - 1)
|
||||
self.select_child(new_index)
|
||||
|
||||
# Focus new child if not already focused
|
||||
self.focus(new_index)
|
||||
|
||||
# Track which child was selected
|
||||
self.last_selected_index = new_index
|
||||
|
||||
def focus(self, index=None):
|
||||
if index is None:
|
||||
index = self.last_selected_index
|
||||
child = self.get_child(index)
|
||||
app = get_app()
|
||||
if not app.layout.has_focus(child):
|
||||
app.layout.focus(child)
|
||||
183
euporie/term.py
Normal file
183
euporie/term.py
Normal file
@@ -0,0 +1,183 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import array
|
||||
import re
|
||||
import sys
|
||||
from functools import lru_cache
|
||||
|
||||
CONTROL_RE = re.compile(
|
||||
r"""
|
||||
\x1b
|
||||
(?:
|
||||
(?P<csi> # Control Sequence Introducer
|
||||
\[
|
||||
(?P<csi_params>[0-9:;<=>?]*)
|
||||
(?P<csi_inter>[!\"#$%&'()*+,\-./]*)
|
||||
(?P<csi_final>[A-Za-z@[\]^_`a–z{|}~])
|
||||
)
|
||||
|
|
||||
(?P<osc> # Operating System Command
|
||||
\]
|
||||
(?P<osc_string>.*(?=\x1b\\|\x07))
|
||||
(?P<osc_term>\x1b\\|\x07) # Terminated by ST or BEL
|
||||
)
|
||||
|
|
||||
(?P<apc> # Application Program Command
|
||||
_
|
||||
(?P<apc_string>.*(?=\x1b\\))
|
||||
(?P<apc_term>\x1b\\) # Terminated by ST or BEL
|
||||
)
|
||||
|
|
||||
(?P<fe> # Other Fe escape sequences
|
||||
[NOP[\\\]X^_]
|
||||
)
|
||||
)
|
||||
""",
|
||||
re.VERBOSE,
|
||||
)
|
||||
|
||||
|
||||
class QueryCodes:
|
||||
device = "\x1b[>0c"
|
||||
pixel_dimensions = "\x1b[14t"
|
||||
background_color = "\x1b]11;?\x1b\\"
|
||||
sixel = "\033[?1;1;0S"
|
||||
# For some reason, konsole prints APC codes to the screen, so we clear the current
|
||||
# line and move the curor to the start after sending a kitty graphics query code,
|
||||
# which prevents breaking the display
|
||||
kitty = "\x1b_Gi=1,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\" + "\x1b[1K" + "\x1b[1G"
|
||||
|
||||
|
||||
class QueryResponsePatterns:
|
||||
device = re.compile(r"\x1b\[\>(\d;?)+c")
|
||||
background_color = re.compile(
|
||||
"11;rgb:(?P<r>[0-9A-Fa-f]{2,4})/(?P<g>[0-9A-Fa-f]{2,4})/(?P<b>[0-9A-Fa-f]{2,4})"
|
||||
)
|
||||
pixel_dimensions = re.compile(r"4;(?P<y>\d+);(?P<x>\d+)")
|
||||
sixel = re.compile(r"\d+")
|
||||
kitty = "\x1b[_Gi=1;OK\x1b[\\"
|
||||
|
||||
|
||||
class TermAppMixin:
|
||||
@property
|
||||
@lru_cache
|
||||
def _have_termios_tty_fcntl(self):
|
||||
try:
|
||||
import fcntl # noqa F401
|
||||
import termios # noqa F401
|
||||
import tty # noqa F401
|
||||
except ModuleNotFoundError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def _query_term(self, query_code):
|
||||
"""
|
||||
We use a Secondary Device Attribute request as our deliminator to locate the
|
||||
query response string
|
||||
"""
|
||||
if self._have_termios_tty_fcntl:
|
||||
import termios
|
||||
import tty
|
||||
|
||||
stdin = sys.stdin.fileno()
|
||||
tattr = termios.tcgetattr(stdin)
|
||||
|
||||
output = ""
|
||||
|
||||
try:
|
||||
tty.setcbreak(stdin, termios.TCSANOW)
|
||||
self.output.write_raw(QueryCodes.device)
|
||||
self.output.flush()
|
||||
|
||||
output_started = False
|
||||
query_sent = False
|
||||
|
||||
while True:
|
||||
output += sys.stdin.read(1)
|
||||
# Send query after first character of first deliminator recieved
|
||||
if not query_sent:
|
||||
self.output.write_raw(query_code)
|
||||
self.output.flush()
|
||||
query_sent = True
|
||||
if re.search(QueryResponsePatterns.device, output):
|
||||
if not output_started:
|
||||
output_started = True
|
||||
# Discard the first deliminator
|
||||
output = ""
|
||||
# Send the second deliminator
|
||||
self.output.write_raw(QueryCodes.device)
|
||||
self.output.flush()
|
||||
continue
|
||||
break
|
||||
finally:
|
||||
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
|
||||
# Remove deliminator
|
||||
output = re.sub(QueryResponsePatterns.device, "", output, 1)
|
||||
# Parse result
|
||||
if match := CONTROL_RE.search(output):
|
||||
return match.groupdict()
|
||||
|
||||
def tiocgwnsz(self):
|
||||
output = array.array("H", [0, 0, 0, 0])
|
||||
if self._have_termios_tty_fcntl:
|
||||
import fcntl
|
||||
import termios
|
||||
|
||||
fcntl.ioctl(1, termios.TIOCGWINSZ, output)
|
||||
rows, cols, xpixels, ypixels = output
|
||||
return rows, cols, xpixels, ypixels
|
||||
|
||||
@property
|
||||
def bg_color(self):
|
||||
if result := self._query_term(QueryCodes.background_color):
|
||||
if oscs := result.get("osc_string"):
|
||||
if match := QueryResponsePatterns.background_color.match(oscs):
|
||||
if colors := match.groupdict():
|
||||
if len(colors) >= 3:
|
||||
r, g, b = colors.get("r"), colors.get("g"), colors.get("b")
|
||||
return f"#{r[:2]}{g[:2]}{b[:2]}"
|
||||
|
||||
@property
|
||||
def term_size_px(self):
|
||||
*_, px, py = self.tiocgwnsz()
|
||||
# If unsuccessful, try requesting info with escape code method
|
||||
if px == 0:
|
||||
if result := self._query_term(QueryCodes.pixel_dimensions):
|
||||
params = result.get("csi_params", "")
|
||||
if match := QueryResponsePatterns.pixel_dimensions.match(params):
|
||||
if values := match.groupdict():
|
||||
px, py = int(values.get("x")), int(values.get("y"))
|
||||
return px, py
|
||||
|
||||
@property
|
||||
def char_size_px(self):
|
||||
px, py = self.term_size_px
|
||||
rows, cols = self.output.get_size()
|
||||
# If we can't get the pixel size, just guess wildly
|
||||
if px == 0:
|
||||
return 10, 22
|
||||
return px // cols, py // rows
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def has_sixel_graphics(self):
|
||||
if result := self._query_term(QueryCodes.sixel):
|
||||
params = result.get("csi_params", "")
|
||||
params = QueryResponsePatterns.sixel.findall(params)
|
||||
params = [int(x) for x in params]
|
||||
if len(params) <= 3:
|
||||
Pi, Ps, Pv = params[:3]
|
||||
if Ps == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def has_kitty_graphics(self):
|
||||
if result := self._query_term(QueryCodes.kitty):
|
||||
apc_string = result.get("apc_string", "")
|
||||
if apc_string.startswith("G"):
|
||||
if len(response := apc_string.lstrip("G").split(";")) >= 2:
|
||||
if response[1] == "OK":
|
||||
return True
|
||||
return False
|
||||
1493
poetry.lock
generated
Normal file
1493
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
44
pyproject.toml
Normal file
44
pyproject.toml
Normal file
@@ -0,0 +1,44 @@
|
||||
[tool.poetry]
|
||||
name = "euporie"
|
||||
version = "0.1.1"
|
||||
description = "Euporie is a text-based user interface for running and editing Jupyter notebooks"
|
||||
authors = ["Josiah Outram Halstead <josiah@halstead.email>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
readme = "README.md"
|
||||
homepage = "https://github.com/joouha/euporie"
|
||||
keywords = ["jupyter", "ipython", "markdown", "terminal", "notebook"]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Environment :: Console",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Topic :: Scientific/Engineering",
|
||||
]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.8"
|
||||
rich = "^10.1.0"
|
||||
nbformat = "^5.1.3"
|
||||
img2unicode = {version = "^0.1a7", optional = true}
|
||||
prompt-toolkit = "^3.0.18"
|
||||
jupyter-client = "^6.2.0"
|
||||
timg = {version = "^1.1.5", optional = true}
|
||||
mtable = {version = "^0.1.10", optional = true}
|
||||
html5lib = {version = "^1.1", optional = true}
|
||||
Pillow = "^8.2.0"
|
||||
|
||||
[tool.poetry.extras]
|
||||
tables = ["mtable", "html5lib"]
|
||||
images = ["timg"]
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
pytest = "^5.2"
|
||||
isort = "^5.8.0"
|
||||
flake8 = "^3.9.1"
|
||||
black = "^21.5b0"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
euporie = 'euporie.app:App.launch'
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
0
tests/__init__.py
Normal file
0
tests/__init__.py
Normal file
6
tests/test_redspot.py
Normal file
6
tests/test_redspot.py
Normal file
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from notebook_tui import __version__
|
||||
|
||||
|
||||
def test_version():
|
||||
assert __version__ == "0.1.0"
|
||||
Reference in New Issue
Block a user