pax_global_header 0000666 0000000 0000000 00000000064 14753047770 0014530 g ustar 00root root 0000000 0000000 52 comment=e47779c06c0ad2e588da1ad3bdc487f7cf5665b8
bdflib-v2.1.0/ 0000775 0000000 0000000 00000000000 14753047770 0013140 5 ustar 00root root 0000000 0000000 bdflib-v2.1.0/.bumpversion.cfg 0000664 0000000 0000000 00000000261 14753047770 0016247 0 ustar 00root root 0000000 0000000 [bumpversion]
current_version = 2.1.0
[bumpversion:file:setup.py]
[bumpversion:file:docs/conf.py]
[bumpversion:file:docs/tutorial.rst]
[bumpversion:file:bdflib/__init__.py]
bdflib-v2.1.0/.gitignore 0000664 0000000 0000000 00000000136 14753047770 0015130 0 ustar 00root root 0000000 0000000 .*.swp
*.pyc
*.pyo
*.bak
build/
dist/
MANIFEST
.tox/
*.egg-info/
docs/tutorial2.bdf
.coverage
bdflib-v2.1.0/.gitlab-ci.yml 0000664 0000000 0000000 00000000150 14753047770 0015570 0 ustar 00root root 0000000 0000000 image: debian:stable
tests:
script:
- apt-get update && apt-get -y install python3 tox
- tox
bdflib-v2.1.0/.readthedocs.yaml 0000664 0000000 0000000 00000000731 14753047770 0016370 0 ustar 00root root 0000000 0000000 # .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.11"
# Install our package so Sphinx can find the docstrings.
python:
install:
- method: pip
path: .
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
bdflib-v2.1.0/COPYING 0000664 0000000 0000000 00000104513 14753047770 0014177 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
bdflib-v2.1.0/README.md 0000664 0000000 0000000 00000001051 14753047770 0014414 0 ustar 00root root 0000000 0000000 bdflib
======
bdflib is a Python library for working with [BDF font files][bdf].
The library allows for manipulating fonts directly and comes with
command-line utilities for performing various operations on font files.
[bdf]: http://en.wikipedia.org/wiki/BDF_%28Glyph_Bitmap_Distribution_Format%29
Documentation
-------------
Documentation is available for [the current stable release][stable]
and for [the latest development version][latest].
[stable]: https://bdflib.readthedocs.io/en/stable/
[latest]: https://bdflib.readthedocs.io/en/latest/
bdflib-v2.1.0/TODO 0000664 0000000 0000000 00000001147 14753047770 0013633 0 ustar 00root root 0000000 0000000 - Add a standard set of extra compositions that are useful for font-building,
such as characters WITH STROKE.
- Support more combining classes.
- Support for charcell/monospaced fonts. This would involve ignoring
decompositions with spacing characters (Dz -> "D", "z"), or maybe just
ignoring any decompositions that went outside the defined character cell.
- Font manipulation functions should return a new font with the appropriate
modifications rather than changing the original font in-place, so that
"pipelines" of font modifications can be built.
- Add a test for model.Font.__delitem__()
bdflib-v2.1.0/bdflib/ 0000775 0000000 0000000 00000000000 14753047770 0014362 5 ustar 00root root 0000000 0000000 bdflib-v2.1.0/bdflib/__init__.py 0000664 0000000 0000000 00000001156 14753047770 0016476 0 ustar 00root root 0000000 0000000 """
Read, manipulate and write bitmap fonts in the Bitmap Distribution Format.
To get started, use :func:`bdflib.reader.read_bdf` to load a BDF file and
create a :class:`bdflib.model.Font` object, or just create one yourself from
scratch.
Modify the font by tinkering with it directly, or by using the helpers in
:mod:`bdflib.effects` and :mod:`bdflib.glyph_combining`.
If you're making a font intended for use with the X11 windowing system,
check out the helpers in :mod:`bdflib.xlfd`.
When you're done, you can use :func:`bdflib.writer.write_bdf` to write your
font back out to a BDF file.
"""
__version__ = "2.1.0"
bdflib-v2.1.0/bdflib/effects.py 0000664 0000000 0000000 00000011152 14753047770 0016353 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
"""
Automatically generate visual variants of a font.
"""
from bdflib import model
def embolden(font: model.Font, maintain_spacing: bool = True) -> model.Font:
"""
Create a bold version of a font by widening each glyph.
:param font: The font to embolden.
:param maintain_spacing: If true, each glyph's advance width
will be incremented, because a wider glyph needs more room.
:returns: A copy of ``font``, with each glyph emboldened.
To embolden a glyph, it is drawn over itself one pixel to the right,
making each vertical stroke one pixel wider.
"""
res = font.copy()
for cp in res.codepoints():
g = res[cp]
g.merge_glyph(g, 1, 0)
if maintain_spacing:
g.advance += 1
return res
def expand(font: model.Font, x_factor: int, y_factor: int) -> model.Font:
"""
Create a font with greater resolution by duplicating glyph rows and columns.
:param font: The font to expand.
:param x_factor: The number of times to increase
the font's horizontal resolution.
Must be > 0.
:param y_factor: The number of times to increase
the font's vertical resolution.
Must be > 0.
:returns: A copy of ``font``, with the resolution adjusted.
If ``font`` has a horizontal resolution of 72dpi,
and ``x_factor`` is 2,
the resulting font will have the same vertical metrics,
but the horizontal resolution will be doubled to 144dpi.
The new columns will be created by duplicating existing columns
("Nearest Neighbour"),
so each column of a source glyph
will appear twice in the resulting glyph.
Vertical increases work the same way,
except duplicating rows instead of columns.
Because the resolution is increased,
rather than making the glyph bigger,
the point size stays the same.
"""
if x_factor < 1:
raise ValueError("Scaling factor must be greater than 0")
if y_factor < 1:
raise ValueError("Scaling factor must be greater than 0")
res = font.copy()
# Adjust font metadata
res.xdpi *= x_factor
res.ydpi *= y_factor
# Scale glyphs horizontally and vertically
for g in res.glyphs:
# Scale the glyph bitmap
new_data = []
for old_row in g.data:
# Calculate the new, horizontally scaled row
new_row = 0
for x in range(g.bbW):
pixel = (old_row >> x) & 1
for x_offset in range(x_factor):
new_row |= pixel << (x * x_factor + x_offset)
new_data.append(new_row)
# Duplicate the new row to create vertical scaling
for _ in range(1, y_factor):
new_data.append(new_row)
g.data = new_data
# Adjust glyph metadata
g.bbX *= x_factor
g.bbY *= y_factor
g.bbW *= x_factor
g.bbH *= y_factor
g.advance *= x_factor
return res
def merge(base: model.Font, custom: model.Font) -> model.Font:
"""
Create a new font by choosing glyphs from two other fonts.
:param base: The lower-priority font.
:param custom: The higher-priority font.
:returns: A font where each glyph comes from ``base`` or ``custom``.
For any given codepoint, the resulting font will use the corresponding
glyph from ``custom`` if there is one, falling back to the glyph from
``base``. The new font's properties and other metadata are all copied
from ``custom``.
"""
res = custom.copy()
for cp in base.codepoints():
if cp not in res:
old_glyph = base[cp]
res.new_glyph_from_data(
old_glyph.name,
old_glyph.data,
old_glyph.bbX,
old_glyph.bbY,
old_glyph.bbW,
old_glyph.bbH,
old_glyph.advance,
old_glyph.codepoint,
)
return res
bdflib-v2.1.0/bdflib/glyph_combining.py 0000664 0000000 0000000 00000027777 14753047770 0020130 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
"""
Tools for building glyphs by combining other glyphs.
Unicode has a lot of "pre-combined" code-points that are the combination of
a normal code-point and a combining code-point, like how U+014D LATIN SMALL
LETTER O WITH MACRON is the combination of U+006F LATIN SMALL LETTER O with
U+0304 COMBINING MACRON. Given glyphs for their individual components,
glyphs for pre-combined code-points can be automatically generated.
An example of using this module to generate pre-combined glyphs:
.. code-block:: python
decompositions = build_unicode_decompositions()
filler = FontFiller(myfont, decompositions)
filler.add_decomposable_glyphs_to_font()
"""
import sys
from typing import Dict, List, Tuple, Counter
import unicodedata
import collections
from bdflib import model
# There are many ways in which one character might be said to be 'made up of'
# other characters. We're only interested in the ones that involve graphically
# drawing one character overlaid on or beside another.
USEFUL_COMPOSITION_TYPES = [
"",
"",
]
# Combining class names. Summarised from
# https://www.unicode.org/reports/tr44/#Canonical_Combining_Class_Values
CC_SPACING = 0 # Spacing, split, enclosing, reordrant, etc.
CC_OVERLAY = 1 # Overlays and interior
CC_NUKTAS = 7 # Nuktas
CC_VOICING_MARKS = 8 # Hiragana/Katakana voicing marks
CC_VIRAMAS = 9 # Viramas
CC_BL_ATTACHED = 200 # Bottom-left attached
CC_B_ATTACHED = 202 # Bottom attached
CC_BR_ATTACHED = 204 # Bottom-right attached
CC_L_ATTACHED = 208 # Left attached
CC_R_ATTACHED = 210 # Right attached
CC_AL_ATTACHED = 212 # Above-left attached
CC_A_ATTACHED = 214 # Above attached
CC_AR_ATTACHED = 216 # Above-right attached
CC_BL = 218 # Below-left
CC_B = 220 # Below
CC_BR = 222 # Below-right
CC_L = 224 # Left
CC_R = 226 # Right
CC_AL = 228 # Above-left
CC_A = 230 # Above
CC_AR = 232 # Above-right
CC_B_DOUBLE = 233 # Double below
CC_A_DOUBLE = 234 # Double above
CC_IOTA_SUBSCRIPT = 240 # Below (iota subscript)
# Combining classes that mean "draw the combining character above the base
# character". These cause characters with the "Soft_Dotted" property to be
# treated specially.
ABOVE_COMBINING_CLASSES = [CC_A, CC_A_ATTACHED]
# Characters with the "Soft_Dotted" property are treated specially a combining
# character is drawn above them; the dot is not drawn. Since Python's
# unicodedata module won't tell us what properties a character has, we'll have
# to hard-code the list ourselves.
SOFT_DOTTED_CHARACTERS = {
"i": "\N{LATIN SMALL LETTER DOTLESS I}",
"j": "\N{LATIN SMALL LETTER DOTLESS J}",
}
Decompositions = Dict[str, List[Tuple[str, int]]]
def build_unicode_decompositions() -> Decompositions:
r"""
Returns a dictionary mapping unicode characters to their components.
:returns: a mapping from pre-combined characters to their components.
Each key in the resulting dict is a single-character Unicode string,
and each value is a list of single-character Unicode strings and their
combining classes, the components of the key. For example, one of the
items in the result should be::
u"\N{LATIN SMALL LETTER O WITH MACRON}": [
(u"o", 0),
(u"\N{COMBINING MACRON}", 230),
]
(where 0 indicates a regular base character, and 230 means the glyph
is drawn above the base glyph. See
https://www.unicode.org/reports/tr44/#Canonical_Combining_Class_Values
for details.)
This function obtains information about combining characters from
Python's :mod:`unicodedata` standard library module. It also properly
handles "soft-dotted" characters "i" and "j" where pre-combined glyphs
should be built from the dotless versions of those characters.
"""
res = {}
for codepoint in range(0, sys.maxunicode + 1):
curr_char = chr(codepoint)
hex_components = unicodedata.decomposition(curr_char).split()
if hex_components == []:
# No decomposition at all, who cares?
continue
# If this combining-char sequence has a special type...
if hex_components[0].startswith("<"):
composition_type = hex_components[0]
# ...is it a type we like?
if composition_type in USEFUL_COMPOSITION_TYPES:
# Strip the type, use the rest of the sequence
hex_components = hex_components[1:]
else:
# This sequence is no good to us, let's move on.
continue
# Convert ['aaaa', 'bbbb'] to [u'\uaaaa', u'\ubbbb'].
components = [chr(int(cp, 16)) for cp in hex_components]
# Handle soft-dotted characters.
if components[0] in SOFT_DOTTED_CHARACTERS and len(components) > 1:
above_components = [
c
for c in components[1:]
if unicodedata.combining(c) in ABOVE_COMBINING_CLASSES
]
# If there are any above components...
if len(above_components) > 0:
# ...replace the base character with its undotted equivalent.
components[0] = SOFT_DOTTED_CHARACTERS[components[0]]
# Look up the combining classes, too
res[curr_char] = [
(char, unicodedata.combining(char)) for char in components
]
return res
def _merge_glyph_beside(
_: model.Font, base: model.Glyph, other: model.Glyph
) -> None:
"""
Draw other_glyph beside the current glyph.
"""
base.merge_glyph(other, base.advance, 0)
base.advance += other.advance
def _merge_glyph_above(
font: model.Font, base: model.Glyph, other: model.Glyph
) -> None:
"""
Draw other_glyph centred above the current glyph.
"""
y_offset = 0
x_offset = 0
cap_height = font.get(b"CAP_HEIGHT")
if isinstance(cap_height, int) and base.bbH > 0:
# If the font has a CAP_HEIGHT,
# we assume combining characters are drawn to appear above it,
# so we can adjust the height to match this specific glyph.
y_offset = base.get_ascent() - cap_height
# Otherwise, we assume the combining character must be drawn
# at the original position onto every character.
if base.bbW > 0:
x_offset = int(float(base.advance) / 2 - float(other.advance) / 2)
base.merge_glyph(other, x_offset, y_offset)
def _merge_glyph_below(
_: model.Font, base: model.Glyph, other: model.Glyph
) -> None:
"""
Draw other_glyph centred below the current glyph.
"""
y_offset = -base.get_descent()
x_offset = 0
if base.bbW > 0:
x_offset = int(float(base.advance) / 2 - float(other.advance) / 2)
base.merge_glyph(other, x_offset, y_offset)
# Combining glyphs can be drawn in different places on the base glyph; the
# combining class determines exactly where.
SUPPORTED_COMBINING_CLASSES = {
CC_SPACING: _merge_glyph_beside,
CC_A: _merge_glyph_above,
CC_B: _merge_glyph_below,
CC_B_ATTACHED: _merge_glyph_below,
}
class FontFiller(object):
"""
Build pre-combined glyphs from available component glyphs.
:param Font font: Any pre-combined glyphs will be added to this font.
:param decompositions: A dict mapping pre-combined characters to their
components, as returned by :func:`build_unicode_decompositions`.
Call :meth:`add_decomposable_glyphs_to_font()` on an instance of this
class to add as many pre-combined glyphs as possible.
"""
#: The font passed to the constructor
font: model.Font
#: The decompositions passed to the constructor
decompositions: Decompositions
#: After calling :meth:`add_decomposable_glyphs_to_font()`,
#: this attribute will record characters
#: that could be used in combining sequences,
#: but were missing from the input font.
#: Adding the character with the highest count to the font
#: will give you the biggest increase in Unicode coverage.
missing_chars: Counter[str]
#: After calling :meth:`add_decomposable_glyphs_to_font()`,
#: this attribute will record Unicode combining classes
#: included in the `decompositions` paramater
#: that `bdflib` does not yet support.
#: If `bdflib` were extended to support these Unicode combining classes,
#: we might be able to use them to create new glyphs.
unknown_classes: Counter[int]
def __init__(self, font: model.Font, decompositions: Decompositions):
self.font = font
self.decompositions = decompositions
self.missing_chars = collections.Counter()
self.unknown_classes = collections.Counter()
def add_glyph_to_font(self, char: str) -> bool:
"""
Add the glyph representing char to the given font, if it can be built.
:param char: A single-codepoint Unicode string,
whose glyph should be generated (if possible)
and added to the font passed to the class constructor.
:returns: ``True`` if the font now contains a glyph for that
character, ``False`` otherwise.
This method may return ``True`` if a glyph was generated, or if the
font already contained the required glyph.
This method may return ``False`` if:
* the decompositions passed to the class constructor do not include
any components for ``char``
* the font passed to the class constructor is missing glyphs for
one or more of ``char``'s components, and they could not be generated
* one of ``char``'s components uses
a combining class this code doesn't understand
"""
if ord(char) in self.font:
# It's already there!
return True
if char not in self.decompositions:
# We don't know how to build it.
return False
# Make sure we have all the components
# before we try to produce the combined glyph.
components = self.decompositions[char]
for component_char, combining_class in components:
if combining_class not in SUPPORTED_COMBINING_CLASSES:
# We don't know how to combine this with other characters.
self.unknown_classes[combining_class] += 1
return False
if not self.add_glyph_to_font(component_char):
# We don't know how to build one of the required components.
self.missing_chars[component_char] += 1
return False
# Now we have all the components, let's put them together!
glyph = self.font.new_glyph_from_data(
b"char%d" % ord(char), codepoint=ord(char)
)
# Draw on the base char.
base_char = components[0][0]
base_glyph = self.font[ord(base_char)]
glyph.merge_glyph(base_glyph, 0, 0)
glyph.advance = base_glyph.advance
for component_char, combining_class in components[1:]:
other_glyph = self.font[ord(component_char)]
merger = SUPPORTED_COMBINING_CLASSES[combining_class]
merger(self.font, glyph, other_glyph)
return True
def add_decomposable_glyphs_to_font(self) -> None:
"""
Adds all the glyphs that can be built to the given font.
This calls :meth:`add_glyph_to_font` for each key in the decompositions
passed to the class constructor.
"""
for char in self.decompositions:
self.add_glyph_to_font(char)
bdflib-v2.1.0/bdflib/model.py 0000664 0000000 0000000 00000043213 14753047770 0016037 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
"""
Classes that represent a bitmap font, with its glyphs and metadata.
.. testsetup::
from bdflib.model import *
"""
from typing import Union, Optional, Dict, List, Iterable, Tuple, overload
PropertyValue = Union[bytes, int]
Properties = Dict[bytes, PropertyValue]
class GlyphExists(Exception):
"""
Raised when creating a new glyph for a codepoint that already has one.
"""
class Glyph(object):
"""
Represents a font glyph and associated properties.
:param name: The name of this glyph, ASCII encoded.
:param data: If provided,
gives the initial bitmap for the glyph,
see the :attr:`data` attribute below.
:param bbX: The left-most edge of the glyph's bounding box, in
pixels.
:param bbY: The bottom-most edge of the glyph's bounding box, in pixels.
:param bbW: The glyph's bounding-box extends this many pixels right of
``bbX`` (must be >= 0).
If `data` is provided,
each integer should be at most this many bits wide.
:param bbH: The glyph's bounding-box extends this many pixels upward
from ``bbY`` (must be >= 0).
If `data` is provided,
it should yield this many rows.
:param advance: After drawing this glyph, the next glyph will be
drawn this many pixels to the right.
:param codepoint: The Unicode codepoint that this glyph represents.
"""
#: How far to the right the next glyph should be drawn, in pixels.
advance: int
#: Each item of the ``.data`` property
#: is a :class:`int` `bbW` bits wide,
#: representing the pixels of a single row.
#: the first item in ``.data`` is
#: the lowest row in the glyph,
#: so that list indices increase in the same
#: direction as pixel coordinates.
#:
#: >>> my_glyph = Glyph(
#: ... name=b"capital A",
#: ... data=[
#: ... 0b10001,
#: ... 0b11111,
#: ... 0b10001,
#: ... 0b01110,
#: ... ],
#: ... bbW=5,
#: ... bbH=4,
#: ... )
#: >>> for row in reversed(my_glyph.data):
#: ... print("{:05b}".format(row))
#: 01110
#: 10001
#: 11111
#: 10001
#:
#: If you want to get the actual coordinates
#: of the glyph's drawn pixels,
#: look at the :meth:`iter_pixels` method.
data: List[int]
def __init__(
self,
name: bytes,
data: Optional[List[int]] = None,
bbX: int = 0,
bbY: int = 0,
bbW: int = 0,
bbH: int = 0,
advance: int = 0,
codepoint: Optional[int] = None,
):
self.name = name
self.bbX = bbX
self.bbY = bbY
self.bbW = bbW
self.bbH = bbH
if data is None:
self.data = []
else:
self.data = data
self.advance = advance
if codepoint is None:
self.codepoint = -1
else:
self.codepoint = codepoint
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Glyph)
and self.name == other.name
and self.bbX == other.bbX
and self.bbY == other.bbY
and self.bbW == other.bbW
and self.bbH == other.bbH
and self.data == other.data
and self.advance == other.advance
)
def __str__(self) -> str:
def padding_char(x: int, y: int) -> str:
if x == 0 and y == 0:
return "+"
elif x == 0:
return "|"
elif y == 0:
return "-"
else:
return "."
# What are the extents of this bitmap, given that we always want to
# include the origin?
bitmap_min_X = min(0, self.bbX)
bitmap_max_X = max(0, self.bbX + self.bbW - 1)
bitmap_min_Y = min(0, self.bbY)
bitmap_max_Y = max(0, self.bbY + self.bbH - 1)
res = []
for y in range(bitmap_max_Y, bitmap_min_Y - 1, -1):
res_row = []
# Find the data row associated with this output row.
if self.bbY <= y < self.bbY + self.bbH:
data_row = self.data[y - self.bbY]
else:
data_row = 0
for x in range(bitmap_min_X, bitmap_max_X + 1):
# Figure out which bit controls (x,y)
bit_number = self.bbW - (x - self.bbX) - 1
# If we're in a cell covered by the bitmap and this particular
# bit is set...
if self.bbX <= x < self.bbX + self.bbW and (
data_row >> bit_number & 1
):
res_row.append("#")
else:
res_row.append(padding_char(x, y))
res.append("".join(res_row))
return "\n".join(res)
def get_bounding_box(self) -> Tuple[int, int, int, int]:
"""
Returns the position and dimensions of the glyph's bounding box.
:returns: The left, bottom, width and height of the bounding box, as
passed to the constructor.
"""
return (self.bbX, self.bbY, self.bbW, self.bbH)
def merge_glyph(self, other: "Glyph", atX: int, atY: int) -> None:
"""
Draw another glyph onto this one at the given coordinates.
:param other: The other glyph to draw onto this one.
:param atX: The other glyph's origin will be placed at this X
offset in this glyph.
:param atY: The other glyph's origin will be placed at this Y
offset in this glyph.
This glyph's bounding box will be stretch to include the area of
the added glyph, but the :attr:`advance` will not be modified.
"""
# Calculate the new metrics
new_bbX = min(self.bbX, atX + other.bbX)
new_bbY = min(self.bbY, atY + other.bbY)
new_bbW = (
max(self.bbX + self.bbW, atX + other.bbX + other.bbW) - new_bbX
)
new_bbH = (
max(self.bbY + self.bbH, atY + other.bbY + other.bbH) - new_bbY
)
# Calculate the new data
new_data = []
for y in range(new_bbY, new_bbY + new_bbH):
# If the old glyph has a row here...
if self.bbY <= y < self.bbY + self.bbH:
old_row = self.data[y - self.bbY]
# If the right-hand edge of the bounding box has moved right,
# we'll need to left shift the old-data to get more empty space
# to draw the new glyph into.
right_edge_delta = (new_bbX + new_bbW) - (self.bbX + self.bbW)
if right_edge_delta > 0:
old_row <<= right_edge_delta
else:
old_row = 0
# If the new glyph has a row here...
if atY + other.bbY <= y < atY + other.bbY + other.bbH:
new_row = other.data[y - other.bbY - atY]
# If the new right-hand-edge ofthe bounding box
if atX + other.bbX + other.bbW < new_bbX + new_bbW:
new_row <<= (new_bbX + new_bbW) - (
atX + other.bbX + other.bbW
)
else:
new_row = 0
new_data.append(old_row | new_row)
# Update our properties with calculated values
self.bbX = new_bbX
self.bbY = new_bbY
self.bbW = new_bbW
self.bbH = new_bbH
self.data = new_data
def get_ascent(self) -> int:
"""
Returns the distance from the Y axis to the highest point of the glyph.
This is zero if no part of the glyph is above the Y axis.
:returns: The ascent of this glyph.
"""
res = self.bbY + self.bbH
# Each empty row at the top of the bitmap should not be counted as part
# of the ascent.
for row in self.data[::-1]:
if row != 0:
break
else:
res -= 1
return res
def get_descent(self) -> int:
"""
Returns the distance from the Y axis to the lowest point of the glyph.
This is zero if no part of the glyph is below the Y axis.
:returns: The descent of this glyph.
"""
res = -1 * self.bbY
# Each empty row at the bottom of the bitmap should not be counted as
# part of the descent.
for row in self.data:
if row != 0:
break
else:
res -= 1
return res
def iter_pixels(self) -> Iterable[Iterable[bool]]:
"""
Yields the state of pixels within the bounding box.
This method returns an iterable of ``bbH`` rows,
from the top of the glyph (large X values)
to the bottom (small X values).
Each row is an iterable of ``bbW`` booleans,
from left to right.
Each boolean is ``True`` if that pixel should be drawn,
and otherwise ``False``.
Alternatively,
you can obtain the glyph data in BDF format with :meth:`get_data()`,
or access the raw bitmap via the :attr:`data` property.
:returns: the state of each pixel
"""
return (
(bool(row & (1 << self.bbW - x - 1)) for x in range(self.bbW))
for row in (self.data[self.bbH - y - 1] for y in range(self.bbH))
)
class Font(object):
"""
Represents the entire font and font-global properties.
:param bytes name: The human-readable name of this font, ASCII encoded.
:param int ptSize: The nominal size of this font in PostScript points (1/72
of an inch).
:param int xdpi: The horizontal resolution of this font in dots-per-inch.
:param int ydpi: The vertical resolution of this font in dots-per-inch.
Instances of this class can be used like :class:`dict` instances.
:class:`bytes` keys refer to the font's properties and are associated with
:class:`bytes` instances, while :class:`int` keys refer to the code-points
the font supports, and are associated with :class:`Glyph` instances.
>>> myfont = Font(
... b"My Font",
... ptSize=12,
... xdpi=96,
... ydpi=96,
... )
>>> myfont.ptSize
12
>>> a_glyph = myfont.new_glyph_from_data(
... b"capital A",
... codepoint=65,
... )
>>> a_glyph == myfont[65]
True
.. note::
Some properties (the name, point-size and resolutions) are required,
and although they can be examined via the ``dict`` interface,
they cannot be removed with the ``del`` statement.
"""
#: All the glyphs in this font,
#: even the ones with no associated codepoint.
glyphs: List[Glyph]
#: The value of the FONT field in the BDF file
name: bytes = b""
#: The font's nominal size in PostScript points (1/72 of an inch),
#: the first value in the SIZE field in the BDF file
ptSize: int
#: The font's horizontal resolution in dots-per-inch,
#: the second value in the SIZE field in the BDF file
xdpi: int
#: The font's vertical resolution in dots-per-inch,
#: the third value in the SIZE field in the BDF file
ydpi: int
def __init__(self, name: bytes, ptSize: int, xdpi: int, ydpi: int) -> None:
"""
Initialise this font object.
"""
self.properties: Properties = {}
self.name = name
self.ptSize = ptSize
self.xdpi = xdpi
self.ydpi = ydpi
self.glyphs = []
self.glyphs_by_codepoint: Dict[int, Glyph] = {}
self.comments: List[bytes] = []
def add_comment(self, comment: bytes) -> None:
"""
Add one or more lines of text to the font's comment field.
:param comment: Human-readable text to add to the
comment, ASCII encoded. It may include newline characters.
The added text will begin on a new line.
"""
lines = comment.split(b"\n")
self.comments.extend(lines)
def get_comments(self) -> List[bytes]:
"""
Retrieve the lines of the font's comment field.
:returns: The comment text, ASCII encoded.
"""
return self.comments
def __setitem__(self, name: bytes, value: PropertyValue) -> None:
self.properties[name] = value
@overload
def __getitem__(self, key: bytes) -> PropertyValue: ...
@overload
def __getitem__(self, key: int) -> Glyph: ...
def __getitem__(
self, key: Union[bytes, int]
) -> Union[PropertyValue, Glyph]:
if isinstance(key, bytes):
return self.properties[key]
elif isinstance(key, int):
return self.glyphs_by_codepoint[key]
def __delitem__(self, key: Union[bytes, int]) -> None:
if isinstance(key, bytes):
del self.properties[key]
elif isinstance(key, int):
g = self.glyphs_by_codepoint[key]
self.glyphs.remove(g)
del self.glyphs_by_codepoint[key]
def __contains__(self, key: object) -> bool:
if isinstance(key, bytes):
return key in self.properties
elif isinstance(key, int):
return key in self.glyphs_by_codepoint
else:
return False
@overload
def get(self, key: bytes) -> Optional[PropertyValue]: ...
@overload
def get(self, key: int) -> Optional[Glyph]: ...
def get(
self, key: Union[bytes, int]
) -> Optional[Union[PropertyValue, Glyph]]:
if isinstance(key, bytes):
return self.properties.get(key)
elif isinstance(key, int):
return self.glyphs_by_codepoint.get(key)
def new_glyph_from_data(
self,
name: bytes,
data: Optional[List[int]] = None,
bbX: int = 0,
bbY: int = 0,
bbW: int = 0,
bbH: int = 0,
advance: int = 0,
codepoint: Optional[int] = None,
) -> Glyph:
"""
Add a new :class:`Glyph` to this font.
This method's arguments are passed to the :class:`Glyph` constructor.
If you include the ``codepoint`` parameter, the codepoint will be
included in the result of :meth:`codepoints` and you will be able
to look up the glyph by codepoint later.
Otherwise, the glyph will only be available
via the :attr:`glyphs` property.
:returns: the newly-created Glyph
:raises GlyphExists: if an existing glyph is already associated with
the requested codepoint.
"""
g = Glyph(name, data, bbX, bbY, bbW, bbH, advance, codepoint)
if codepoint is not None and codepoint >= 0:
if codepoint in self.glyphs_by_codepoint:
old_glyph = self.glyphs_by_codepoint[codepoint]
if g == old_glyph:
# We've already got one! It's very nice.
return old_glyph
else:
# Two different glyphs with the same codepoint?
# Must be a mistake.
raise GlyphExists(
"A glyph already exists for codepoint %r" % codepoint
)
else:
# This is a genuinely new glyph, let's use it.
self.glyphs_by_codepoint[codepoint] = g
self.glyphs.append(g)
return g
def copy(self) -> "Font":
"""
Returns a deep copy of this font.
The new font, along with all of its properties and glyphs, may be
modified without affecting this font.
:returns: A new, independent copy of this Font
"""
# Create a new font object.
res = Font(self.name, self.ptSize, self.xdpi, self.ydpi)
# Copy the comments across.
for c in self.comments:
res.add_comment(c)
# Copy the properties across.
for p in self.properties:
res[p] = self[p]
# Copy the glyphs across.
for g in self.glyphs:
res.new_glyph_from_data(
g.name,
g.data,
g.bbX,
g.bbY,
g.bbW,
g.bbH,
g.advance,
g.codepoint,
)
return res
def property_names(self) -> Iterable[bytes]:
"""
Returns the names of this font's properties.
These names can be used with the regular dict syntax to retrieve the
associated value.
:returns: Property names
"""
return self.properties.keys()
def codepoints(self) -> Iterable[int]:
"""
Returns the codepoints that this font has glyphs for.
These codepoints can be used with the regular dict syntax to retrieve
the associated glyphs
:returns: Supported codepoints
"""
return self.glyphs_by_codepoint.keys()
bdflib-v2.1.0/bdflib/py.typed 0000664 0000000 0000000 00000000000 14753047770 0016047 0 ustar 00root root 0000000 0000000 bdflib-v2.1.0/bdflib/reader.py 0000664 0000000 0000000 00000045517 14753047770 0016212 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
from functools import partial
from typing import (
Iterable,
Iterator,
Optional,
List,
NamedTuple,
Callable,
Union,
)
from bdflib import model
__all__ = ["read_bdf", "ParseError", "WarningCallback"]
class Token(NamedTuple):
lineno: int
key: bytes
value: bytes
def _tokenise_bdf(
source: Iterable[bytes], comments: List[bytes]
) -> Iterator[Token]:
for lineno, line in enumerate(source, 1):
line = line.strip()
if line == b"":
continue
if b" " in line:
key, value = line.split(None, 1)
else:
key, value = line, b""
if key == b"COMMENT":
comments.append(value.strip())
continue
yield Token(lineno, key, value)
class ParseError(Exception):
"""
An error encountered by :func:`read_bdf`
"""
#: The (1-based) line number where the error was encountered
lineno: int
#: A human-readable description of the problem
message: str
def __init__(self, lineno: int, message: str):
self.lineno = lineno
self.message = message
def __str__(self) -> str:
return f"Line {self.lineno}: {self.message}"
#: The signature of a function for reporting parser warnings
WarningCallback = Callable[[int, str], None]
ParseStep = Callable[[Token, WarningCallback], Union["ParseStep", model.Font]]
def _parse_key(token: Token, expected: bytes) -> None:
if token.key != expected:
raise ParseError(
token.lineno, f"Expected {expected!r}, not {token.key!r}"
)
def _parse_int(lineno: int, value: bytes, description: str) -> int:
try:
return int(value)
except ValueError:
raise ParseError(
lineno, f"{description} must be an integer, not {value!r}"
)
def _parse_startfont(
token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"STARTFONT")
if token.value not in (b"2.0", b"2.1"):
raise ParseError(
token.lineno,
f"Only BDF versions 2.0 and 2.1 are supported, not {token.value!r}",
)
return _parse_font
def _parse_font(
token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"FONT")
if token.value == b"":
raise ParseError(token.lineno, "Font name must not be empty")
return partial(_parse_size, token.value)
def _parse_size(
name: bytes, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"SIZE")
parts = token.value.split()
if len(parts) != 3:
raise ParseError(token.lineno, "SIZE must have three values")
point_size = _parse_int(token.lineno, parts[0], "Point size")
xdpi = _parse_int(token.lineno, parts[1], "Horizontal DPI")
ydpi = _parse_int(token.lineno, parts[2], "Vertical DPI")
if point_size <= 0:
warning(token.lineno, f"Point size should be > 0, not {point_size!r}")
if xdpi <= 0:
warning(token.lineno, f"Horizontal DPI should be > 0, not {xdpi!r}")
if ydpi <= 0:
warning(token.lineno, f"Vertical DPI should be > 0, not {ydpi!r}")
return partial(
_parse_fontboundingbox, model.Font(name, point_size, xdpi, ydpi)
)
def _parse_fontboundingbox(
font: model.Font, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"FONTBOUNDINGBOX")
# We don't actually care about anything in the FONTBOUNDINGBOX,
# since we'll recalculate it ourselves from the glyphs.
return partial(_parse_startproperties_or_chars, font)
def _parse_startproperties_or_chars(
font: model.Font, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
if token.key == b"STARTPROPERTIES":
return _parse_startproperties(font, token, warning)
elif token.key == b"CHARS":
return _parse_chars(font, token, warning)
raise ParseError(
token.lineno,
f"Metadata must be followed by properties or chars, not {token.key!r}",
)
def _parse_startproperties(
font: model.Font, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"STARTPROPERTIES")
count = _parse_int(token.lineno, token.value, "Property count")
if count > 0:
return partial(_parse_property, font, count)
else:
return partial(_parse_endproperties, font)
def _parse_property(
font: model.Font, remaining: int, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
value: Optional[model.PropertyValue] = None
if token.value.startswith(b'"') and token.value.endswith(b'"'):
# Must be a string. Remove the outer quotes and un-escape embedded
# quotes.
value = token.value[1:-1].replace(b'""', b'"')
else:
try:
value = int(token.value)
except ValueError:
warning(
token.lineno,
(
f"Property {token.key!r} value must be "
+ "int or quoted string, "
+ f"not {token.value!r}"
),
)
if value is not None:
if token.key in font.property_names():
warning(
token.lineno,
(
f"Property {token.key!r} already set to "
+ repr(font[token.key])
+ ", "
+ f"ignoring new value {value!r}"
),
)
else:
font[token.key] = value
if remaining == 1:
return partial(_parse_endproperties, font)
else:
return partial(_parse_property, font, remaining - 1)
def _parse_endproperties(
font: model.Font, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"ENDPROPERTIES")
if token.value != b"":
warning(
token.lineno,
f"ENDPROPERTIES expects no value, got {token.value!r}",
)
return partial(_parse_chars, font)
def _parse_chars(
font: model.Font, token: Token, warning: WarningCallback
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"CHARS")
count = _parse_int(token.lineno, token.value, "Glyph count")
if count > 0:
return partial(_parse_startchar, font, count)
else:
return partial(_parse_endfont, font, count)
def _parse_startchar_or_endfont(
font: model.Font,
glyphs_expected: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
if token.key == b"STARTCHAR":
return _parse_startchar(font, glyphs_expected, token, warning)
elif token.key == b"ENDFONT":
return _parse_endfont(font, glyphs_expected, token, warning)
raise ParseError(
token.lineno,
f"Expected STARTCHAR or ENDFONT, not {token.key!r}",
)
def _parse_startchar(
font: model.Font,
glyphs_expected: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"STARTCHAR")
if token.value == b"":
warning(token.lineno, "Character name shouldn't be empty")
if b" " in token.value:
warning(
token.lineno,
f"Character name should not contain spaces: {token.value!r}",
)
# BDF 2.1 requires the glyph name to be 14 characters or less.
# BDF 2.2 lifts that restriction, and a number of glyph names in the
# official Adobe Glyph List are longer than that.
# Even though we don't support BDF 2.2, it's not helpful to complain about
# the name length, especially since we don't actually care.
return partial(_parse_char_encoding, font, glyphs_expected, token.value)
def _parse_char_encoding(
font: model.Font,
glyphs_expected: int,
name: bytes,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"ENCODING")
raw_codepoint = _parse_int(token.lineno, token.value, "Glyph encoding")
if raw_codepoint < -1:
warning(
token.lineno,
f"Glyph encoding must be >= -1, not {raw_codepoint!r}",
)
codepoint = None
# Anything with a negative codepoint is "unencoded"
# as far as we're concerned.
elif raw_codepoint < 0:
codepoint = None
# Codepoints must be unique.
elif raw_codepoint in font.codepoints():
warning(
token.lineno,
f"Font already has a glyph with encoding {raw_codepoint}",
)
codepoint = None
# Otherwise, the codepoint is probably fine.
else:
codepoint = raw_codepoint
return partial(
_parse_char_swidth,
font,
glyphs_expected,
name,
codepoint,
)
def _parse_char_swidth(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"SWIDTH")
# Since we are interested in bitmap fonts as bitmap fonts,
# rather than pre-rendered scalable fonts,
# we don't care about the SWIDTH,
# and we just recalculate it based on the DWIDTH.
return partial(_parse_char_dwidth, font, glyphs_expected, name, codepoint)
def _parse_char_dwidth(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"DWIDTH")
parts = token.value.split()
if len(parts) != 2:
raise ParseError(
token.lineno, f"DWIDTH must have two values, got {token.value!r}"
)
advance = _parse_int(token.lineno, parts[0], "Horizontal DWIDTH")
y_dwidth = _parse_int(token.lineno, parts[1], "Vertical DWIDTH")
if advance < 0:
warning(
token.lineno,
f"Horizontal DWIDTH should be >= 0, not {advance!r}",
)
if y_dwidth != 0:
# X11 only supports fonts with an vertial DWIDTH of 0
warning(
token.lineno,
f"Non-zero vertical DWIDTH not supported, got {y_dwidth!r}",
)
return partial(
_parse_char_bbx,
font,
glyphs_expected,
name,
codepoint,
advance,
)
def _parse_char_bbx(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"BBX")
parts = token.value.split()
if len(parts) != 4:
raise ParseError(token.lineno, "BBX must have four values")
bbW = _parse_int(token.lineno, parts[0], "Bounding box width")
bbH = _parse_int(token.lineno, parts[1], "Bounding box height")
bbX = _parse_int(token.lineno, parts[2], "Bounding box X")
bbY = _parse_int(token.lineno, parts[3], "Bounding box Y")
if bbW < 0:
raise ParseError(
token.lineno,
f"Bounding box width should be >= 0, not {bbW!r}",
)
if bbH < 0:
raise ParseError(
token.lineno,
f"Bounding box width should be >= 0, not {bbH!r}",
)
return partial(
_parse_char_attributes_or_bitmap,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
)
def _parse_char_attributes_or_bitmap(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
bbX: int,
bbY: int,
bbW: int,
bbH: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
if token.key == b"ATTRIBUTES":
return _parse_char_attributes(
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
token,
warning,
)
elif token.key == b"BITMAP":
return _parse_char_bitmap(
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
token,
warning,
)
raise ParseError(
token.lineno,
f"Expected ATTRIBUTES or BITMAP, not {token.key!r}",
)
def _parse_char_attributes(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
bbX: int,
bbY: int,
bbW: int,
bbH: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"ATTRIBUTES")
# The BDF 2.1 specification says:
# "The interpretation of these attributes is undefined in this document."
# The ATTRIBUTES field is not mentioned at all in the 2.2 spec.
# So we'll just ignore it.
return partial(
_parse_char_bitmap,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
)
def _parse_char_bitmap(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
bbX: int,
bbY: int,
bbW: int,
bbH: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"BITMAP")
if token.value != b"":
warning(
token.lineno,
f"BITMAP expects no value, got {token.value!r}",
)
if bbH > 0:
return partial(
_parse_char_bitmap_row,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
[],
)
else:
return partial(
_parse_endchar,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
[],
)
def _parse_char_bitmap_row(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
bbX: int,
bbY: int,
bbW: int,
bbH: int,
rows: List[int],
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
try:
row_int = int(token.key, 16)
except ValueError:
raise ParseError(
token.lineno, f"Expected hexadecimal digits, not {token.key!r}"
)
if token.value != b"":
warning(
token.lineno,
(
"Bitmap row should not contain spaces, got "
+ repr(token.key + b" " + token.value)
),
)
paddingbits = len(token.key) * 4 - bbW
rows.append(row_int >> paddingbits)
if len(rows) < bbH:
return partial(
_parse_char_bitmap_row,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
rows,
)
else:
return partial(
_parse_endchar,
font,
glyphs_expected,
name,
codepoint,
advance,
bbX,
bbY,
bbW,
bbH,
rows,
)
def _parse_endchar(
font: model.Font,
glyphs_expected: int,
name: bytes,
codepoint: Optional[int],
advance: int,
bbX: int,
bbY: int,
bbW: int,
bbH: int,
rows: List[int],
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"ENDCHAR")
if token.value != b"":
warning(
token.lineno,
f"ENDCHAR expects no value, got {token.value!r}",
)
# Make the list indices match the coordinate system
rows.reverse()
font.new_glyph_from_data(name, rows, bbX, bbY, bbW, bbH, advance, codepoint)
return partial(_parse_startchar_or_endfont, font, glyphs_expected)
def _parse_endfont(
font: model.Font,
glyphs_expected: int,
token: Token,
warning: WarningCallback,
) -> Union[ParseStep, model.Font]:
_parse_key(token, b"ENDFONT")
if token.value != b"":
warning(
token.lineno,
f"ENDFONT expects no value, got {token.value!r}",
)
glyphs_actual = len(font.glyphs)
if len(font.glyphs) != glyphs_expected:
warning(
token.lineno,
f"Font should have {glyphs_expected} glyphs, "
+ f"found {glyphs_actual}",
)
return font
def read_bdf(
raw_iterable: Iterable[bytes],
report_warning: Optional[WarningCallback] = None,
) -> model.Font:
"""
Read a BDF-format font from the given source.
:param raw_iterable: Each item should be a single line of the BDF file,
ASCII encoded.
:param report_warning: A callback that will be invoked to report
problems encountered during parsing the file.
These problems do not prevent the file being interpreted as BDF,
but may indicate misunderstandings or corruption.
If not provided, warnings will be discarded.
:returns: the resulting font object
:raises ParseError: if the font cannot be meaningfully interpreted
as a BDF file.
If you want to read an actual file, make sure you use the 'b' flag so
you get bytes instead of text::
def report_warning(lineno: int, message: str) -> None:
print("Problem on line {}: {}".format(lineno, message))
font = bdflib.reader.read_bdf(open(path, 'rb'), report_warning)
"""
comments: List[bytes] = []
tokens = _tokenise_bdf(raw_iterable, comments)
if report_warning is None:
def report_warning(lineno: int, message: str) -> None:
pass
step: Union[ParseStep, model.Font] = _parse_startfont
while not isinstance(step, model.Font):
try:
step = step(next(tokens), report_warning)
except StopIteration:
raise ParseError(0, "Unexpected EOF")
# Set font comments
for c in comments:
step.add_comment(c)
return step
bdflib-v2.1.0/bdflib/test/ 0000775 0000000 0000000 00000000000 14753047770 0015341 5 ustar 00root root 0000000 0000000 bdflib-v2.1.0/bdflib/test/__init__.py 0000664 0000000 0000000 00000000000 14753047770 0017440 0 ustar 00root root 0000000 0000000 bdflib-v2.1.0/bdflib/test/test_effects.py 0000664 0000000 0000000 00000021516 14753047770 0020376 0 ustar 00root root 0000000 0000000 import unittest
from bdflib import model, effects
class TestEmbolden(unittest.TestCase):
def _build_test_font(self) -> model.Font:
f = model.Font(b"TestFont", 12, 100, 100)
f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
return f
def test_basic_operation(self) -> None:
f = self._build_test_font()
f2 = effects.embolden(f)
self.assertNotEqual(f, f2)
g = f2[1]
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, 0)
self.assertEqual(g.bbW, 3)
self.assertEqual(g.bbH, 2)
self.assertEqual(g.data, [0b110, 0b011])
def test_maintaining_spacing(self) -> None:
f = effects.embolden(self._build_test_font(), True)
g = f[1]
self.assertEqual(g.advance, 4)
def test_without_maintaining_spacing(self) -> None:
f = effects.embolden(self._build_test_font(), False)
g = f[1]
self.assertEqual(g.advance, 3)
class TestExpand(unittest.TestCase):
def _build_test_font(self) -> model.Font:
f = model.Font(b"TestFont", 4, 72, 72)
f.new_glyph_from_data(
name=b"o",
data=[
0b010,
0b101,
0b010,
],
bbX=0,
bbY=0,
bbW=3,
bbH=3,
advance=4,
codepoint=ord("o"),
)
f.new_glyph_from_data(
name=b"!",
data=[
0b1,
0b1,
0b0,
0b1,
],
bbX=1,
bbY=0,
bbW=1,
bbH=4,
advance=4,
codepoint=ord("!"),
)
f.new_glyph_from_data(
name=b"-",
data=[
0b111,
],
bbX=0,
bbY=1,
bbW=3,
bbH=1,
advance=4,
codepoint=ord("-"),
)
f.new_glyph_from_data(
name=b"j",
data=[
0b001,
0b001,
0b101,
0b010,
],
bbX=0,
bbY=-1,
bbW=3,
bbH=4,
advance=4,
codepoint=ord("j"),
)
return f
def test_expand_vertically_on_baseline(self) -> None:
f = effects.expand(self._build_test_font(), 1, 2)
# This is supposed to be for correcting the aspect ratio,
# so the point size should be the same,
# but the vertical resolution should be doubled.
self.assertEqual(f.ptSize, 4)
self.assertEqual(f.xdpi, 72)
self.assertEqual(f.ydpi, 72 * 2)
# The glyphs should also be modified.
g = f[ord("o")]
self.assertEqual(
g.data,
[
0b010,
0b010,
0b101,
0b101,
0b010,
0b010,
],
)
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, 0)
self.assertEqual(g.bbW, 3)
self.assertEqual(g.bbH, 6)
self.assertEqual(g.advance, 4)
def test_expand_vertically_above_baseline(self) -> None:
"""
Glyphs above the baseline should be raised further.
"""
f = effects.expand(self._build_test_font(), 1, 2)
g = f[ord("-")]
self.assertEqual(
g.data,
[
0b111,
0b111,
],
)
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, 2)
self.assertEqual(g.bbW, 3)
self.assertEqual(g.bbH, 2)
self.assertEqual(g.advance, 4)
def test_expand_vertically_below_baseline(self) -> None:
"""
Glyphs below the baseline should be lowered further.
"""
f = effects.expand(self._build_test_font(), 1, 2)
g = f[ord("j")]
self.assertEqual(
g.data,
[
0b001,
0b001,
0b001,
0b001,
0b101,
0b101,
0b010,
0b010,
],
)
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, -2)
self.assertEqual(g.bbW, 3)
self.assertEqual(g.bbH, 8)
self.assertEqual(g.advance, 4)
def test_expand_vertically_factor_three(self) -> None:
f = effects.expand(self._build_test_font(), 1, 3)
# This is supposed to be for correcting the aspect ratio,
# so the point size should be the same,
# but the vertical resolution should be tripled.
self.assertEqual(f.ptSize, 4)
self.assertEqual(f.xdpi, 72)
self.assertEqual(f.ydpi, 72 * 3)
# The glyphs should also be modified.
g = f[ord("o")]
self.assertEqual(
g.data,
[
0b010,
0b010,
0b010,
0b101,
0b101,
0b101,
0b010,
0b010,
0b010,
],
)
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, 0)
self.assertEqual(g.bbW, 3)
self.assertEqual(g.bbH, 9)
self.assertEqual(g.advance, 4)
def test_expand_vertically_factor_zero(self) -> None:
"""
Vertical factor must be above zero.
"""
with self.assertRaises(ValueError):
effects.expand(self._build_test_font(), 1, 0)
with self.assertRaises(ValueError):
effects.expand(self._build_test_font(), 1, -1)
def test_reject_negative_vertical_factor(self) -> None:
"""
Scaling vertically by -1 flips glyph images
"""
with self.assertRaises(ValueError):
effects.expand(self._build_test_font(), 1, -1)
def test_expand_horizontally_at_left(self) -> None:
f = effects.expand(self._build_test_font(), 2, 1)
# The horizontal resolution should be doubled.
self.assertEqual(f.ptSize, 4)
self.assertEqual(f.xdpi, 72 * 2)
self.assertEqual(f.ydpi, 72)
# The glyphs should also be modified.
g = f[ord("o")]
self.assertEqual(
g.data,
[
0b001100,
0b110011,
0b001100,
],
)
self.assertEqual(g.bbX, 0)
self.assertEqual(g.bbY, 0)
self.assertEqual(g.bbW, 6)
self.assertEqual(g.bbH, 3)
self.assertEqual(g.advance, 8)
def test_expand_horizontally_after_left(self) -> None:
f = effects.expand(self._build_test_font(), 2, 1)
# The horizontal resolution should be doubled.
self.assertEqual(f.ptSize, 4)
self.assertEqual(f.xdpi, 72 * 2)
self.assertEqual(f.ydpi, 72)
# The glyphs should also be modified.
g = f[ord("!")]
self.assertEqual(
g.data,
[
0b11,
0b11,
0b00,
0b11,
],
)
self.assertEqual(g.bbX, 2)
self.assertEqual(g.bbY, 0)
self.assertEqual(g.bbW, 2)
self.assertEqual(g.bbH, 4)
self.assertEqual(g.advance, 8)
def test_expand_horizontally_factor_zero(self) -> None:
"""
Vertical factor must be above zero.
"""
with self.assertRaises(ValueError):
effects.expand(self._build_test_font(), 0, 1)
with self.assertRaises(ValueError):
effects.expand(self._build_test_font(), -1, 1)
class TestMerge(unittest.TestCase):
def test_basic_operation(self) -> None:
base_font = model.Font(b"BaseFont", 12, 100, 100)
base_font.new_glyph_from_data(b"base1", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
base_font.new_glyph_from_data(b"base2", [0b01, 0b10], 0, 0, 2, 2, 3, 2)
cust_font = model.Font(b"CustomFont", 12, 100, 100)
cust_font.new_glyph_from_data(b"cust2", [0b1, 0b1], 0, 0, 2, 2, 3, 2)
cust_font.new_glyph_from_data(b"cust3", [0b1, 0b1], 0, 0, 2, 2, 3, 3)
# Start by merging the custom font on top of the base font.
merged1 = effects.merge(base_font, cust_font)
# We should get an entirely new font.
self.assertNotEqual(merged1, base_font)
self.assertNotEqual(merged1, cust_font)
# The new font should have cust* characters in preference to base
# characters.
self.assertEqual(merged1[1].name, b"base1")
self.assertEqual(merged1[2].name, b"cust2")
self.assertEqual(merged1[3].name, b"cust3")
# If we merge things the other way around...
merged2 = effects.merge(cust_font, base_font)
# ...the new font should prefer base* characters.
self.assertEqual(merged2[1].name, b"base1")
self.assertEqual(merged2[2].name, b"base2")
self.assertEqual(merged2[3].name, b"cust3")
bdflib-v2.1.0/bdflib/test/test_glyph_combining.py 0000664 0000000 0000000 00000034546 14753047770 0022136 0 ustar 00root root 0000000 0000000 import unittest
from bdflib import glyph_combining, model
class TestBuildUnicodeDecompositions(unittest.TestCase):
def test_basic_functionality(self) -> None:
"""
build_unicode_decompositions should run without crashing.
"""
res = glyph_combining.build_unicode_decompositions()
# It should return a dict.
self.assertEqual(type(res), dict)
# It should return a non-empty dict.
self.assertNotEqual(res, {})
# It should have a decompositions for simple accented letters.
self.assertIn("\N{LATIN CAPITAL LETTER A WITH GRAVE}", res)
# It should not have decompositions for complicated things like
# superscripts.
self.assertNotIn("\N{SUPERSCRIPT TWO}", res)
# Decompositions should be iterables of (unicode char, int) tuples.
for decomposable in res:
for char, combining_class in res[decomposable]:
self.assertEqual(type(char), type("a"))
self.assertEqual(len(char), 1)
self.assertEqual(type(combining_class), int)
def test_base_dotless_i_and_j(self) -> None:
"""
Accented "i" should be based on a dotless i.
"""
res = glyph_combining.build_unicode_decompositions()
# If there's an accent above the 'i', the base glyph should be
# a dotless 'i'.
components = res["\N{LATIN SMALL LETTER I WITH DIAERESIS}"]
self.assertEqual(components[0], ("\N{LATIN SMALL LETTER DOTLESS I}", 0))
# If the accent is elsewhere, the base glyph should be a dotted 'i'.
components = res["\N{LATIN SMALL LETTER I WITH OGONEK}"]
self.assertEqual(components[0], ("i", 0))
# Likewise, a 'j' with an accent above should be based on dotless 'j'
components = res["\N{LATIN SMALL LETTER J WITH CIRCUMFLEX}"]
self.assertEqual(components[0], ("\N{LATIN SMALL LETTER DOTLESS J}", 0))
# ...and a 'j' with any other accent should be dotted, but the only
# Unicode characters that decompose to a 'j' and an accent have the
# accent above, so there's no test we can test here.
class TestFontFiller(unittest.TestCase):
def setUp(self) -> None:
# Create a simple font with two characters
self.font = model.Font(b"TestFont", 12, 100, 100)
self.font.new_glyph_from_data(
b"a", [0b10, 0b01], 0, 0, 2, 2, 3, ord("a")
)
self.font.new_glyph_from_data(
b"b", [0b01, 0b10], 0, 0, 2, 2, 3, ord("b")
)
# Create a dictionary that says how to combine them.
self.decompositions = {
# A simple combination of basic characters.
"c": [("a", 0), ("b", 0)],
# A recursive definition
"d": [("c", 0), ("a", 0), ("b", 0)],
# A definition that can't be solved with the glyphs in this
# font.
"e": [("f", 0), ("g", 0)],
# A definition that involves an unknown combining class
"h": [("a", 0), ("b", 256)],
}
self.filler = glyph_combining.FontFiller(self.font, self.decompositions)
def test_basic_functionality(self) -> None:
"""
We succeed if we have a decomposition and the components.
"""
added = self.filler.add_glyph_to_font("c")
self.assertEqual(added, True)
self.assertEqual(self.filler.missing_chars, {})
self.assertEqual(self.filler.unknown_classes, {})
glyph = self.font[ord("c")]
print(glyph)
self.assertEqual(str(glyph), "|#.#.\n" "#---#")
def test_recursive_functionality(self) -> None:
"""
We succeed even if we can only get the components recursively.
"""
added = self.filler.add_glyph_to_font("d")
self.assertEqual(added, True)
self.assertEqual(self.filler.missing_chars, {})
self.assertEqual(self.filler.unknown_classes, {})
glyph = self.font[ord("d")]
print(glyph)
self.assertEqual(str(glyph), "|#.#...#.#.\n" "#---#-#---#")
def test_character_present(self) -> None:
"""
We succeed if the char is already in the font.
"""
added = self.filler.add_glyph_to_font("a")
self.assertEqual(self.filler.missing_chars, {})
self.assertEqual(self.filler.unknown_classes, {})
self.assertEqual(added, True)
def test_missing_decomposition(self) -> None:
"""
We fail if there's no decomposition for the given character.
"""
added = self.filler.add_glyph_to_font("z")
self.assertEqual(self.filler.missing_chars, {})
self.assertEqual(self.filler.unknown_classes, {})
self.assertEqual(added, False)
def test_missing_recursive_decomposition(self) -> None:
"""
We fail if there's a decomposition but no components for a character.
"""
added = self.filler.add_glyph_to_font("e")
self.assertEqual(self.filler.missing_chars, {"f": 1})
self.assertEqual(self.filler.unknown_classes, {})
self.assertEqual(added, False)
def test_unknown_combining_class(self) -> None:
"""
We fail if there's a decomposition but we don't know how to use it.
"""
added = self.filler.add_glyph_to_font("h")
self.assertEqual(self.filler.missing_chars, {})
self.assertEqual(self.filler.unknown_classes, {256: 1})
self.assertEqual(added, False)
def test_add_decomposable_glyphs_to_font(self) -> None:
"""
Add all the glyphs we can to the given font.
"""
self.filler.add_decomposable_glyphs_to_font()
self.assertIn(ord("c"), self.font)
self.assertIn(ord("d"), self.font)
self.assertEqual(self.filler.missing_chars, {"f": 1})
self.assertEqual(self.filler.unknown_classes, {256: 1})
class TestFontFillerCombiningAbove(unittest.TestCase):
def _build_composing_above_font(
self, set_cap_height: bool = False
) -> model.Font:
"""
Return a font with glyphs useful for testing COMBINING ABOVE.
"""
font = model.Font(b"TestFont", 12, 100, 100)
# Some glyphs for testing accent placement
font.new_glyph_from_data(b"space", [], 0, 0, 0, 0, 4, ord(" "))
font.new_glyph_from_data(
b"O",
[
0b010,
0b101,
0b101,
0b010,
],
0,
0,
3,
4,
4,
ord("O"),
)
font.new_glyph_from_data(
b"o",
[
0b010,
0b101,
0b010,
],
0,
0,
3,
3,
4,
ord("o"),
)
font.new_glyph_from_data(
b"macron",
[0b1111],
0,
5,
4,
1,
4,
ord("\N{COMBINING MACRON}"),
)
font.new_glyph_from_data(
b"caron",
[
0b101,
0b010,
],
0,
5,
3,
2,
4,
ord("\N{COMBINING CARON}"),
)
if set_cap_height:
font[b"CAP_HEIGHT"] = 4
decompositions = {
# Test combining an odd-width base-character with an even-width
# accent.
"I": [("O", 0), ("\N{COMBINING MACRON}", glyph_combining.CC_A)],
"i": [("o", 0), ("\N{COMBINING MACRON}", glyph_combining.CC_A)],
# Test combining an odd-width base-character with an odd-width
# accent.
"J": [("O", 0), ("\N{COMBINING CARON}", glyph_combining.CC_A)],
"j": [("o", 0), ("\N{COMBINING CARON}", glyph_combining.CC_A)],
"\N{MACRON}": [
(" ", 0),
("\N{COMBINING MACRON}", glyph_combining.CC_A),
],
}
glyph_combining.FontFiller(
font,
decompositions,
).add_decomposable_glyphs_to_font()
return font
def test_composing_even_above_odd(self) -> None:
font = self._build_composing_above_font()
O_macron = font[ord("I")]
print(O_macron)
self.assertEqual(
str(O_macron),
"####\n" "|...\n" "|#..\n" "#.#.\n" "#.#.\n" "+#--",
)
def test_composing_odd_above_odd(self) -> None:
font = self._build_composing_above_font()
O_caron = font[ord("J")]
print(O_caron)
self.assertEqual(
str(O_caron), "|#.\n" "#.#\n" "|..\n" "|#.\n" "#.#\n" "#.#\n" "+#-"
)
def test_composing_above_without_CAP_HEIGHT(self) -> None:
# Build the font without CAP_HEIGHT set.
font = self._build_composing_above_font(False)
# Upper case and lower-case should have the accent at the same place.
O_caron = font[ord("J")]
print(O_caron)
self.assertEqual(
str(O_caron), "|#.\n" "#.#\n" "|..\n" "|#.\n" "#.#\n" "#.#\n" "+#-"
)
o_caron = font[ord("j")]
print(o_caron)
self.assertEqual(
str(o_caron), "|#.\n" "#.#\n" "|..\n" "|..\n" "|#.\n" "#.#\n" "+#-"
)
def test_composing_above_with_CAP_HEIGHT(self) -> None:
# Build the font with CAP_HEIGHT set.
font = self._build_composing_above_font(True)
# Upper case should be the same.
O_caron = font[ord("J")]
print(O_caron)
self.assertEqual(
str(O_caron), "|#.\n" "#.#\n" "|..\n" "|#.\n" "#.#\n" "#.#\n" "+#-"
)
# The accent should be as high above lowercase as it is above
# upper-case.
o_caron = font[ord("j")]
print(o_caron)
self.assertEqual(
str(o_caron), "|#.\n" "#.#\n" "|..\n" "|#.\n" "#.#\n" "+#-"
)
def test_composing_above_blank_base(self) -> None:
"""
Composing on top of a blank base char should work.
"""
# Build the font with CAP_HEIGHT set.
font = self._build_composing_above_font(True)
# Macron should be drawn in the usual place.
macron = font[ord("\N{MACRON}")]
print(macron)
self.assertEqual(
str(macron), "####\n" "|...\n" "|...\n" "|...\n" "|...\n" "+---"
)
# Without CAP_HEIGHT set, the same should happen.
font = self._build_composing_above_font(False)
# Macron should be drawn in the usual place.
macron = font[ord("\N{MACRON}")]
print(macron)
self.assertEqual(
str(macron), "####\n" "|...\n" "|...\n" "|...\n" "|...\n" "+---"
)
class TestFontFillerCombiningBelow(unittest.TestCase):
def _build_composing_below_font(self) -> model.Font:
"""
Return a font with glyphs useful for testing COMBINING BELOW.
"""
font = model.Font(b"TestFont", 12, 100, 100)
# Some glyphs for testing accent placement
font.new_glyph_from_data(b"space", [], 0, 0, 0, 0, 4, ord(" "))
font.new_glyph_from_data(
b"Y",
[
0b010,
0b010,
0b101,
0b101,
],
0,
0,
3,
4,
4,
ord("Y"),
)
font.new_glyph_from_data(
b"y",
[
0b110,
0b001,
0b011,
0b101,
0b101,
],
0,
-2,
3,
5,
4,
ord("y"),
)
font.new_glyph_from_data(
b"macron_below",
[0b1111],
0,
-2,
4,
1,
4,
ord("\N{COMBINING MACRON BELOW}"),
)
font.new_glyph_from_data(
b"dot_below",
[0b1],
0,
-2,
1,
1,
1,
ord("\N{COMBINING DOT BELOW}"),
)
decompositions = {
# Test combining an odd-width base-character with an even-width
# accent.
"I": [
("Y", 0),
("\N{COMBINING MACRON BELOW}", glyph_combining.CC_B),
],
"i": [
("y", 0),
("\N{COMBINING MACRON BELOW}", glyph_combining.CC_B),
],
# Test combining an odd-width base-character with an odd-width
# accent.
"J": [
("Y", 0),
("\N{COMBINING DOT BELOW}", glyph_combining.CC_A),
],
"j": [
("y", 0),
("\N{COMBINING DOT BELOW}", glyph_combining.CC_B),
],
"_": [
(" ", 0),
("\N{COMBINING MACRON BELOW}", glyph_combining.CC_B),
],
}
glyph_combining.FontFiller(
font,
decompositions,
).add_decomposable_glyphs_to_font()
return font
def test_composing_even_below_odd(self) -> None:
font = self._build_composing_below_font()
Y_macron = font[ord("I")]
print(Y_macron)
self.assertEqual(
str(Y_macron), "#.#.\n" "#.#.\n" "|#..\n" "+#--\n" "|...\n" "####"
)
def test_composing_odd_below_odd(self) -> None:
font = self._build_composing_below_font()
Y_dot = font[ord("J")]
print(Y_dot)
self.assertEqual(
str(Y_dot), "#.#\n" "#.#\n" "|#.\n" "+#-\n" "|..\n" "|#."
)
def test_composing_below_clears_descenders(self) -> None:
font = self._build_composing_below_font()
# Upper case and lower-case should have the accent at the same place.
Y_dot = font[ord("J")]
print(Y_dot)
self.assertEqual(
str(Y_dot), "#.#\n" "#.#\n" "|#.\n" "+#-\n" "|..\n" "|#."
)
y_dot = font[ord("j")]
print(y_dot)
self.assertEqual(
str(y_dot), "#.#\n" "#.#\n" "+##\n" "|.#\n" "##.\n" "|..\n" "|#."
)
def test_composing_below_blank_base(self) -> None:
"""
Composing on top of a blank base char should work.
"""
font = self._build_composing_below_font()
# Underscore should be drawn in the usual place.
underscore = font[ord("_")]
print(underscore)
self.assertEqual(str(underscore), "+---\n" "|...\n" "####")
bdflib-v2.1.0/bdflib/test/test_model.py 0000664 0000000 0000000 00000033315 14753047770 0020057 0 ustar 00root root 0000000 0000000 import unittest
from bdflib import model
class TestFont(unittest.TestCase):
def test_basic_properties(self) -> None:
f = model.Font(name=b"TestFont", ptSize=12, xdpi=100, ydpi=100)
# Test that we're storing font fields as attributes.
self.assertEqual(f.name, b"TestFont")
self.assertEqual(f.ptSize, 12)
self.assertEqual(f.xdpi, 100)
self.assertEqual(f.ydpi, 100)
def test_property_setting(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
f[b"CHARSET_REGISTRY"] = b"iso8859"
self.assertEqual(f[b"CHARSET_REGISTRY"], b"iso8859")
self.assertEqual(f.get(b"CHARSET_REGISTRY"), b"iso8859")
def test_property_removal(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
# Add the property
f[b"CHARSET_REGISTRY"] = b"iso8859"
# Remove the property
del f[b"CHARSET_REGISTRY"]
self.assertNotIn(b"CHARSET_REGISTRY", f)
def test_property_iteration(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
self.assertEqual(list(f.property_names()), [])
f[b"CUSTOM_PROP1"] = b"hello"
f[b"CUSTOM_PROP2"] = b"world"
self.assertEqual(
sorted(f.property_names()),
[b"CUSTOM_PROP1", b"CUSTOM_PROP2"],
)
def test_add_glyph_with_codepoint(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 5)
self.assertEqual(f[5], g)
self.assertEqual(f.get(5), g)
def test_codepoint_removal(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 5)
del f[5]
self.assertNotIn(5, f.codepoints())
self.assertNotIn(g, f.glyphs)
def test_codepoint_iteration(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
# Add glyphs at code-points out-of-order.
f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 5)
f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 16)
f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 37)
f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 93)
codepoints = list(f.codepoints())
codepoints.sort()
self.assertEqual(codepoints, [5, 16, 37, 93])
def test_font_does_not_contain_other_things(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
# The font only stores bytestrings (properties) and ints (codepoints),
# not other random things.
self.assertNotIn((1, 2, 3), f)
def test_comments(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
f.add_comment(b"This is another comment")
f.add_comment(b"hello, world!\nMultiple lines!")
self.assertEqual(
f.get_comments(),
[
b"This is another comment",
b"hello, world!",
b"Multiple lines!",
],
)
def test_font_copying(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
f.new_glyph_from_data(
b"TestGlyph",
[
0b0001,
0b0000,
0b0000,
0b0000,
0b0000,
0b1000,
],
-3,
-4,
4,
6,
8,
1,
)
f.add_comment(b"This is another comment")
f.add_comment(b"hello, world!\nMultiple lines!")
f[b"SOMEPROPERTY"] = b"Some value"
f2 = f.copy()
self.assertEqual(
f2.get_comments(),
[
b"This is another comment",
b"hello, world!",
b"Multiple lines!",
],
)
self.assertEqual(f2[b"SOMEPROPERTY"], b"Some value")
g2 = f2[1]
self.assertEqual(g2.name, b"TestGlyph")
self.assertEqual(
g2.data,
[
0b0001,
0b0000,
0b0000,
0b0000,
0b0000,
0b1000,
],
)
self.assertEqual(g2.get_bounding_box(), (-3, -4, 4, 6))
self.assertEqual(g2.advance, 8)
self.assertEqual(g2.codepoint, 1)
self.assertEqual(f2[g2.codepoint], g2)
class TestGlyph(unittest.TestCase):
def test_glyph_creation(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(
b"TestGlyph",
[
0b0001,
0b0000,
0b0000,
0b0000,
0b0000,
0b1000,
],
-3,
-4,
4,
6,
8,
1,
)
self.assertEqual(g.name, b"TestGlyph")
self.assertEqual(
g.data,
[
0b0001,
0b0000,
0b0000,
0b0000,
0b0000,
0b1000,
],
)
self.assertEqual(g.get_bounding_box(), (-3, -4, 4, 6))
self.assertEqual(g.advance, 8)
self.assertEqual(g.codepoint, 1)
self.assertEqual(f[g.codepoint], g)
def test_duplicate_codepoints(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
f.new_glyph_from_data(b"TestGlyph1", codepoint=1)
self.assertEqual(len(f.glyphs), 1)
self.assertRaises(
model.GlyphExists,
f.new_glyph_from_data,
b"TestGlyph2",
codepoint=1,
)
# The glyph should not have been added to the font
self.assertEqual(len(f.glyphs), 1)
def test_accept_duplicate_codepoints_for_identical_glyphs(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g1 = f.new_glyph_from_data(b"TestGlyph1", codepoint=1)
self.assertEqual(len(f.glyphs), 1)
# Add a second glyph with the same content and codepoint
g2 = f.new_glyph_from_data(b"TestGlyph1", codepoint=1)
# Still only one glyph in the font
self.assertEqual(len(f.glyphs), 1)
# Should have returned the original glyph as the "new" glyph
self.assertIs(g1, g2)
def test_glyph_merging_no_op(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself at 0,0
g.merge_glyph(g, 0, 0)
# Nothing should have changed.
self.assertEqual(g.get_bounding_box(), (0, 0, 2, 2))
self.assertEqual(
g.data,
[
0b10,
0b01,
],
)
def test_glyph_merging_above(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself but a few rows higher.
g.merge_glyph(g, 0, 4)
# The bounding box should be higher.
self.assertEqual(g.get_bounding_box(), (0, 0, 2, 6))
# There should be some blank rows in the bitmap
self.assertEqual(
g.data,
[
0b10,
0b01,
0b00,
0b00,
0b10,
0b01,
],
)
def test_glyph_merging_below(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b01, 0b10], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself but a row lower.
g.merge_glyph(g, 0, -3)
# The origin vector should have moved downward, and the height
# increased to compensate.
self.assertEqual(g.get_bounding_box(), (0, -3, 2, 5))
# There should be a blank row in the bitmap
self.assertEqual(
g.data,
[
0b01,
0b10,
0b00,
0b01,
0b10,
],
)
def test_glyph_merging_left(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself a few columns to the left.
g.merge_glyph(g, -4, 0)
# The origin vector should have moved left, and the width enlarged to
# compensate.
self.assertEqual(g.get_bounding_box(), (-4, 0, 6, 2))
# The bitmap should be wider.
self.assertEqual(
g.data,
[
0b100010,
0b010001,
],
)
def test_glyph_merging_right(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself a few columns to the right.
g.merge_glyph(g, 3, 0)
# The origin vector should be the same, and the width enlarged.
self.assertEqual(g.get_bounding_box(), (0, 0, 5, 2))
# The bitmap should be wider.
self.assertEqual(
g.data,
[
0b10010,
0b01001,
],
)
def test_glyph_merging_offset_glyph(self) -> None:
"""
Merging a glyph whose bitmap doesn't start at (0,0)
"""
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 1, 1, 2, 2, 3, 1)
# Draw this glyph onto itself to make a diamond.
g.merge_glyph(g, -1, 1)
# The origin vector should be the same, and the width enlarged.
self.assertEqual(g.get_bounding_box(), (0, 1, 3, 3))
# The bitmap should be a larger diagonal.
self.assertEqual(
g.data,
[
0b010,
0b101,
0b010,
],
)
def test_glyph_merging(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
# Draw this glyph onto itself at 2,2
g.merge_glyph(g, 2, 2)
# Check the results
self.assertEqual(g.get_bounding_box(), (0, 0, 4, 4))
self.assertEqual(
g.data,
[
0b1000,
0b0100,
0b0010,
0b0001,
],
)
def test_glyph_printing(self) -> None:
# A small circle
glyph_data = [
0b01110,
0b10001,
0b10001,
0b10001,
0b01110,
]
f = model.Font(b"TestFont", 12, 100, 100)
glyphs = []
for offset in range(0, 7):
glyphs.append(
f.new_glyph_from_data(
b"TestGlyph%d" % offset,
glyph_data,
-5 + offset,
-5 + offset,
5,
5,
offset,
offset,
)
)
for g in glyphs:
print(g)
print()
self.assertEqual(
[str(g) for g in glyphs],
[
"-----+\n.###.|\n#...#|\n#...#|\n#...#|\n.###.|",
"-###+\n#...#\n#...#\n#...#\n.###|",
".###.\n#--+#\n#..|#\n#..|#\n.###.",
".###.\n#.|.#\n#-+-#\n#.|.#\n.###.",
".###.\n#|..#\n#|..#\n#+--#\n.###.",
"|###.\n#...#\n#...#\n#...#\n+###-",
"|.###.\n|#...#\n|#...#\n|#...#\n|.###.\n+-----",
],
)
def test_glyph_get_ascent_and_descent(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
# For a simple glyph at the origin, ascent and descent should match the
# bitmap bounding box.
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1)
self.assertEqual(g.get_ascent(), 2)
self.assertEqual(g.get_descent(), 0)
# If the bitmap crosses the baseline, we should get a positive ascent
# and descent.
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, -1, 2, 2, 3, 2)
self.assertEqual(g.get_ascent(), 1)
self.assertEqual(g.get_descent(), 1)
# If the bitmap is well above the baseline, ascent should be positive
# and descent negative.
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, 1, 2, 2, 3, 3)
self.assertEqual(g.get_ascent(), 3)
self.assertEqual(g.get_descent(), -1)
# If the bitmap is well below the baseline, ascent should be negative
# and descent positive.
g = f.new_glyph_from_data(b"TestGlyph", [0b10, 0b01], 0, -3, 2, 2, 3, 4)
self.assertEqual(g.get_ascent(), -1)
self.assertEqual(g.get_descent(), 3)
# Ascent and descent should be calculated from the actual extents of
# the character, not the bitmap.
g = f.new_glyph_from_data(
b"TestGlyph", [0b00, 0b10, 0b01, 0b00], 0, -2, 2, 4, 3, 5
)
self.assertEqual(g.get_ascent(), 1)
self.assertEqual(g.get_descent(), 1)
def test_iter_pixels(self) -> None:
f = model.Font(b"TestFont", 12, 100, 100)
g = f.new_glyph_from_data(
name=b"LATIN SMALL LETTER H",
data=[0b101, 0b111, 0b100],
bbX=0,
bbY=0,
bbW=3,
bbH=3,
advance=4,
codepoint=ord("h"),
)
pixels = [list(row) for row in g.iter_pixels()]
self.assertEqual(
pixels,
[
[True, False, False],
[True, True, True],
[True, False, True],
],
)
bdflib-v2.1.0/bdflib/test/test_reader.py 0000664 0000000 0000000 00000104050 14753047770 0020214 0 ustar 00root root 0000000 0000000 from typing import List, Tuple
import unittest
from io import BytesIO
from bdflib import model, reader
# This comes from the X11 BDF spec.
SAMPLE_FONT = b"""
STARTFONT 2.1
COMMENT This is a sample font in 2.1 format.
FONT -Adobe-Helvetica-Bold-R-Normal--24-240-75-75-P-65-ISO8859-1
SIZE 24 75 75
FONTBOUNDINGBOX 9 24 -2 -6
STARTPROPERTIES 19
FOUNDRY "Adobe"
FAMILY "Helvetica"
WEIGHT_NAME "Bold"
SLANT "R"
SETWIDTH_NAME "Normal"
ADD_STYLE_NAME ""
PIXEL_SIZE 24
POINT_SIZE 240
RESOLUTION_X 75
RESOLUTION_Y 75
SPACING "P"
AVERAGE_WIDTH 65
CHARSET_REGISTRY "ISO8859"
CHARSET_ENCODING "1"
MIN_SPACE 4
FONT_ASCENT 21
FONT_DESCENT 7
COPYRIGHT "Copyright (c) 1987 Adobe Systems, Inc."
NOTICE "Helvetica is a registered trademark of Linotype Inc."
ENDPROPERTIES
CHARS 2
STARTCHAR j
ENCODING 106
SWIDTH 355 0
DWIDTH 8 0
BBX 9 22 -2 -6
BITMAP
0380
0380
0380
0380
0000
0700
0700
0700
0700
0E00
0E00
0E00
0E00
0E00
1C00
1C00
1C00
1C00
3C00
7800
F000
E000
ENDCHAR
STARTCHAR quoteright
ENCODING 39
SWIDTH 223 0
DWIDTH 5 0
BBX 4 6 2 12
ATTRIBUTES 01C0
BITMAP
70
70
70
60
E0
C0
ENDCHAR
ENDFONT
""".strip()
class TestReadFont(unittest.TestCase):
def _check_font(self, font: model.Font) -> None:
"""
Checks that the given font is a representation of the sample font.
"""
self.assertEqual(
font.name,
b"-Adobe-Helvetica-Bold-R-Normal--24-240-75-75-P-65-ISO8859-1",
)
self.assertEqual(font.ptSize, 24.0)
self.assertEqual(font.xdpi, 75)
self.assertEqual(font.ydpi, 75)
self.assertEqual(
font.get_comments(), [b"This is a sample font in 2.1 format."]
)
self.assertEqual(len(font.glyphs), 2)
# Our code ignores PIXEL_SIZE but adds FACE_NAME, so the total is still
# 19.
self.assertEqual(len(font.properties), 19)
def test_basic_operation(self) -> None:
testFontData = BytesIO(SAMPLE_FONT)
testFont = reader.read_bdf(testFontData)
self._check_font(testFont)
def test_extra_blank_lines(self) -> None:
"""
We should ignore any extra lines in the input.
"""
testFontData = BytesIO(SAMPLE_FONT.replace(b"\n", b"\n\n"))
testFont = reader.read_bdf(testFontData)
self._check_font(testFont)
def test_reject_illegible_font(self) -> None:
input = [b"blah blah blah"]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 1: Expected b'STARTFONT', not b'blah'"
)
def test_reject_unsupported_bdf_version(self) -> None:
input = [b"STARTFONT 1.9"]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 1: Only BDF versions 2.0 and 2.1 are supported, not b'1.9'",
)
input = [b"STARTFONT 2.2"]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 1: Only BDF versions 2.0 and 2.1 are supported, not b'2.2'",
)
def test_reject_font_with_no_metadata(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"ENDFONT\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 3: Expected b'SIZE', not b'ENDFONT'"
)
def test_accept_font_with_only_metadata(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 0\n",
b"ENDFONT\n",
]
f = reader.read_bdf(input)
self.assertEqual(f.name, b"Awesome Font")
self.assertEqual(f.ptSize, 12)
self.assertEqual(f.xdpi, 72)
self.assertEqual(f.ydpi, 72)
self.assertEqual(f.glyphs, [])
self.assertEqual(list(f.property_names()), [])
self.assertEqual(list(f.codepoints()), [])
def test_accept_font_with_empty_property_list(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 0\n",
b"ENDPROPERTIES\n",
b"CHARS 0\n",
b"ENDFONT\n",
]
f = reader.read_bdf(input)
self.assertEqual(f.name, b"Awesome Font")
self.assertEqual(f.ptSize, 12)
self.assertEqual(f.xdpi, 72)
self.assertEqual(f.ydpi, 72)
self.assertEqual(f.glyphs, [])
self.assertEqual(list(f.property_names()), [])
self.assertEqual(list(f.codepoints()), [])
def test_reject_unnamed_font(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT\n",
b"ENDFONT\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 2: Font name must not be empty"
)
def test_reject_font_with_missing_size(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72\n",
b"ENDFONT\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 3: SIZE must have three values"
)
def test_reject_font_with_corrupt_size(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 blah\n",
b"ENDFONT\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 3: Vertical DPI must be an integer, not b'blah'",
)
def test_warn_font_with_negative_size(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE -12 72 72\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(
str(cm.exception),
"Line 4: Expected b'FONTBOUNDINGBOX', not b'ENDFONT'",
)
expected = (3, "Point size should be > 0, not -12")
self.assertIn(expected, warnings)
def test_warn_font_with_negative_xdpi(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 -72 72\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(
str(cm.exception),
"Line 4: Expected b'FONTBOUNDINGBOX', not b'ENDFONT'",
)
expected = (3, "Horizontal DPI should be > 0, not -72")
self.assertIn(expected, warnings)
def test_warn_font_with_negative_ydpi(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 -72\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(
str(cm.exception),
"Line 4: Expected b'FONTBOUNDINGBOX', not b'ENDFONT'",
)
expected = (3, "Vertical DPI should be > 0, not -72")
self.assertIn(expected, warnings)
def test_reject_font_missing_required_metadata(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"STARTPROPERTIES 4\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 2: Expected b'FONT', not b'STARTPROPERTIES'",
)
input = [
b"STARTFONT 2.1\n",
b"CHARS 4\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 2: Expected b'FONT', not b'CHARS'",
)
def test_reject_font_with_unexpected_metadata(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"BLAH\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
(
"Line 5: Metadata must be followed by properties or chars, "
+ "not b'BLAH'"
),
)
def test_reject_font_missing_property_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 5: Property count must be an integer, not b''",
)
def test_reject_font_with_corrupt_property_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES blah\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 5: Property count must be an integer, not b'blah'",
)
def test_warn_font_with_missing_property_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 5\n",
b"AVERAGE_WIDTH\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (
6,
(
"Property b'AVERAGE_WIDTH' value must be int or quoted string, "
+ "not b''"
),
)
self.assertIn(expected, warnings)
def test_warn_font_with_corrupt_property_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 5\n",
b"AVERAGE_WIDTH blah\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (
6,
(
"Property b'AVERAGE_WIDTH' value must be int or quoted string, "
+ "not b'blah'"
),
)
self.assertIn(expected, warnings)
def test_warn_font_with_duplicate_property_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 5\n",
b"AVERAGE_WIDTH 7\n",
b"AVERAGE_WIDTH 8\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (
7,
"Property b'AVERAGE_WIDTH' already set to 7, ignoring new value 8",
)
self.assertIn(expected, warnings)
def test_reject_font_with_wrong_property_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 2\n",
b"AVERAGE_WIDTH 10\n",
b"AVERAGE_RAINFALL 20\n",
b"AVERAGE_SALARY 30\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 8: Expected b'ENDPROPERTIES', not b'AVERAGE_SALARY'",
)
def test_warn_font_with_endproperties_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"STARTPROPERTIES 1\n",
b"AVERAGE_WIDTH 7\n",
b"ENDPROPERTIES blah\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (7, "ENDPROPERTIES expects no value, got b'blah'")
self.assertIn(expected, warnings)
def test_reject_font_missing_char_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 5: Glyph count must be an integer, not b''"
)
def test_reject_font_with_corrupt_char_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS blah\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 5: Glyph count must be an integer, not b'blah'",
)
def test_warn_glyph_with_missing_char_name(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (6, "Character name shouldn't be empty")
self.assertIn(expected, warnings)
def test_warn_glyph_with_char_name_with_spaces(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR o circumflex\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (
6,
"Character name should not contain spaces: b'o circumflex'",
)
self.assertIn(expected, warnings)
def test_reject_glyph_with_missing_encoding_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 7: Glyph encoding must be an integer, not b''",
)
def test_reject_glyph_with_corrupt_encoding_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING blah\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 7: Glyph encoding must be an integer, not b'blah'",
)
def test_reject_glyph_with_invalid_encoding_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING -2\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (7, "Glyph encoding must be >= -1, not -2")
self.assertIn(expected, warnings)
def test_accept_glyph_with_no_encoding(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING -1\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 2 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR\n",
b"ENDFONT\n",
]
f = reader.read_bdf(input)
# Make sure this glyph is unencoded
self.assertNotIn(-1, f)
self.assertEqual(len(f.glyphs), 1)
g = f.glyphs[0]
self.assertEqual(g.name, b"j")
self.assertEqual(g.codepoint, -1)
def test_warn_glyph_with_duplicate_encoding(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 2\n",
b"STARTCHAR j1\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR\n",
b"STARTCHAR j2\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 2 2 3 4\n",
b"BITMAP\n",
b"10\n",
b"01\n",
b"ENDCHAR\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
f = reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
# One glyph gets a codepoint
self.assertEqual(list(f.codepoints()), [106])
# But there should be two glyphs
self.assertEqual(len(f.glyphs), 2)
# Let's get the names and codepoints of glyphs in the font
actual = set((g.name, g.codepoint) for g in f.glyphs)
# The first glyph should be fine,
# the second glyph should be de-encoded
# (but still exist)
expected = set(
[
(b"j1", 106),
(b"j2", -1),
]
)
self.assertEqual(actual, expected)
# There should be a warning about it
self.assertIn(
(16, "Font already has a glyph with encoding 106"), warnings
)
def test_reject_glyph_with_missing_dwidth_values(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 9: DWIDTH must have two values, got b''"
)
def test_reject_glyph_with_missing_dwidth_y_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 12\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 9: DWIDTH must have two values, got b'12'"
)
def test_warn_glyph_with_non_zero_dwidth_y_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 12 1\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (9, "Non-zero vertical DWIDTH not supported, got 1")
self.assertIn(expected, warnings)
def test_reject_glyph_with_corrupt_dwidth_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH blah 0\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 9: Horizontal DWIDTH must be an integer, not b'blah'",
)
def test_warn_glyph_with_negative_advance(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH -3 0\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(cm.exception.lineno, 0)
self.assertEqual(cm.exception.message, "Unexpected EOF")
expected = (9, "Horizontal DWIDTH should be >= 0, not -3")
self.assertIn(expected, warnings)
def test_reject_glyph_with_missing_bbx_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception), "Line 10: BBX must have four values"
)
def test_reject_glyph_with_corrupt_bbx_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 blah\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 10: Bounding box Y must be an integer, not b'blah'",
)
def test_reject_glyph_with_invalid_bb_width(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX -1 2 3 4\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 10: Bounding box width should be >= 0, not -1",
)
def test_reject_glyph_with_invalid_bb_height(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 -2 3 4\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 10: Bounding box width should be >= 0, not -2",
)
def test_reject_glyph_with_unexpected_metadata(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BLAH\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 11: Expected ATTRIBUTES or BITMAP, not b'BLAH'",
)
def test_warn_glyph_with_bitmap_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP blah\n",
]
warnings: List[Tuple[int, str]] = []
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertEqual(
str(cm.exception),
"Line 0: Unexpected EOF",
)
self.assertIn((11, "BITMAP expects no value, got b'blah'"), warnings)
def test_reject_glyph_with_not_enough_rows(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"00\n",
b"ENDCHAR\n",
b"STARTCHAR k\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 13: Expected hexadecimal digits, not b'ENDCHAR'",
)
def test_reject_glyph_with_too_many_rows(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"00\n",
b"00\n",
b"00\n",
b"ENDCHAR\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 14: Expected b'ENDCHAR', not b'00'",
)
def test_accept_glyph_with_zero_height(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR space\n",
b"ENCODING 32\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 0 0 3 4\n",
b"BITMAP\n",
b"ENDCHAR\n",
b"ENDFONT\n",
]
f = reader.read_bdf(input)
self.assertIn(32, f.codepoints())
g = f[32]
self.assertEqual(g.name, b"space")
self.assertEqual(g.codepoint, 32)
self.assertEqual(g.bbW, 0)
self.assertEqual(g.bbH, 0)
self.assertEqual(g.advance, 8)
def test_reject_glyph_with_corrupt_rows(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"00\n",
b"blah\n",
b"ENDCHAR\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 13: Expected hexadecimal digits, not b'blah'",
)
def test_warn_glyph_with_extra_row_data(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10 blah\n",
b"ENDCHAR\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertIn(
(13, "Bitmap row should not contain spaces, got b'10 blah'"),
warnings,
)
def test_reject_font_with_non_character_data(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR\n",
b"BLAH\n",
]
with self.assertRaises(reader.ParseError) as cm:
reader.read_bdf(input)
self.assertEqual(
str(cm.exception),
"Line 15: Expected STARTCHAR or ENDFONT, not b'BLAH'",
)
def test_warn_font_with_endchar_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR blah\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertIn((14, "ENDCHAR expects no value, got b'blah'"), warnings)
def test_warn_font_with_endfont_value(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 1\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR\n",
b"ENDFONT blah\n",
]
warnings: List[Tuple[int, str]] = []
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertIn((15, "ENDFONT expects no value, got b'blah'"), warnings)
def test_warn_font_with_wrong_char_count(self) -> None:
input = [
b"STARTFONT 2.1\n",
b"FONT Awesome Font\n",
b"SIZE 12 72 72\n",
b"FONTBOUNDINGBOX 9 24 -2 -6\n",
b"CHARS 2\n",
b"STARTCHAR j\n",
b"ENCODING 106\n",
b"SWIDTH 355 0\n",
b"DWIDTH 8 0\n",
b"BBX 1 2 3 4\n",
b"BITMAP\n",
b"01\n",
b"10\n",
b"ENDCHAR\n",
b"ENDFONT\n",
]
warnings: List[Tuple[int, str]] = []
reader.read_bdf(input, lambda n, m: warnings.append((n, m)))
self.assertIn((15, "Font should have 2 glyphs, found 1"), warnings)
bdflib-v2.1.0/bdflib/test/test_writer.py 0000664 0000000 0000000 00000023613 14753047770 0020273 0 ustar 00root root 0000000 0000000 import unittest
from io import BytesIO
from bdflib import model, writer
class TestBDFWriter(unittest.TestCase):
def setUp(self) -> None:
self.font = model.Font(b"TestFont", 12, 100, 100)
def test_basic_writing(self) -> None:
"""
Writing out a simple font should work.
"""
self.font.new_glyph_from_data(
b"TestGlyph", [0b10, 0b01], 0, 0, 2, 2, 3, 1
)
stream = BytesIO()
writer.write_bdf(self.font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 2 2 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 1\n"
"STARTCHAR TestGlyph\n"
"ENCODING 1\n"
"SWIDTH 176 0\n"
"DWIDTH 3 0\n"
"BBX 2 2 0 0\n"
"BITMAP\n"
"40\n"
"80\n"
"ENDCHAR\n"
"ENDFONT\n",
)
def test_empty_font(self) -> None:
"""
We should be able to write an empty font.
"""
stream = BytesIO()
writer.write_bdf(self.font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 0 0 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 0\n"
"ENDFONT\n",
)
def test_bounding_box_calculations(self) -> None:
"""
FONTBOUNDINGBOX should be calculated from individual glyphs.
"""
self.font.new_glyph_from_data(
b"TestGlyph1", [0b10, 0b01], 1, 3, 2, 2, 3, 1
)
self.font.new_glyph_from_data(
b"TestGlyph2", [0b10, 0b01], -5, -7, 2, 2, 1, 2
)
stream = BytesIO()
writer.write_bdf(self.font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 8 12 -5 -7\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 2\n"
"STARTCHAR TestGlyph1\n"
"ENCODING 1\n"
"SWIDTH 176 0\n"
"DWIDTH 3 0\n"
"BBX 2 2 1 3\n"
"BITMAP\n"
"40\n"
"80\n"
"ENDCHAR\n"
"STARTCHAR TestGlyph2\n"
"ENCODING 2\n"
"SWIDTH 58 0\n"
"DWIDTH 1 0\n"
"BBX 2 2 -5 -7\n"
"BITMAP\n"
"40\n"
"80\n"
"ENDCHAR\n"
"ENDFONT\n",
)
def test_property_quoting(self) -> None:
"""
Test that property values are quoted properly.
"""
self.font[b"AN_INTEGER"] = 42
self.font[b"A_STRING"] = b"42"
self.font[b"STRING_WITH_QUOTES"] = b'Neville "The Banker" Robinson'
stream = BytesIO()
writer.write_bdf(self.font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 0 0 0 0\n"
"STARTPROPERTIES 3\n"
"AN_INTEGER 42\n"
'A_STRING "42"\n'
'STRING_WITH_QUOTES "Neville ""The Banker"" Robinson"\n'
"ENDPROPERTIES\n"
"CHARS 0\n"
"ENDFONT\n",
)
def test_default_char_setting(self) -> None:
"""
If a default char is explicitly set, it should be used.
"""
self.font.new_glyph_from_data(
b"TestGlyph1", [0b10, 0b01], 0, 0, 2, 2, 3, 1
)
self.font.new_glyph_from_data(
b"TestGlyph2", [0b01, 0b10], 0, 0, 2, 2, 3, 0xFFFD
)
self.font[b"DEFAULT_CHAR"] = 0xFFFD
stream = BytesIO()
writer.write_bdf(self.font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 2 2 0 0\n"
"STARTPROPERTIES 1\n"
"DEFAULT_CHAR 65533\n"
"ENDPROPERTIES\n"
"CHARS 2\n"
"STARTCHAR TestGlyph1\n"
"ENCODING 1\n"
"SWIDTH 176 0\n"
"DWIDTH 3 0\n"
"BBX 2 2 0 0\n"
"BITMAP\n"
"40\n"
"80\n"
"ENDCHAR\n"
"STARTCHAR TestGlyph2\n"
"ENCODING 65533\n"
"SWIDTH 176 0\n"
"DWIDTH 3 0\n"
"BBX 2 2 0 0\n"
"BITMAP\n"
"80\n"
"40\n"
"ENDCHAR\n"
"ENDFONT\n",
)
def test_resolution_calculations(self) -> None:
"""
The pixel size should be correctly calculated from the point size.
"""
tests = [
(12, 72, 12),
(12, 100, 17),
(12.2, 100, 17),
(12, 144, 24),
]
for pointSz, res, pixelSz in tests:
font = model.Font(b"TestFont", int(pointSz), res, res)
stream = BytesIO()
writer.write_bdf(font, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE %(pointSz)g %(res)d %(res)d\n"
"FONTBOUNDINGBOX 0 0 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 0\n"
"ENDFONT\n"
% {
"pointSz": int(pointSz),
"res": res,
},
)
def test_glyph_data_case(self) -> None:
"""
gbdfed writes upper-case hex digits, so we should too.
"""
f = model.Font(b"TestFont", 12, 100, 100)
f.new_glyph_from_data(
b"TestGlyph",
[0xA, 0xB, 0xC, 0xD, 0xE, 0xF],
bbW=4,
bbH=6,
advance=5,
)
stream = BytesIO()
writer.write_bdf(f, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 4 6 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 1\n"
"STARTCHAR TestGlyph\n"
"ENCODING -1\n"
"SWIDTH 294 0\n"
"DWIDTH 5 0\n"
"BBX 4 6 0 0\n"
"BITMAP\n"
"F0\n"
"E0\n"
"D0\n"
"C0\n"
"B0\n"
"A0\n"
"ENDCHAR\n"
"ENDFONT\n",
)
def test_glyphs_should_be_zero_padded(self) -> None:
"""
Each row of the bitmap should be zero-padded to the same length.
"""
f = model.Font(b"TestFont", 12, 100, 100)
# When a glyph is multiple hex-digits wide and a row has no bits set in
# the left-most columns, a zero should be placed there.
f.new_glyph_from_data(
b"TestGlyph", [0b100000000000, 0b1], bbW=12, bbH=2
)
stream = BytesIO()
writer.write_bdf(f, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 12 2 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 1\n"
"STARTCHAR TestGlyph\n"
"ENCODING -1\n"
"SWIDTH 0 0\n"
"DWIDTH 0 0\n"
"BBX 12 2 0 0\n"
"BITMAP\n"
"0010\n"
"8000\n"
"ENDCHAR\n"
"ENDFONT\n",
)
# When a glyph's width doesn't take up a even number of hex digits, the
# row width should be rounded up to the nearest even number of
# digits, not down.
f.new_glyph_from_data(
b"TestGlyph", [0b10000000000, 0b00000001000], bbW=11, bbH=2
)
stream = BytesIO()
writer.write_bdf(f, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 12 2 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 2\n"
"STARTCHAR TestGlyph\n"
"ENCODING -1\n"
"SWIDTH 0 0\n"
"DWIDTH 0 0\n"
"BBX 12 2 0 0\n"
"BITMAP\n"
"0010\n"
"8000\n"
"ENDCHAR\n"
"STARTCHAR TestGlyph\n"
"ENCODING -1\n"
"SWIDTH 0 0\n"
"DWIDTH 0 0\n"
"BBX 11 2 0 0\n"
"BITMAP\n"
"0100\n"
"8000\n"
"ENDCHAR\n"
"ENDFONT\n",
)
def test_no_padding_for_eight_pixel_wide_glyphs(self) -> None:
"""
A glyph that's eight pixels wide should require no additional padding.
"""
f = model.Font(b"TestFont", 12, 100, 100)
f.new_glyph_from_data(b"TestGlyph", [0b10000000, 0b1], bbW=8, bbH=2)
stream = BytesIO()
writer.write_bdf(f, stream)
self.assertEqual(
stream.getvalue().decode("UTF-8"),
"STARTFONT 2.1\n"
"FONT TestFont\n"
"SIZE 12 100 100\n"
"FONTBOUNDINGBOX 8 2 0 0\n"
"STARTPROPERTIES 0\n"
"ENDPROPERTIES\n"
"CHARS 1\n"
"STARTCHAR TestGlyph\n"
"ENCODING -1\n"
"SWIDTH 0 0\n"
"DWIDTH 0 0\n"
"BBX 8 2 0 0\n"
"BITMAP\n"
"01\n"
"80\n"
"ENDCHAR\n"
"ENDFONT\n",
)
bdflib-v2.1.0/bdflib/test/test_xlfd.py 0000664 0000000 0000000 00000044551 14753047770 0017720 0 ustar 00root root 0000000 0000000 import unittest
from bdflib import model, xlfd
FONTNAME = b"-screwtapello-testfont-medium-r-normal--5-50-75-75-m-45-iso10646-1"
class TestExceptions(unittest.TestCase):
def test_contradiction(self) -> None:
e = xlfd.Contradiction(b"SOMEFIELD", b"propvalue", b"xlfdvalue")
self.assertEqual(
str(e),
(
"b'SOMEFIELD' value b'propvalue' conflicts "
"with XLFD value b'xlfdvalue'"
),
)
def test_expected_integer(self) -> None:
e = xlfd.ExpectedInteger(b"SOMEFIELD", b"somevalue")
self.assertEqual(
str(e), "b'SOMEFIELD' value should be integer, not b'somevalue'"
)
def test_expected_bytestring(self) -> None:
e = xlfd.ExpectedBytestring(b"SOMEFIELD", 42)
self.assertEqual(str(e), "b'SOMEFIELD' value should be string, not 42")
def test_expected_enumerated_value(self) -> None:
e = xlfd.ExpectedEnumeratedValue(
b"SOMEFIELD",
b"Coconut",
set((b"Strawberry", b"Chocolate", b"Vanilla")),
)
self.assertEqual(
str(e),
(
"b'SOMEFIELD' value should be one of "
+ "[b'Chocolate', b'Strawberry', b'Vanilla'], not b'Coconut'"
),
)
class TestFix(unittest.TestCase):
def test_set_xlfd_properties_from_bdf_fields(self) -> None:
"""
xlfd.fix() calculates all the properties that can be calculated.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f.new_glyph_from_data(
name=b"j",
data=[
0b10,
0b01,
0b01,
0b01,
0b00,
0b01,
],
bbX=0,
bbY=-1,
bbW=2,
bbH=6,
advance=3,
codepoint=ord("j"),
)
f.new_glyph_from_data(
name=b"m",
data=[
0b1001001,
0b1001001,
0b0110110,
],
bbX=0,
bbY=0,
bbW=7,
bbH=3,
advance=8,
codepoint=ord("m"),
)
# Fix/generate as much information as possible.
xlfd.fix(f)
self.assertEqual(f[xlfd.WEIGHT_NAME], b"Medium")
self.assertEqual(f[xlfd.SLANT], xlfd.SLANT_ROMAN)
self.assertEqual(f[xlfd.SETWIDTH_NAME], b"Normal")
self.assertEqual(f[xlfd.ADD_STYLE_NAME], b"")
self.assertEqual(f[xlfd.PIXEL_SIZE], 6)
self.assertEqual(f[xlfd.POINT_SIZE], 50)
self.assertEqual(f[xlfd.RESOLUTION_X], 75)
self.assertEqual(f[xlfd.RESOLUTION_Y], 75)
self.assertEqual(f[xlfd.SPACING], xlfd.SPACING_PROPORTIONAL)
self.assertEqual(f[xlfd.AVERAGE_WIDTH], 55)
self.assertEqual(f[xlfd.FONT_ASCENT], 5)
self.assertEqual(f[xlfd.FONT_DESCENT], 1)
self.assertEqual(f[xlfd.DEFAULT_CHAR], ord("m"))
def test_detect_charcell_spacing(self) -> None:
"""
xlfd.fix() detects when a font uses charcell spacing..
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
# Add glyphs that both have the same advance width,
# and don't draw outside their cell.
f.new_glyph_from_data(
name=b"j",
data=[
0b01110,
0b10001,
0b00001,
0b00111,
0b00000,
0b00001,
],
bbX=0,
bbY=-1,
bbW=5,
bbH=6,
advance=6,
codepoint=ord("j"),
)
f.new_glyph_from_data(
name=b"m",
data=[
0b10101,
0b10101,
0b01010,
],
bbX=0,
bbY=0,
bbW=5,
bbH=3,
advance=6,
codepoint=ord("m"),
)
# Fix/generate as much information as possible.
xlfd.fix(f)
self.assertEqual(f[xlfd.SPACING], xlfd.SPACING_CHARCELL)
def test_detect_monospace_spacing(self) -> None:
"""
xlfd.fix() detects when a font uses monospace spacing..
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
# Add glyphs that both have the same advance width,
# but may draw outside their cell.
f.new_glyph_from_data(
name=b"j",
data=[
0b01110,
0b10001,
0b00001,
0b00111,
0b00000,
0b00001,
],
bbX=0,
bbY=-1,
bbW=5,
bbH=6,
advance=6,
codepoint=ord("j"),
)
f.new_glyph_from_data(
name=b"m",
data=[
0b010101,
0b010101,
0b101010,
],
bbX=-1,
bbY=0,
bbW=6,
bbH=3,
advance=6,
codepoint=ord("m"),
)
# Fix/generate as much information as possible.
xlfd.fix(f)
self.assertEqual(f[xlfd.SPACING], xlfd.SPACING_MONOSPACED)
def test_respect_existing_properties(self) -> None:
"""
xlfd.fix() does not overwrite previously-set properties.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f.new_glyph_from_data(
name=b"j",
data=[
0b10,
0b01,
0b01,
0b01,
0b00,
0b01,
],
bbX=0,
bbY=-1,
bbW=2,
bbH=6,
advance=3,
codepoint=ord("j"),
)
f.new_glyph_from_data(
name=b"m",
data=[
0b1001001,
0b1001001,
0b0110110,
],
bbX=0,
bbY=0,
bbW=7,
bbH=3,
advance=8,
codepoint=ord("m"),
)
f[xlfd.WEIGHT_NAME] = b"Thin"
f[xlfd.SLANT] = xlfd.SLANT_REVERSE_OBLIQUE
f[xlfd.SETWIDTH_NAME] = b"Ultracondensed"
f[xlfd.ADD_STYLE_NAME] = b"Loopy"
f[xlfd.PIXEL_SIZE] = 10
f[xlfd.POINT_SIZE] = 100
f[xlfd.RESOLUTION_X] = 96
f[xlfd.RESOLUTION_Y] = 12
f[xlfd.SPACING] = xlfd.SPACING_CHARCELL
f[xlfd.AVERAGE_WIDTH] = 993
f[xlfd.FONT_ASCENT] = 123
f[xlfd.FONT_DESCENT] = 456
f[xlfd.DEFAULT_CHAR] = ord("j")
# Fix/generate as much information as possible.
xlfd.fix(f)
self.assertEqual(f[xlfd.WEIGHT_NAME], b"Thin")
self.assertEqual(f[xlfd.SLANT], xlfd.SLANT_REVERSE_OBLIQUE)
self.assertEqual(f[xlfd.SETWIDTH_NAME], b"Ultracondensed")
self.assertEqual(f[xlfd.ADD_STYLE_NAME], b"Loopy")
self.assertEqual(f[xlfd.PIXEL_SIZE], 10)
self.assertEqual(f[xlfd.POINT_SIZE], 100)
self.assertEqual(f[xlfd.RESOLUTION_X], 96)
self.assertEqual(f[xlfd.RESOLUTION_Y], 12)
self.assertEqual(f[xlfd.SPACING], xlfd.SPACING_CHARCELL)
self.assertEqual(f[xlfd.AVERAGE_WIDTH], 993)
self.assertEqual(f[xlfd.FONT_ASCENT], 123)
self.assertEqual(f[xlfd.FONT_DESCENT], 456)
self.assertEqual(f[xlfd.DEFAULT_CHAR], ord("j"))
class TestValidate(unittest.TestCase):
"""
Validation rules from Chapter 8 of the XLFD specification.
"""
def test_reject_if_name_not_xlfd(self) -> None:
"""
xlfd.validate() rejects a font whose name is not an XLFD name.
"""
f = model.Font(name=b"invalid xlfd", ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertIn(xlfd.NotAnXlfd(b"invalid xlfd"), errors)
def test_reject_if_name_includes_invalid_characters(self) -> None:
"""
xlfd.validate() rejects a font whose name includes invalid characters.
"""
for c in (b"-", b"?", b"*", b",", b'"'):
invalid_font_name = FONTNAME + c
f = model.Font(name=invalid_font_name, ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertIn(xlfd.NotAnXlfd(invalid_font_name), errors)
def test_accept_valid_name(self) -> None:
"""
xlfd.validate() does not complain about a valid XLFD name.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertNotIn(xlfd.NotAnXlfd(FONTNAME), errors)
def test_reject_if_missing_property_values(self) -> None:
"""
xlfd.validate() requires all FontName properties to be present.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertIn(xlfd.MissingProperty(xlfd.FOUNDRY), errors)
self.assertIn(xlfd.MissingProperty(xlfd.FAMILY_NAME), errors)
self.assertIn(xlfd.MissingProperty(xlfd.WEIGHT_NAME), errors)
self.assertIn(xlfd.MissingProperty(xlfd.SLANT), errors)
self.assertIn(xlfd.MissingProperty(xlfd.SETWIDTH_NAME), errors)
self.assertIn(xlfd.MissingProperty(xlfd.ADD_STYLE_NAME), errors)
self.assertIn(xlfd.MissingProperty(xlfd.PIXEL_SIZE), errors)
self.assertIn(xlfd.MissingProperty(xlfd.POINT_SIZE), errors)
self.assertIn(xlfd.MissingProperty(xlfd.RESOLUTION_X), errors)
self.assertIn(xlfd.MissingProperty(xlfd.RESOLUTION_Y), errors)
self.assertIn(xlfd.MissingProperty(xlfd.SPACING), errors)
self.assertIn(xlfd.MissingProperty(xlfd.AVERAGE_WIDTH), errors)
self.assertIn(xlfd.MissingProperty(xlfd.CHARSET_REGISTRY), errors)
self.assertIn(xlfd.MissingProperty(xlfd.CHARSET_ENCODING), errors)
def test_reject_if_xlfd_property_mismatch(self) -> None:
"""
xlfd.validate() requires XLFD field values match the font properties.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f[xlfd.FOUNDRY] = b"a"
f[xlfd.FAMILY_NAME] = b"b"
f[xlfd.WEIGHT_NAME] = b"Thin"
f[xlfd.SLANT] = xlfd.SLANT_REVERSE_OBLIQUE
f[xlfd.SETWIDTH_NAME] = b"Condensed"
f[xlfd.ADD_STYLE_NAME] = b"Loopy"
f[xlfd.PIXEL_SIZE] = 10
f[xlfd.POINT_SIZE] = 100
f[xlfd.RESOLUTION_X] = 96
f[xlfd.RESOLUTION_Y] = 12
f[xlfd.SPACING] = xlfd.SPACING_CHARCELL
f[xlfd.AVERAGE_WIDTH] = 993
f[xlfd.CHARSET_REGISTRY] = b"iso8859"
f[xlfd.CHARSET_ENCODING] = b"15"
errors = xlfd.validate(f)
self.assertIn(
xlfd.Contradiction(xlfd.FOUNDRY, b"a", b"screwtapello"), errors
)
self.assertIn(
xlfd.Contradiction(xlfd.FAMILY_NAME, b"b", b"testfont"), errors
)
self.assertIn(
xlfd.Contradiction(xlfd.WEIGHT_NAME, b"Thin", b"medium"), errors
)
self.assertIn(
xlfd.Contradiction(
xlfd.SLANT, xlfd.SLANT_REVERSE_OBLIQUE, xlfd.SLANT_ROMAN
),
errors,
)
self.assertIn(
xlfd.Contradiction(xlfd.SETWIDTH_NAME, b"Condensed", b"normal"),
errors,
)
self.assertIn(
xlfd.Contradiction(xlfd.ADD_STYLE_NAME, b"Loopy", b""), errors
)
self.assertIn(xlfd.Contradiction(xlfd.PIXEL_SIZE, 10, 5), errors)
self.assertIn(xlfd.Contradiction(xlfd.POINT_SIZE, 100, 50), errors)
self.assertIn(xlfd.Contradiction(xlfd.RESOLUTION_X, 96, 75), errors)
self.assertIn(xlfd.Contradiction(xlfd.RESOLUTION_Y, 12, 75), errors)
self.assertIn(
xlfd.Contradiction(
xlfd.SPACING, xlfd.SPACING_CHARCELL, xlfd.SPACING_MONOSPACED
),
errors,
)
self.assertIn(xlfd.Contradiction(xlfd.AVERAGE_WIDTH, 993, 45), errors)
self.assertIn(
xlfd.Contradiction(xlfd.CHARSET_REGISTRY, b"iso8859", b"iso10646"),
errors,
)
self.assertIn(
xlfd.Contradiction(xlfd.CHARSET_ENCODING, b"15", b"1"), errors
)
def test_reject_if_invalid_property_values(self) -> None:
"""
xlfd.validate() requires all properties have the expected types.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f.new_glyph_from_data(
name=b"j",
data=[
0b10,
0b01,
0b01,
0b01,
0b00,
0b01,
],
bbX=0,
bbY=-1,
bbW=2,
bbH=6,
advance=3,
codepoint=ord("j"),
)
f[xlfd.FOUNDRY] = 123
f[xlfd.FAMILY_NAME] = 456
f[xlfd.WEIGHT_NAME] = 789
f[xlfd.SLANT] = b"invalid"
f[xlfd.SETWIDTH_NAME] = 101112
f[xlfd.ADD_STYLE_NAME] = 131415
f[xlfd.PIXEL_SIZE] = b"pixel size"
f[xlfd.POINT_SIZE] = b"point size"
f[xlfd.RESOLUTION_X] = b"resolution x"
f[xlfd.RESOLUTION_Y] = b"resolution y"
f[xlfd.SPACING] = b"invalid"
f[xlfd.AVERAGE_WIDTH] = b"average width"
f[xlfd.CHARSET_REGISTRY] = 161718
f[xlfd.CHARSET_ENCODING] = 192021
f[xlfd.FONT_ASCENT] = b"invalid"
f[xlfd.FONT_DESCENT] = b"invalid"
f[xlfd.DEFAULT_CHAR] = ord("m")
errors = xlfd.validate(f)
self.assertIn(xlfd.ExpectedBytestring(xlfd.FOUNDRY, 123), errors)
self.assertIn(xlfd.ExpectedBytestring(xlfd.FAMILY_NAME, 456), errors)
self.assertIn(xlfd.ExpectedBytestring(xlfd.WEIGHT_NAME, 789), errors)
self.assertIn(
xlfd.ExpectedEnumeratedValue(
xlfd.SLANT, b"invalid", xlfd.SLANT_VALUES
),
errors,
)
self.assertIn(
xlfd.ExpectedBytestring(xlfd.SETWIDTH_NAME, 101112), errors
)
self.assertIn(
xlfd.ExpectedBytestring(xlfd.ADD_STYLE_NAME, 131415), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.PIXEL_SIZE, b"pixel size"), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.POINT_SIZE, b"point size"), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.RESOLUTION_X, b"resolution x"), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.RESOLUTION_Y, b"resolution y"), errors
)
self.assertIn(
xlfd.ExpectedEnumeratedValue(
xlfd.SPACING, b"invalid", xlfd.SPACING_VALUES
),
errors,
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.AVERAGE_WIDTH, b"average width"), errors
)
self.assertIn(
xlfd.ExpectedBytestring(xlfd.CHARSET_REGISTRY, 161718), errors
)
self.assertIn(
xlfd.ExpectedBytestring(xlfd.CHARSET_ENCODING, 192021), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.FONT_ASCENT, b"invalid"), errors
)
self.assertIn(
xlfd.ExpectedInteger(xlfd.FONT_DESCENT, b"invalid"), errors
)
self.assertIn(
xlfd.ExpectedEnumeratedValue(
xlfd.DEFAULT_CHAR, ord("m"), {ord("j")}
),
errors,
)
# Check that enumerated properties with the wrong type,
# not just an invalid value,
# are also detected.
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f[xlfd.SLANT] = 123
f[xlfd.SPACING] = 456
f[xlfd.DEFAULT_CHAR] = b"invalid"
errors = xlfd.validate(f)
self.assertIn(
xlfd.ExpectedEnumeratedValue(xlfd.SLANT, 123, xlfd.SLANT_VALUES),
errors,
)
self.assertIn(
xlfd.ExpectedEnumeratedValue(
xlfd.SPACING, 456, xlfd.SPACING_VALUES
),
errors,
)
self.assertIn(
xlfd.ExpectedEnumeratedValue(xlfd.DEFAULT_CHAR, b"invalid", set()),
errors,
)
def test_reject_if_invalid_enumerated_xlfd_value(self) -> None:
"""
xlfd.validate() rejects an invalid enumerated value in the XLFD.
"""
broken_fontname = FONTNAME.replace(b"-m-", b"-x-")
f = model.Font(name=broken_fontname, ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertIn(
xlfd.ExpectedEnumeratedValue(
xlfd.SPACING, b"x", xlfd.SPACING_VALUES
),
errors,
)
def test_reject_if_invalid_integer_xlfd_value(self) -> None:
"""
xlfd.validate() rejects an invalid enumerated value in the XLFD.
"""
broken_fontname = FONTNAME.replace(b"-75-", b"-x-")
f = model.Font(name=broken_fontname, ptSize=5, xdpi=75, ydpi=75)
errors = xlfd.validate(f)
self.assertIn(xlfd.ExpectedInteger(xlfd.RESOLUTION_X, b"x"), errors)
def test_accept_clean_font(self) -> None:
"""
xlfd.validate() accepts a font that passes all its tests.
"""
f = model.Font(name=FONTNAME, ptSize=5, xdpi=75, ydpi=75)
f[xlfd.FOUNDRY] = b"screwtapello"
f[xlfd.FAMILY_NAME] = b"testfont"
f[xlfd.WEIGHT_NAME] = b"medium"
f[xlfd.SLANT] = xlfd.SLANT_ROMAN
f[xlfd.SETWIDTH_NAME] = b"normal"
f[xlfd.ADD_STYLE_NAME] = b""
f[xlfd.PIXEL_SIZE] = 5
f[xlfd.POINT_SIZE] = 50
f[xlfd.RESOLUTION_X] = 75
f[xlfd.RESOLUTION_Y] = 75
f[xlfd.SPACING] = xlfd.SPACING_MONOSPACED
f[xlfd.AVERAGE_WIDTH] = 45
f[xlfd.CHARSET_REGISTRY] = b"iso10646"
f[xlfd.CHARSET_ENCODING] = b"1"
self.assertEqual(xlfd.validate(f), [])
def test_accept_case_insensitive_values(self) -> None:
"""
xlfd.validate() accepts values with different case than expected.
"""
f = model.Font(name=FONTNAME.upper(), ptSize=5, xdpi=75, ydpi=75)
f[xlfd.FOUNDRY] = b"Screwtapello"
f[xlfd.FAMILY_NAME] = b"TestFont"
f[xlfd.WEIGHT_NAME] = b"Medium"
f[xlfd.SLANT] = b"R"
f[xlfd.SETWIDTH_NAME] = b"Normal"
f[xlfd.ADD_STYLE_NAME] = b""
f[xlfd.PIXEL_SIZE] = 5
f[xlfd.POINT_SIZE] = 50
f[xlfd.RESOLUTION_X] = 75
f[xlfd.RESOLUTION_Y] = 75
f[xlfd.SPACING] = b"M"
f[xlfd.AVERAGE_WIDTH] = 45
f[xlfd.CHARSET_REGISTRY] = b"ISO10646"
f[xlfd.CHARSET_ENCODING] = b"1"
self.assertEqual(xlfd.validate(f), [])
bdflib-v2.1.0/bdflib/tools.py 0000664 0000000 0000000 00000017635 14753047770 0016110 0 ustar 00root root 0000000 0000000 """
Command-line tools for common bdflib operations.
"""
import argparse
from typing import Counter, Callable, TypeVar
import unicodedata
import bdflib
from bdflib import reader, writer, effects, glyph_combining, xlfd
T = TypeVar("T")
def add_standard_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-V",
"--version",
action="version",
version=bdflib.__version__,
)
# I'd love to use argparse.FileType, but https://bugs.python.org/issue14156
parser.add_argument(
"input",
metavar="INPUT",
help="Read a BDF font from file INPUT.",
)
parser.add_argument(
"output",
metavar="OUTPUT",
help="Write the resulting BDF font to file OUTPUT.",
)
def embolden() -> None:
parser = argparse.ArgumentParser(
description="Add a faux-bold effect to a font.",
)
add_standard_arguments(parser)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--maintain-spacing",
dest="maintain_spacing",
action="store_true",
default="True",
help="Expand each character's spacing to account for emboldening "
"(default)",
)
group.add_argument(
"--ignore-spacing",
dest="maintain_spacing",
action="store_false",
help="Let bold characters use their original spacing",
)
args = parser.parse_args()
with open(args.input, "rb") as input:
with open(args.output, "wb") as output:
font = reader.read_bdf(input)
bold = effects.embolden(font, args.maintain_spacing)
writer.write_bdf(bold, output)
def expand() -> None:
parser = argparse.ArgumentParser(
description="Increase the resolution of a font.",
)
add_standard_arguments(parser)
parser.add_argument(
"--x-factor",
metavar="X",
dest="x_factor",
type=int,
default=1,
help="Expand each glyph horizontally by X times",
)
parser.add_argument(
"--y-factor",
metavar="Y",
dest="y_factor",
type=int,
default=1,
help="Expand each glyph vertically by Y times",
)
args = parser.parse_args()
with open(args.input, "rb") as input:
with open(args.output, "wb") as output:
font = reader.read_bdf(input)
expanded = effects.expand(font, args.x_factor, args.y_factor)
writer.write_bdf(expanded, output)
def show_counter(
counter: Counter[T], kind: str, formatter: Callable[[T], str] = repr
) -> None:
"""
Print the result of the tally.
formatter should be a callable that takes an item and returns a pretty
string. If not supplied, repr() is used.
"""
data = [(value, key) for key, value in counter.items()]
data.sort()
if len(data) == 0:
return
print("count", kind)
for count, item in data:
print("%5d %s" % (count, formatter(item)))
def fill() -> None:
parser = argparse.ArgumentParser(
description="Generate pre-composed glyphs from available components",
)
add_standard_arguments(parser)
args = parser.parse_args()
with open(args.input, "rb") as input:
with open(args.output, "wb") as output:
print("Reading font...")
font = reader.read_bdf(input)
print("Building list of decompositions...")
decompositions = glyph_combining.build_unicode_decompositions()
print("Generating combined characters...")
filler = glyph_combining.FontFiller(font, decompositions)
filler.add_decomposable_glyphs_to_font()
print("Writing out result...")
writer.write_bdf(font, output)
# Show the inventory of things this font is missing.
print()
print("Unknown combining classes")
show_counter(filler.unknown_classes, "class")
print()
print("Missing combinable characters")
show_counter(
filler.missing_chars,
"char",
lambda char: "%r (%s)" % (char, unicodedata.name(char)),
)
def merge() -> None:
parser = argparse.ArgumentParser(
description="""
For each code-point that has a glyph in BASE or CUSTOM,
the resulting font will use the glyph from CUSTOM if present,
otherwise falling back to the glyph in BASE.
""",
)
parser.add_argument(
"-V",
"--version",
action="version",
version=bdflib.__version__,
)
# I'd love to use argparse.FileType, but https://bugs.python.org/issue14156
parser.add_argument(
"base",
metavar="BASE",
help="Path to a BDF font file, used for fallback glyphs.",
)
parser.add_argument(
"custom",
metavar="CUSTOM",
help="Path to a BDF font file, whose glyphs override those in BASE.",
)
parser.add_argument(
"output",
metavar="OUTPUT",
help="The resulting font will be written to the file OUTPUT.",
)
args = parser.parse_args()
with open(args.base, "rb") as base:
with open(args.custom, "rb") as custom:
with open(args.output, "wb") as output:
base_font = reader.read_bdf(base)
custom_font = reader.read_bdf(custom)
merged = effects.merge(base_font, custom_font)
writer.write_bdf(merged, output)
def passthrough() -> None:
parser = argparse.ArgumentParser(
description="Parse and re-serialise a BDF font.",
)
add_standard_arguments(parser)
args = parser.parse_args()
with open(args.input, "rb") as input:
with open(args.output, "wb") as output:
font = reader.read_bdf(input)
writer.write_bdf(font, output)
def validate() -> int:
parser = argparse.ArgumentParser(
description=("Check a font conforms to the BDF specification"),
)
parser.add_argument(
"-V",
"--version",
action="version",
version=bdflib.__version__,
)
# I'd love to use argparse.FileType, but https://bugs.python.org/issue14156
parser.add_argument(
"fonts",
metavar="FONT",
nargs="+",
help="Read a BDF font from file FONT.",
)
args = parser.parse_args()
exit_code = 0
for filename in args.fonts:
def report_warning(lineno: int, message: str) -> None:
print(f"{filename}:{lineno}: warning: {message}")
try:
with open(filename, "rb") as input:
reader.read_bdf(input, report_warning)
except reader.ParseError as e:
exit_code = 1
print(f"{filename}:{e.lineno}: error: {e.message}")
return exit_code
def xlfd_validate() -> int:
parser = argparse.ArgumentParser(
description=(
"Check a font against X Logical Font Descriptor conventions"
),
)
parser.add_argument(
"-V",
"--version",
action="version",
version=bdflib.__version__,
)
# I'd love to use argparse.FileType, but https://bugs.python.org/issue14156
parser.add_argument(
"input",
metavar="INPUT",
help="Read a BDF font from file INPUT.",
)
args = parser.parse_args()
with open(args.input, "rb") as input:
font = reader.read_bdf(input)
errors = xlfd.validate(font)
for each in errors:
print(type(each).__name__, ":", each)
if errors:
return 1
return 0
def xlfd_fix() -> None:
parser = argparse.ArgumentParser(
description="Add missing X Logical Font Descriptor properties",
)
add_standard_arguments(parser)
args = parser.parse_args()
with open(args.input, "rb") as input:
with open(args.output, "wb") as output:
font = reader.read_bdf(input)
xlfd.fix(font)
writer.write_bdf(font, output)
bdflib-v2.1.0/bdflib/writer.py 0000664 0000000 0000000 00000010052 14753047770 0016246 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
import io
import math
from bdflib import model
def _quote_property_value(val: model.PropertyValue) -> bytes:
if isinstance(val, int):
return b"%d" % val
else:
return b'"' + bytes(val).replace(b'"', b'""') + b'"'
def write_bdf(font: model.Font, stream: io.IOBase) -> None:
"""
Write a BDF-format font to the given stream.
:param font: The font to write to the given stream.
:param stream: The stream that will receive the font.
``stream`` must be an object with at ``.write()`` method that takes a
:class:`bytes`. If you want to write to an actual file, make sure you
use the 'b' flag::
bdflib.writer.write_bdf(font, open(path, 'wb'))
"""
# The font bounding box is the union of glyph bounding boxes.
font_bbX = 0
font_bbY = 0
font_bbW = 0
font_bbH = 0
for g in font.glyphs:
new_bbX = min(font_bbX, g.bbX)
new_bbY = min(font_bbY, g.bbY)
new_bbW = max(font_bbX + font_bbW, g.bbX + g.bbW) - new_bbX
new_bbH = max(font_bbY + font_bbH, g.bbY + g.bbH) - new_bbY
(font_bbX, font_bbY, font_bbW, font_bbH) = (
new_bbX,
new_bbY,
new_bbW,
new_bbH,
)
font_pixel_size = math.ceil(font.ydpi * font.ptSize / 72.0)
# Write the basic header.
stream.write(b"STARTFONT 2.1\n")
stream.write(b"FONT ")
stream.write(font.name)
stream.write(b"\n")
stream.write(b"SIZE %g %d %d\n" % (font.ptSize, font.xdpi, font.ydpi))
stream.write(
b"FONTBOUNDINGBOX %d %d %d %d\n"
% (font_bbW, font_bbH, font_bbX, font_bbY)
)
# Write the properties
stream.write(b"STARTPROPERTIES %d\n" % (len(font.properties),))
keys = sorted(font.properties.keys())
for key in keys:
stream.write(key)
stream.write(b" ")
stream.write(_quote_property_value(font.properties[key]))
stream.write(b"\n")
stream.write(b"ENDPROPERTIES\n")
# Write out the glyphs
stream.write(b"CHARS %d\n" % (len(font.glyphs),))
for glyph in font.glyphs:
scalable_width = int(1000.0 * glyph.advance / font_pixel_size)
stream.write(b"STARTCHAR ")
stream.write(glyph.name)
stream.write(b"\n")
stream.write(b"ENCODING %d\n" % (glyph.codepoint,))
stream.write(b"SWIDTH %d 0\n" % (scalable_width,))
stream.write(b"DWIDTH %d 0\n" % (glyph.advance,))
stream.write(
b"BBX %d %d %d %d\n" % (glyph.bbW, glyph.bbH, glyph.bbX, glyph.bbY)
)
stream.write(b"BITMAP\n")
# How many bytes do we need to represent the bits in each row?
rowWidth, extraBits = divmod(glyph.bbW, 8)
# How many bits of padding do we need to round up to a full byte?
if extraBits > 0:
rowWidth += 1
paddingBits = 8 - extraBits
else:
paddingBits = 0
# glyph.data goes bottom-to-top
# like any proper coordinate system does,
# but rows wants to be top-to-bottom
# like any proper stream-output.
for row in reversed(glyph.data):
# rowWidth is the number of bytes,
# but Python wants the number of nybbles,
# so multiply by 2.
stream.write(b"%0*X\n" % (rowWidth * 2, row << paddingBits))
stream.write(b"ENDCHAR\n")
stream.write(b"ENDFONT\n")
bdflib-v2.1.0/bdflib/xlfd.py 0000664 0000000 0000000 00000051734 14753047770 0015703 0 ustar 00root root 0000000 0000000 # bdflib, a library for working with BDF font files
# Copyright (C) 2009-2022, Timothy Allen
#
# 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 .
"""
Check fonts against the X Logical Font Descriptor conventions.
Fonts in the BDF format can be used for all kinds of things,
but commonly they are used with the traditional X11 font APIs,
built around X Logical Font Descriptors,
which require certain custom properties be set.
To check a BDF font against the XLFD conventions,
use :func:`.validate()`,
which returns a (hopefully empty) list of problems,
represented as subclasses of :class:`.ValidationError`.
If the font is missing properties that can be automatically calculated,
:func:`fix()` will update the font as required.
For more information about these issues,
see the official `X Logical Font Description Conventions`_ specification.
.. _X Logical Font Description Conventions:
https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/
XLFD/xlfd.html#fontname_field_definitions
Helpful constants
-----------------
Names for XLFD properties:
.. py:data:: FOUNDRY
The organisation responsible for making the font,
a namespace for :data:`FAMILY_NAME`
.. py:data:: FAMILY_NAME
The human-readable name of the font,
like "Times New" or "Helvetica"
.. py:data:: WEIGHT_NAME
The human-readable name of the font's weight,
like "Bold" or "Thin"
.. py:data:: SLANT
A code describing the slant style of the font,
one of the values in :data:`SLANT_VALUES`
.. py:data:: SETWIDTH_NAME
The human-reaadable name of the font's width,
like "Expanded" or "Ultracondensed"
.. py:data:: ADD_STYLE_NAME
A human-readable name that further distinguishes this font
from other similar fonts; an "additional style" if you will,
like "Sans Serif" or "Outline"
.. py:data:: PIXEL_SIZE
The vertical space required for a line of type,
in pixels,
usually (but not always)
the sum of :data:`FONT_ASCENT` and :data:`FONT_DESCENT`
.. py:data:: POINT_SIZE
The vertical space required for a line of type,
in deci-points
.. py:data:: RESOLUTION_X
The horizontal output resolution this font is intended for,
in dots-per-inch
.. py:data:: RESOLUTION_Y
The horizontal output resolution this font is intended for,
in dots-per-inch
.. py:data:: SPACING
A code describing the spacing of this font,
one of the values in :data:`SPACING_VALUES` below
.. py:data:: AVERAGE_WIDTH
The average width of all the characters in this font,
in deci-pixels.
.. py:data:: CHARSET_REGISTRY
The organisation responsible for defining
the character set encoding used by this font,
a namespace for :data:`CHARSET_ENCODING`
.. py:data:: CHARSET_ENCODING
The identifier for the character set encoding used by this font
.. py:data:: FONT_ASCENT
The maxium height above the baseline
that any glyph in this font touches,
in pixels
.. py:data:: FONT_DESCENT
The maxium depth below the baseline
that any glyph in this font touches,
in pixels
.. py:data:: DEFAULT_CHAR
If the software using this font wants to draw a glyph
that the font does not contain,
the glyph with this encoding will be drawn instead
Values for the :data:`SLANT` property:
.. py:data:: SLANT_ROMAN
This font is drawn with upright strokes
.. py:data:: SLANT_ITALIC
This font is drawn leaning forward,
often with curves or flourishes
.. py:data:: SLANT_OBLIQUE
This font is the Roman variant,
tilted forward
.. py:data:: SLANT_REVERSE_ITALIC
This font is drawn leaning backward,
often with curves or flourishes
.. py:data:: SLANT_REVERSE_OBLIQUE
This font is the Roman variant,
tilted backward
.. py:data:: SLANT_OTHER
This font has a tilt that's not any of the above
.. py:data:: SLANT_VALUES
The :class:`set` of valid :data:`SLANT` values:
Values for the :data:`SPACING` property:
.. py:data:: SPACING_PROPORTIONAL
Each glyph in this font takes space
proportional to its natural width,
so a character like "i" is narrow
while "m" is wide
.. py:data:: SPACING_MONOSPACED
Each glyph in this font takes exactly the same space,
regardless of its natural width
.. py:data:: SPACING_CHARCELL
Like :data:`SPACING_MONOSPACED`,
but in addition,
no part of any glyph sticks out of the space allocated to it
.. py:data:: SPACING_VALUES
The :class:`set` of valid :data:`SPACING` values:
Classes and functions
---------------------
"""
from math import inf, ceil
import typing
from bdflib import model
FOUNDRY = b"FOUNDRY"
FAMILY_NAME = b"FAMILY_NAME"
WEIGHT_NAME = b"WEIGHT_NAME"
SLANT = b"SLANT"
SETWIDTH_NAME = b"SETWIDTH_NAME"
ADD_STYLE_NAME = b"ADD_STYLE_NAME"
PIXEL_SIZE = b"PIXEL_SIZE"
POINT_SIZE = b"POINT_SIZE"
RESOLUTION_X = b"RESOLUTION_X"
RESOLUTION_Y = b"RESOLUTION_Y"
SPACING = b"SPACING"
AVERAGE_WIDTH = b"AVERAGE_WIDTH"
CHARSET_REGISTRY = b"CHARSET_REGISTRY"
CHARSET_ENCODING = b"CHARSET_ENCODING"
FONT_ASCENT = b"FONT_ASCENT"
FONT_DESCENT = b"FONT_DESCENT"
DEFAULT_CHAR = b"DEFAULT_CHAR"
SLANT_ROMAN = b"r"
SLANT_ITALIC = b"i"
SLANT_OBLIQUE = b"o"
SLANT_REVERSE_ITALIC = b"ri"
SLANT_REVERSE_OBLIQUE = b"ro"
SLANT_OTHER = b"ot"
SLANT_VALUES: typing.Set[model.PropertyValue] = {
SLANT_ROMAN,
SLANT_ITALIC,
SLANT_OBLIQUE,
SLANT_REVERSE_ITALIC,
SLANT_REVERSE_OBLIQUE,
SLANT_OTHER,
}
SPACING_PROPORTIONAL = b"p"
SPACING_MONOSPACED = b"m"
SPACING_CHARCELL = b"c"
SPACING_VALUES: typing.Set[model.PropertyValue] = {
SPACING_PROPORTIONAL,
SPACING_MONOSPACED,
SPACING_CHARCELL,
}
class ValidationError(ValueError):
"""
Superclass of all problems detected by :func:`.validate()`
"""
def __eq__(self, other: object) -> bool:
return isinstance(other, ValidationError) and self.args == other.args
class NotAnXlfd(ValidationError):
"""
The font's name is not a valid XLFD string
"""
pass
class MissingProperty(ValidationError):
"""
The font is missing a property required by the XLFD conventions
"""
pass
class Contradiction(ValidationError):
"""
A value in the XLFD name contradicts a BDF property value
"""
#: The property name with conflicting values
name: bytes
#: The value associated with the BDF property
prop_value: model.PropertyValue
#: The value stored in the XLFD name
xlfd_value: model.PropertyValue
def __init__(
self,
name: bytes,
prop_value: model.PropertyValue,
xlfd_value: model.PropertyValue,
) -> None:
super().__init__(name, prop_value, xlfd_value)
self.name = name
self.prop_value = prop_value
self.xlfd_value = xlfd_value
def __str__(self) -> str:
return "{!r} value {!r} conflicts with XLFD value {!r}".format(
self.name,
self.prop_value,
self.xlfd_value,
)
class ExpectedInteger(ValidationError):
"""
The value of a property should be an integer
"""
#: The name of the property whose value should be an integer
name: bytes
#: The value that is not an integer
value: bytes
def __init__(self, name: bytes, value: bytes) -> None:
super().__init__(name, value)
self.name = name
self.value = value
def __str__(self) -> str:
return "{name!r} value should be integer, not {value!r}".format(
name=self.name, value=self.value
)
class ExpectedBytestring(ValidationError):
"""
The value of a property should be a bytestring
"""
#: The name of the property whose value should be a bytestring
name: bytes
#: The value that is not a bytestring
value: int
def __init__(self, name: bytes, value: int) -> None:
super().__init__(name, value)
self.name = name
self.value = value
def __str__(self) -> str:
return "{name!r} value should be string, not {value!r}".format(
name=self.name, value=self.value
)
class ExpectedEnumeratedValue(ValidationError):
"""
The value of a property should be one of a fixed set of values
"""
#: The name of the property with an invalid value
name: bytes
#: The value that is not in the expected set
value: model.PropertyValue
#: The set of possible values
expected: typing.Set[model.PropertyValue]
def __init__(
self,
name: bytes,
value: model.PropertyValue,
expected: typing.Set[model.PropertyValue],
) -> None:
super().__init__(name, value, expected)
self.name = name
self.value = value
self.expected = expected
def __str__(self) -> str:
return "{!r} value should be one of {!r}, not {!r}".format(
self.name, sorted(self.expected), self.value
)
def _calculate_properties(
font: model.Font,
) -> model.Properties:
res: model.Properties = {}
# XLFD stores point sizes in tenths of a point.
res[POINT_SIZE] = font.ptSize * 10
# Measure the font metrics ourselves.
minAdvance = inf
maxAdvance = 0
totalAdvance = 0
glyphOverflowsBounds = False
maxAscent = 0
maxDescent = 0
count = 0
for glyph in font.glyphs:
minAdvance = min(minAdvance, glyph.advance)
maxAdvance = max(maxAdvance, glyph.advance)
totalAdvance += glyph.advance
if glyph.bbX < 0 or glyph.bbX + glyph.bbW > glyph.advance:
glyphOverflowsBounds = True
maxAscent = max(maxAscent, glyph.bbY + glyph.bbH)
maxDescent = max(maxDescent, -1 * glyph.bbY)
count += 1
res[AVERAGE_WIDTH] = int(10 * totalAdvance / count)
res[FONT_ASCENT] = maxAscent
res[FONT_DESCENT] = maxDescent
if minAdvance == maxAdvance:
if glyphOverflowsBounds:
res[SPACING] = SPACING_MONOSPACED
else:
res[SPACING] = SPACING_CHARCELL
else:
res[SPACING] = SPACING_PROPORTIONAL
if font.glyphs_by_codepoint:
res[DEFAULT_CHAR] = max(font.glyphs_by_codepoint.keys())
return res
def _parse_xlfd(
xlfd: bytes, errors: typing.List[ValidationError]
) -> model.Properties:
res: model.Properties = {}
for bad_char in (b"?", b"*", b",", b'"'):
# XLFD Conventions, Chapter 3
# An XLFD cannot contain:
#
# - the font name wildcard characters * or ?
# - the font-name separator, ","
# - the font-name quoting character '"'
#
# It also cannot contain a "-" other than as a delimeter,
# but we'll catch that below.
if bad_char in xlfd:
errors.append(NotAnXlfd(xlfd))
return res
parts = xlfd.split(b"-")
if parts[0] != b"":
# XLFD Conventions, Chapter 8
# requires that "The FontName begins with
# the X FontNameRegistry prefix: '-'."
# (i.e. it follows the standard structure, not the private structure.
errors.append(NotAnXlfd(xlfd))
return res
if len(parts) != 15:
# XLFD Conventions, Chapter 3
# After the initial "-" are 14 "-" separated fields.
errors.append(NotAnXlfd(xlfd))
return res
def assign_enumerated(
key: bytes,
value: bytes,
allowed_values: typing.Set[model.PropertyValue],
) -> None:
value = value.lower()
if value in allowed_values:
res[key] = value
else:
errors.append(ExpectedEnumeratedValue(key, value, allowed_values))
def assign_integer(
key: bytes,
value: bytes,
) -> None:
try:
res[key] = int(value)
except ValueError:
errors.append(ExpectedInteger(key, value))
res[FOUNDRY] = parts[1]
res[FAMILY_NAME] = parts[2]
res[WEIGHT_NAME] = parts[3]
assign_enumerated(SLANT, parts[4], SLANT_VALUES)
res[SETWIDTH_NAME] = parts[5]
res[ADD_STYLE_NAME] = parts[6]
assign_integer(PIXEL_SIZE, parts[7])
assign_integer(POINT_SIZE, parts[8])
assign_integer(RESOLUTION_X, parts[9])
assign_integer(RESOLUTION_Y, parts[10])
assign_enumerated(SPACING, parts[11], SPACING_VALUES)
assign_integer(AVERAGE_WIDTH, parts[12])
res[CHARSET_REGISTRY] = parts[13]
res[CHARSET_ENCODING] = parts[14]
return res
def fix(font: model.Font) -> None:
"""
Add missing XLFD properties to a font, with default or calculated values
Any properties already present will be preserved,
even if their values seem to be incorrect.
"""
# The default values for every font.
properties: model.Properties = {
POINT_SIZE: font.ptSize,
PIXEL_SIZE: ceil(font.ydpi * font.ptSize / 72.0),
RESOLUTION_X: font.xdpi,
RESOLUTION_Y: font.ydpi,
WEIGHT_NAME: b"Medium",
SLANT: SLANT_ROMAN,
SETWIDTH_NAME: b"Normal",
ADD_STYLE_NAME: b"",
}
# Add the properties we can calculate from font data.
properties.update(_calculate_properties(font))
# Add our new properties to the font,
# but don't overwrite any existing properties.
properties.update(font.properties)
font.properties = properties
def _check_missing(
font: model.Font, errors: typing.List[ValidationError], key: bytes
) -> None:
if key not in font.properties:
errors.append(MissingProperty(key))
return
def _check_value(
font: model.Font,
errors: typing.List[ValidationError],
key: bytes,
expected_type: type,
expected_values: typing.Optional[typing.Set[model.PropertyValue]] = None,
) -> None:
if key not in font.properties:
# We check for missing properties in _check_missing
return
value = font[key]
if isinstance(value, int) and expected_type == bytes:
errors.append(ExpectedBytestring(key, value))
elif isinstance(value, bytes) and expected_type == int:
errors.append(ExpectedInteger(key, value))
# Otherwise, everything should be fine.
# XLFD strings are case-insensitive.
normalised_value: model.PropertyValue
if isinstance(value, bytes):
normalised_value = value.lower()
else:
normalised_value = value
if expected_values is not None and normalised_value not in expected_values:
errors.append(ExpectedEnumeratedValue(key, value, expected_values))
def _compare_property(
bdf_properties: model.Properties,
xlfd_properties: model.Properties,
errors: typing.List[ValidationError],
key: bytes,
) -> None:
if key not in bdf_properties or key not in xlfd_properties:
# We validate missing properties in _check_missing.
return
bdf_value = bdf_properties[key]
xlfd_value = xlfd_properties[key]
normalised_bdf_value: model.PropertyValue
normalised_xlfd_value: model.PropertyValue
# XLFD strings are case-insensitive.
if isinstance(bdf_value, bytes):
normalised_bdf_value = bdf_value.lower()
else:
normalised_bdf_value = bdf_value
if isinstance(xlfd_value, bytes):
normalised_xlfd_value = xlfd_value.lower()
else:
normalised_xlfd_value = xlfd_value
if normalised_bdf_value != normalised_xlfd_value:
errors.append(Contradiction(key, bdf_value, xlfd_value))
def validate(font: model.Font) -> typing.List[ValidationError]:
"""
Validate a font against the XLFD conventions
This function checks for missing, required properties,
properties with the wrong type,
the syntax of the font's XLFD name
and conflicts between the XLFD name and its properties.
All problems detected
(not just the first)
are returned in a list.
"""
res: typing.List[ValidationError] = []
# XLFD Conventions, chapter 8:
# the 14 values included in the XLFD
# must also be present as properties.
_check_missing(font, res, FOUNDRY)
_check_missing(font, res, FAMILY_NAME)
_check_missing(font, res, WEIGHT_NAME)
_check_missing(font, res, SLANT)
_check_missing(font, res, SETWIDTH_NAME)
_check_missing(font, res, ADD_STYLE_NAME)
_check_missing(font, res, PIXEL_SIZE)
_check_missing(font, res, POINT_SIZE)
_check_missing(font, res, RESOLUTION_X)
_check_missing(font, res, RESOLUTION_Y)
_check_missing(font, res, SPACING)
_check_missing(font, res, AVERAGE_WIDTH)
_check_missing(font, res, CHARSET_REGISTRY)
_check_missing(font, res, CHARSET_ENCODING)
# XLFD Conventions, chapter 8:
# "Any FontProperties provided
# conform in name and semantics
# to the XLFD FontProperty definitions."
_check_value(font, res, FOUNDRY, bytes)
_check_value(font, res, FAMILY_NAME, bytes)
_check_value(font, res, WEIGHT_NAME, bytes)
_check_value(font, res, SLANT, bytes, SLANT_VALUES)
_check_value(font, res, SETWIDTH_NAME, bytes)
_check_value(font, res, ADD_STYLE_NAME, bytes)
_check_value(font, res, PIXEL_SIZE, int)
_check_value(font, res, POINT_SIZE, int)
_check_value(font, res, RESOLUTION_X, int)
_check_value(font, res, RESOLUTION_Y, int)
_check_value(font, res, SPACING, bytes, SPACING_VALUES)
_check_value(font, res, AVERAGE_WIDTH, int)
_check_value(font, res, CHARSET_REGISTRY, bytes)
_check_value(font, res, CHARSET_ENCODING, bytes)
_check_value(font, res, b"MIN_SPACE", int)
_check_value(font, res, b"NORM_SPACE", int)
_check_value(font, res, b"MAX_SPACE", int)
_check_value(font, res, b"END_SPACE", int)
_check_value(font, res, b"AVG_CAPITAL_WIDTH", int)
_check_value(font, res, b"AVG_LOWERCASE_WIDTH", int)
_check_value(font, res, b"QUAD_WIDTH", int)
_check_value(font, res, b"FIGURE_WIDTH", int)
_check_value(font, res, b"SUPERSCRIPT_X", int)
_check_value(font, res, b"SUPERSCRIPT_Y", int)
_check_value(font, res, b"SUBSCRIPT_X", int)
_check_value(font, res, b"SUBSCRIPT_Y", int)
_check_value(font, res, b"SUPERSCRIPT_SIZE", int)
_check_value(font, res, b"SUBSCRIPT_SIZE", int)
_check_value(font, res, b"SMALL_CAP_SIZE", int)
_check_value(font, res, b"UNDERLINE_POSITION", int)
_check_value(font, res, b"UNDERLINE_THICKNESS", int)
_check_value(font, res, b"STRIKEOUT_ASCENT", int)
_check_value(font, res, b"STRIKEOUT_DESCENT", int)
_check_value(font, res, b"ITALIC_ANGLE", int)
_check_value(font, res, b"CAP_HEIGHT", int)
_check_value(font, res, b"X_HEIGHT", int)
_check_value(font, res, b"RELATIVE_SETWIDTH", int)
_check_value(font, res, b"RELATIVE_WEIGHT", int)
_check_value(font, res, b"WEIGHT", int)
_check_value(font, res, b"FACE_NAME", bytes)
_check_value(font, res, b"COPYRIGHT", bytes)
_check_value(font, res, b"NOTICE", bytes)
_check_value(font, res, b"DESTINATION", int)
_check_value(
font,
res,
b"FONT_TYPE",
bytes,
{b"Bitmap", b"Prebuilt", b"Type 1", b"TrueType", b"Speedo", b"F3"},
)
_check_value(font, res, b"FONT_VERSION", bytes)
_check_value(font, res, b"RASTERIZER_NAME", bytes)
_check_value(font, res, b"RASTERIZER_VERSION", bytes)
_check_value(font, res, b"RAW_ASCENT", int)
_check_value(font, res, b"RAW_DESCENT", int)
_check_value(font, res, FONT_ASCENT, int)
_check_value(font, res, FONT_DESCENT, int)
_check_value(
font, res, DEFAULT_CHAR, int, set(font.glyphs_by_codepoint.keys())
)
xlfd_properties = _parse_xlfd(font.name, res)
# Any fields in the XLFD name that also appear as BDF properties
# should have values that match the corresponding BDF property value.
_compare_property(font.properties, xlfd_properties, res, FOUNDRY)
_compare_property(font.properties, xlfd_properties, res, FAMILY_NAME)
_compare_property(font.properties, xlfd_properties, res, WEIGHT_NAME)
_compare_property(font.properties, xlfd_properties, res, SLANT)
_compare_property(font.properties, xlfd_properties, res, SETWIDTH_NAME)
_compare_property(font.properties, xlfd_properties, res, ADD_STYLE_NAME)
_compare_property(font.properties, xlfd_properties, res, PIXEL_SIZE)
_compare_property(font.properties, xlfd_properties, res, POINT_SIZE)
_compare_property(font.properties, xlfd_properties, res, RESOLUTION_X)
_compare_property(font.properties, xlfd_properties, res, RESOLUTION_Y)
_compare_property(font.properties, xlfd_properties, res, SPACING)
_compare_property(font.properties, xlfd_properties, res, AVERAGE_WIDTH)
_compare_property(font.properties, xlfd_properties, res, CHARSET_REGISTRY)
_compare_property(font.properties, xlfd_properties, res, CHARSET_ENCODING)
_compare_property(font.properties, xlfd_properties, res, FONT_ASCENT)
_compare_property(font.properties, xlfd_properties, res, FONT_DESCENT)
return res
bdflib-v2.1.0/docs/ 0000775 0000000 0000000 00000000000 14753047770 0014070 5 ustar 00root root 0000000 0000000 bdflib-v2.1.0/docs/Makefile 0000664 0000000 0000000 00000001133 14753047770 0015526 0 ustar 00root root 0000000 0000000 # Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = bdflib
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) bdflib-v2.1.0/docs/_static/ 0000775 0000000 0000000 00000000000 14753047770 0015516 5 ustar 00root root 0000000 0000000 bdflib-v2.1.0/docs/_static/.gitignore 0000664 0000000 0000000 00000000000 14753047770 0017474 0 ustar 00root root 0000000 0000000 bdflib-v2.1.0/docs/about.rst 0000664 0000000 0000000 00000003511 14753047770 0015734 0 ustar 00root root 0000000 0000000 About this project
==================
Important things to know
about ``bdflib`` and its development.
Requirements
------------
Python 3.8 or greater
(earlier versions may work, but they are unsupported)
``bdflib`` does not require anything outside the standard library.
License
-------
``bdflib`` is published under the GNU General Public License version 3.
Development
-----------
The source-code and issue tracker for ``bdflib`` are at
https://gitlab.com/Screwtapello/bdflib
Once you've checked out the ``bdflib`` source code,
you can run the ``bdflib`` unit tests with:
.. code-block:: console
$ python3 -m unittest
Alternatively,
if you have `tox `_ installed,
you can just run:
.. code-block:: console
$ tox
to run all the tests and build all the documentation.
Further reading
---------------
- `Bitmap Distribution Format version 2.1
`_ (PDF format)
is the X11 version of the BDF specification,
based on the Adobe standard.
- `Glyph Bitmap Distribution Format (BDF) Specification version 2.2
`_
(PDF format)
is the Adobe version of the BDF specification.
Version 2.2 is backward-compatible with version 2.1,
and adds extra features to support scripts with vertical text layout.
``bdflib`` does not implement this version,
but some things are better explained here than in the X11 version.
- `X Logical Font Description Conventions
`_
describes the extra font properties that X11 uses,
above and beyond the basic BDF specification.
- `BDF Fonts and Modern Linux
`_
describes practical concerns with making a BDF font
that will be properly recognised by a modern Linux system.
bdflib-v2.1.0/docs/changelog.rst 0000664 0000000 0000000 00000012303 14753047770 0016550 0 ustar 00root root 0000000 0000000 Changelog
=========
All notable changes to this project will be documented in this file.
The format is based on `Keep a Changelog`_,
and this project adheres to `Semantic Versioning`_.
`Unreleased`_
-------------
Nothing yet.
`v2.1.0`_ - 2025-02-12
----------------------
Added:
* Complete type annotations for the whole library.
* :func:`.effects.expand` for increasing the resolution of a font,
along with the ``bdflib-expand`` command-line tool to wrap it.
* A new ``bdflib-validate`` command-line tool to exercise the rewritten parser
(described below).
* :meth:`.Font.get` to match the existing :meth:`.Font.__getitem__` method.
Changed:
* :func:`.reader.read_bdf` is much more robust,
reports errors with a well-defined :class:`.reader.ParseError` class
(instead of random :class:`AssertionError`
and :class:`ValueError` exceptions),
and can report warnings as well as errors.
If your code did not check exceptions too closely
(and it probably shouldn't have),
it should still work just fine.
Fixed:
* :meth:`.Font.new_glyph_from_data` now raises :class:`.GlyphExists`
*before* adding the glyph to the font,
rather than after.
`v2.0.1`_ - 2022-01-14
----------------------
Fixed:
* Fixed the v2.0.0 changelog entry.
`v2.0.0`_ - 2022-01-14
----------------------
Added:
* This changelog!
* Documentation for the :attr:`.FontFiller.missing_chars`
and :attr:`.FontFiller.unknown_classes` attributes.
* :class:`.Font` now stores the standard BDF fields as attributes
(:attr:`~.Font.name`, :attr:`~.Font.ptSize`, :attr:`~.Font.xdpi`,
:attr:`~.Font.ydpi`).
* :mod:`bdflib.xlfd` makes it easy to check whether a font
conforms to the X Logical Font Descriptor conventions,
and to automatically fix many conformance problems.
Changed:
* Now that :class:`.Font` stores BDF fields in standard attributes,
and now that :mod:`bdflib.xlfd` exists,
the :class:`.Font` class no longer needs to assume
BDF custom properties are used for anything in particular.
In particular, the standard BDF fields are no longer mirrored
to XLFD-style properties,
there's no special property names that cannot be overwritten,
and XLFD properties will no longer be automatically synthesised
when writing out a BDF font.
* The :class:`.Glyph` constructor
(and therefore :meth:`.Font.new_glyph_from_data()`)
now takes bitmap data in the form of a list of integers,
not the hex-encoded string used in the BDF on-disk format.
Removed:
* Support for Python 2.x
* Support for fonts whose point-size
(the first parameter to the `SIZE` field in the font header)
is a non-integer. I don't know why I ever thought this was a good idea.
`v1.1.3`_ - 2019-04-23
----------------------
Fixed:
* We now support BDF comments in more places
(although all the comments in a file are still concatenated)
* We now support values being separated from keywords
by more than a single space.
`v1.1.2`_ - 2019-04-22
----------------------
Added:
* The examples in the API reference and tutorial
are now automatically tested.
Fixed:
* The documentation now includes the `tutorial.bdf` file
used by the tutorial.
`v1.1.1`_ - 2018-11-19
----------------------
Changed:
* Set the package long description to the README contents.
`v1.1.0`_ - 2018-11-19
----------------------
Added:
* Standalone documentation, including a tutorial
* The :meth:`.Glyph.iter_pixels()` method,
making it easier to get at the glyph bitmap data.
Fixed:
* :class:`.FontFiller` now supports
supports generating spacing characters made from only combining characters.
`v1.0.4`_ - 2016-10-19
----------------------
Added:
* Support for Python 3.
`v1.0.3`_ - 2016-09-25
----------------------
Fixed:
* No longer breaks on BDF files containing blank lines.
`v1.0.2`_ - 2016-03-27
----------------------
Added:
* a README
* Support for running tests with Tox
Fixed:
* No longer requires to be installed from a Git checkout.
`v1.0.1`_ - 2015-04-06
----------------------
Changed:
* Repository moved from Gitorious to GitLab
`v1.0.0`_ - 2009-03-22
----------------------
Initial release.
.. _Keep a Changelog: https://keepachangelog.com/en/1.0.0/
.. _Semantic Versioning: https://semver.org/spec/v2.0.0.html
.. _v1.0.0: https://gitlab.com/Screwtapello/bdflib/-/tree/v1.0.0
.. _v1.0.1: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.0.0...v1.0.1
.. _v1.0.2: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.0.1...v1.0.2
.. _v1.0.3: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.0.2...v1.0.3
.. _v1.0.4: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.0.3...v1.0.4
.. _v1.1.0: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.0.4...v1.1.0
.. _v1.1.1: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.1.0...v1.1.1
.. _v1.1.1: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.1.0...v1.1.1
.. _v1.1.2: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.1.1...v1.1.2
.. _v1.1.3: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.1.2...v1.1.3
.. _v2.0.0: https://gitlab.com/Screwtapello/bdflib/-/compare/v1.1.3...v2.0.0
.. _v2.0.1: https://gitlab.com/Screwtapello/bdflib/-/compare/v2.0.0...v2.0.1
.. _v2.1.0: https://gitlab.com/Screwtapello/bdflib/-/compare/v2.0.1...v2.1.0
.. _Unreleased: https://gitlab.com/Screwtapello/bdflib/-/compare/v2.1.0...master
bdflib-v2.1.0/docs/conf.py 0000664 0000000 0000000 00000012463 14753047770 0015375 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = "bdflib"
copyright = "2009-2022, Timothy Allen"
author = "Timothy Allen"
# The short X.Y version
version = "2.1.0"
# The full version, including alpha/beta/rc tags
release = "2.1.0"
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.viewcode",
"sphinx.ext.intersphinx",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "bdflibdoc"
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"bdflib.tex",
"bdflib Documentation",
"Timothy Allen",
"manual",
),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "bdflib", "bdflib Documentation", [author], 1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"bdflib",
"bdflib Documentation",
author,
"bdflib",
"One line description of project.",
"Miscellaneous",
),
]
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
autodoc_default_options = {
"members": None,
"undoc-members": None,
"inherited-members": None,
"show-inheritance": None,
}
bdflib-v2.1.0/docs/index.rst 0000664 0000000 0000000 00000001347 14753047770 0015736 0 ustar 00root root 0000000 0000000 .. bdflib documentation master file, created by
sphinx-quickstart on Sat Oct 27 13:18:54 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to bdflib's documentation!
==================================
bdflib is a Python library for working with `BDF fonts`_.
The library allows for manipulating fonts directly and comes with
command-line utilities for performing various operations on font files.
.. _BDF fonts: http://en.wikipedia.org/wiki/BDF_%28Glyph_Bitmap_Distribution_Format%29
.. toctree::
:maxdepth: 2
about
tutorial
reference
changelog
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
bdflib-v2.1.0/docs/make.bat 0000664 0000000 0000000 00000001452 14753047770 0015477 0 ustar 00root root 0000000 0000000 @ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
set SPHINXPROJ=bdflib
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
bdflib-v2.1.0/docs/reference.rst 0000664 0000000 0000000 00000001363 14753047770 0016563 0 ustar 00root root 0000000 0000000 API Reference
=============
.. automodule:: bdflib
:members:
:show-inheritance:
``bdflib.model``
----------------
.. automodule:: bdflib.model
:members:
:show-inheritance:
``bdflib.reader``
-----------------
.. automodule:: bdflib.reader
:members:
:show-inheritance:
``bdflib.writer``
-----------------
.. automodule:: bdflib.writer
:members:
:show-inheritance:
``bdflib.effects``
------------------
.. automodule:: bdflib.effects
:members:
:show-inheritance:
``bdflib.glyph_combining``
--------------------------
.. automodule:: bdflib.glyph_combining
:members:
:show-inheritance:
``bdflib.xlfd``
--------------------------
.. automodule:: bdflib.xlfd
:members:
:no-inherited-members:
bdflib-v2.1.0/docs/tutorial.bdf 0000664 0000000 0000000 00000000261 14753047770 0016407 0 ustar 00root root 0000000 0000000 STARTFONT 2.1
FONT Tutorial Font
SIZE 9 72 72
FONTBOUNDINGBOX 5 5 0 0
CHARS 1
STARTCHAR o
ENCODING 111
SWIDTH 666 0
DWIDTH 6 0
BBX 5 5 0 0
BITMAP
70
88
88
88
70
ENDCHAR
ENDFONT
bdflib-v2.1.0/docs/tutorial.rst 0000664 0000000 0000000 00000015046 14753047770 0016473 0 ustar 00root root 0000000 0000000 Tutorial
========
This document will guide you through installing the ``bdflib`` library,
and using it to read, modify and write a font.
Installation
------------
For this tutorial,
we will install ``bdflib`` in a "virtual environment"
so it doesn't interfere with any other Python libraries or applications
that might be installed on your system.
1. Create a virtual environment named ``bdflib-tutorial``:
.. code-block:: console
$ python3 -m venv bdflib-tutorial
2. Install the ``bdflib`` library into the virtual environment:
.. code-block:: console
$ bdflib-tutorial/bin/pip install bdflib
3. Launch Python from the virtual environment:
.. code-block:: console
$ bdflib-tutorial/bin/python
4. Verify that ``bdflib`` is properly installed:
.. doctest::
>>> import bdflib
>>> bdflib.__version__
'2.1.0'
Reading an existing font
------------------------
The most basic thing you'll want to do with ``bdflib``
is to read in an existing font in the BDF format.
For this tutorial,
we'll use the following font.
Copy and paste it
into a text editor and save it as ``tutorial.bdf``,
or :download:`download it `:
.. literalinclude:: tutorial.bdf
Reading in a BDF file is really easy:
>>> from bdflib import reader
>>> with open("docs/tutorial.bdf", "rb") as handle:
... font = reader.read_bdf(handle)
Of course,
instead of ``docs/tutorial.bdf``
you should use the actual path to your ``tutorial.bdf`` file.
When you call :func:`.read_bdf`,
you get back a :class:`.Font` object
which represents the font, its metadata, and all its glyphs.
For example, our font has a name and a point-size:
.. doctest::
:pyversion: >= 3.0
>>> font.name
b'Tutorial Font'
>>> font.ptSize
9
Our font also has a glyph for lowercase letter "o":
>>> letter_o = font[ord("o")]
``letter_o`` is a :class:`.Glyph` object
representing the glyph and its properties.
.. doctest::
:pyversion: >= 3.0
>>> letter_o.name
b'o'
To help debugging,
``bdflib`` can render a glyph bitmap to a printable string:
>>> print(letter_o)
|###.
#...#
#...#
#...#
+###-
* ``#`` characters represent pixels that are drawn
* ``.`` characters represent pixels that are blank
* ``-`` and ``|`` represent the X and Y axes
(mostly obscured by drawn pixels in the above example)
* ``+`` represents the origin where they cross over
When you draw a glyph at a particular point on-screen,
the glyph's origin is put on that exact point.
It's usually the bottom-left corner of the glyph,
but some glyphs may start above and to the right
(like an apostrophe)
and some glyphs may start below and to the left
(like a lower-case ``j``).
Adding a glyph
--------------
Once you have a :class:`.Font` object,
you can modify it.
For example,
you can add a new glyph
with the :meth:`.new_glyph_from_data` method.
Let's add a glyph for U+0302 COMBINING CIRCUMFLEX ACCENT.
We start by designing our glyph.
A circumflex is an angle pointing up,
and at the size of our letter "o", it might look like this::
..#..
.#.#.
#...#
BDF files encode each row of the glyph
as a binary number,
where a 1 means a drawn pixel and a 0 means no pixel.
In Python, that might look like this::
0b00100
0b01010
0b10001
However,
BDF uses the traditonal mathematical coordinate system
with 0,0 in the bottom left.
If we put the above binary numbers in coordinate order,
from bottom to top,
we get the Python encoding of the bitmap::
[0b10001, 0b01010, 0b00100]
Now we can add our new glyph:
>>> combining_circumflex = font.new_glyph_from_data(
... # Adobe says glyphs not in the Adobe Glyph List and with codepoints
... # below 0xFFFF should be named 'uni' + four hex digits of the
... # codepoint.
... name=b"uni0302",
... # The bitmap we created above.
... data=[0b10001, 0b01010, 0b00100],
... # We don't need to shift this glyph to the left or right.
... bbX=0,
... # Capitals for this font are 9px high, then leave a 1px gap.
... bbY=10,
... # This glyph is 5px wide.
... bbW=5,
... # This glyph is 3px tall.
... bbH=3,
... # 5px wide, 1px gap, so the next character is 6px to the right.
... advance=6,
... # This is character U+0302.
... codepoint=0x0302,
... )
And now we have our circumflex glyph,
ready to combine with anything else
without overlapping:
>>> print(combining_circumflex)
|.#..
|#.#.
#...#
|....
|....
|....
|....
|....
|....
|....
|....
|....
+----
Merging glyphs
--------------
We have a glyph for LATIN SMALL LETTER O,
and we have a glyph for COMBINING CIRCUMFLEX ACCENT,
but there's also a Unicode character named
LATIN SMALL LETTER O WITH CIRCUMFLEX.
We could just draw it ourselves from scratch,
like we did with COMBINING CIRCUMFLEX ACCENT,
but it seems a waste of energy
when we already have the component glyphs available.
Luckily,
the :meth:`.Glyph.merge_glyph()` method
makes it easy to, well, merge two existing glyphs together.
First, we'll need to create the new glyph
using the new name and codepoint,
but re-using other properties from the base glyph:
>>> letter_o_with_circumflex = font.new_glyph_from_data(
... name=b"ocircumflex",
... data=letter_o.data,
... bbX=letter_o.bbX,
... bbY=letter_o.bbY,
... bbW=letter_o.bbW,
... bbH=letter_o.bbH,
... advance=letter_o.advance,
... codepoint=0x00F4,
... )
Next, we'll merge the circumflex glyph on top.
Since the circumflex glyph was positioned
to sit above nine-pixel-tall capitals
but this is a five-pixel-tall lowercase letter,
we'll need to move the circumflex down by four pixels:
>>> letter_o_with_circumflex.merge_glyph(
... other=combining_circumflex,
... atX=0,
... atY=-4,
... )
The result is a lowercase "o"
with a circumflex resting snugly on top!
>>> print(letter_o_with_circumflex)
|.#..
|#.#.
#...#
|....
|###.
#...#
#...#
#...#
+###-
If you want to automatically generate
as many glyphs as possible
from the base and combining glyphs in your font,
take a look at the :mod:`.glyph_combining` module.
Writing a font
--------------
Now that we've customised our font,
we can write the result to a new file:
>>> from bdflib import writer
>>> with open("docs/tutorial2.bdf", "wb") as handle:
... writer.write_bdf(font, handle)
Once again,
the path ``docs/tutorial2.bdf``
can be whatever path you like.
bdflib-v2.1.0/pyproject.toml 0000664 0000000 0000000 00000000210 14753047770 0016045 0 ustar 00root root 0000000 0000000 [tool.black]
line-length = 80
target-version = ['py38', 'py39', 'py310', 'py311', 'py312', 'py313']
[tool.mypy]
python_version = "3.8"
bdflib-v2.1.0/setup.py 0000775 0000000 0000000 00000002004 14753047770 0014651 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
from setuptools import setup
with open("README.md", "r") as handle:
long_description = handle.read()
setup(
name="bdflib",
version="2.1.0",
description="Library for working with BDF font files.",
long_description=long_description,
long_description_content_type="text/markdown",
author="Timothy Allen",
author_email="screwtape@froup.com",
url="https://gitlab.com/Screwtapello/bdflib/",
packages=["bdflib", "bdflib.test"],
package_data={"bdflib": ["py.typed"]},
entry_points={
"console_scripts": [
"bdflib-embolden = bdflib.tools:embolden",
"bdflib-expand= bdflib.tools:expand",
"bdflib-fill = bdflib.tools:fill",
"bdflib-merge = bdflib.tools:merge",
"bdflib-passthrough = bdflib.tools:passthrough",
"bdflib-validate = bdflib.tools:validate",
"bdflib-xlfd-validate = bdflib.tools:xlfd_validate",
"bdflib-xlfd-fix = bdflib.tools:xlfd_fix",
]
},
)
bdflib-v2.1.0/tox.ini 0000664 0000000 0000000 00000000777 14753047770 0014466 0 ustar 00root root 0000000 0000000 [tox]
envlist=py3
[testenv]
deps=
sphinx
black
mypy
flake8
coverage
commands=
black --check .
coverage erase
coverage run -m unittest -b
coverage report -m --fail-under 100
sphinx-build -E -b coverage docs build/sphinx/html
sphinx-build -E -b html docs build/sphinx/html
sphinx-build -E -b doctest docs build/sphinx/html
mypy -p bdflib --strict
flake8 bdflib
[flake8]
# Must match black config in pyproject.toml
max-line-length = 80
max-complexity = 10