Compare commits

...

40 commits

Author SHA1 Message Date
Kattni
1d712519fc
Merge pull request #27 from FoamyGuy/adding_more_examples
Adding more examples
2020-08-17 15:17:17 -04:00
FoamyGuy
fa19aa5697 keep showing the text 2020-08-15 19:34:58 -05:00
FoamyGuy
eec7b341b8 adding a label example 2020-08-15 16:08:59 -05:00
FoamyGuy
d74656c372 adding a displayio example 2020-08-15 16:00:25 -05:00
Jeff Epler
784322cac4
Merge pull request #24 from FoamyGuy/fix_docs_link_in_readme
fix docs link in readme
2020-08-15 07:34:53 -05:00
FoamyGuy
3116924087 fix docs link in readme 2020-08-14 21:06:59 -05:00
dherrada
5a2b0496cb Fixed discord invite link 2020-07-08 16:49:04 -04:00
Dan Halbert
33439e7479
Merge pull request #22 from adafruit/black-update
Black reformatting with Python 3 target.
2020-04-09 21:48:07 -04:00
Kattni Rembor
43be1dac6b Black reformatting with Python 3 target. 2020-04-09 17:22:09 -04:00
sommersoft
cc47939b31 build.yml: add black formatting check
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-04-07 16:12:22 -05:00
Kattni
5042a3a633
Merge pull request #21 from FoamyGuy/remove-backward-compatibility
Remove backward compatibility
2020-04-02 12:04:00 -04:00
FoamyGuy
97dadca2d1 update mock imports in docs conf 2020-04-01 20:06:22 -05:00
foamyguy
5ab346373b
change Glyph import to fontio 2020-04-01 19:04:50 -05:00
Kattni Rembor
f42442a15b Removing 3.0.0 compatibility. 2020-03-30 11:59:40 -04:00
Kattni
b916b709bc
Merge pull request #19 from andreamah/pip-installation-fix
setup.py fixes for correct pip installation
2020-03-18 14:38:10 -04:00
andreamah
428433025a setup.py fixes for correct pip installation 2020-03-18 09:55:23 -07:00
Kattni
4b663e6f25
Merge pull request #17 from adafruit/pylint-update
Ran black, updated to pylint 2.x
2020-03-16 18:44:05 -04:00
dherrada
0e13195ac9 Ran black, updated to pylint 2.x 2020-03-15 16:17:54 -04:00
sommersoft
ffbfb560f9
Merge pull request #16 from sommersoft/patch_coc
Update Code of Conduct
2020-03-15 09:18:54 -05:00
sommersoft
756e84e3d6 update code of conduct 2020-03-15 09:12:33 -05:00
sommersoft
8d19d48e87 update pylintrc for black
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-08 19:06:16 -05:00
sommersoft
0d0ef30b06 build.yml: move pylint, black, and Sphinx installs to each repo; add description to 'actions-ci/install.sh'
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-05 10:05:13 -06:00
sommersoft
1754a8a52b update pylint examples directive
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-01-14 17:18:42 -06:00
Kattni
6edb08c222
Merge pull request #6 from SeattleChris/example_test
Examples test working
2020-01-12 15:37:40 -05:00
Kattni
b274f6270b
Update to correct pylint: disable error 2020-01-12 15:34:46 -05:00
Scott Shawcroft
958cf34ad3
Add comment and disable lint error 2020-01-10 11:35:38 -08:00
Jeff Epler
b3356eb5e2
Merge pull request #15 from tannewt/load_string_glyphs
Handle string inputs to load_glyphs for BDF.
2020-01-08 16:00:26 -06:00
Scott Shawcroft
5a0dae65e3
Don't encode because it breaks unicode values. 2020-01-08 11:29:17 -08:00
Scott Shawcroft
af0ba1d2ef
Handle string inputs to load_glyphs for BDF. 2020-01-07 15:06:50 -08:00
Limor "Ladyada" Fried
49f281898d
Merge pull request #14 from adafruit/dherrada-patch-1
Moved repository from Travis to GitHub Actions
2019-12-27 22:54:19 -05:00
dherrada
50776d8e63 Moved repository from Travis to GitHub Actions 2019-12-27 22:23:52 -05:00
Kattni
31d0b01c14
Merge pull request #12 from adafruit/dherrada-patch-1
Removed building locally section from README, replaced with documenta…
2019-10-21 19:54:56 -04:00
dherrada
87ffc91e4d
Removed building locally section from README, replaced with documentation section 2019-10-17 18:17:44 -04:00
Limor "Ladyada" Fried
1c0d724da3
Merge pull request #11 from tannewt/improve_preload
Speed up preloads with duplicate code points
2019-05-21 20:34:45 -04:00
Scott Shawcroft
57e9e98bfd
Rename variable for lint. 2019-05-21 16:02:22 -07:00
Scott Shawcroft
fc75a1aade
Speed up preloads with duplicate code points
The original logic wouldn't recognize duplicate characters
in the given set to preload and therefore it'd read the whole
font file looking for a character it already found. A set
deduplicates the given characters at a small memory cost.
2019-05-21 15:55:58 -07:00
Dan Halbert
2f64725e6e
Merge pull request #8 from tannewt/fontio
Add support for fontio
2019-03-20 17:38:28 -04:00
Scott Shawcroft
e26a474223
Add support for fontio 2019-03-19 16:20:17 -07:00
Chris L Chapman
5a5e2865f7 Examples test working 2019-02-25 15:54:51 -08:00
Kattni
c0f8e55764
Merge pull request #4 from adafruit/kattni-patch-1
Fix syntax issue.
2019-02-18 18:23:48 -05:00
20 changed files with 7776 additions and 226 deletions

57
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,57 @@
name: Build CI
on: [pull_request, push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.6
uses: actions/setup-python@v1
with:
python-version: 3.6
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install dependencies
# (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.)
run: |
source actions-ci/install.sh
- name: Pip install pylint, black, & Sphinx
run: |
pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme
- name: Library version
run: git describe --dirty --always --tags
- name: Check formatting
run: |
black --check --target-version=py35 .
- name: PyLint
run: |
pylint $( find . -path './adafruit*.py' )
([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" ))
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Build docs
working-directory: docs
run: sphinx-build -E -W -b html . _build/html

81
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,81 @@
name: Release Actions
on:
release:
types: [published]
jobs:
upload-release-assets:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.6
uses: actions/setup-python@v1
with:
python-version: 3.6
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install deps
run: |
source actions-ci/install.sh
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Upload Release Assets
# the 'official' actions version does not yet support dynamically
# supplying asset names to upload. @csexton's version chosen based on
# discussion in the issue below, as its the simplest to implement and
# allows for selecting files with a pattern.
# https://github.com/actions/upload-release-asset/issues/4
#uses: actions/upload-release-asset@v1.0.1
uses: csexton/release-asset-action@master
with:
pattern: "bundles/*"
github-token: ${{ secrets.GITHUB_TOKEN }}
upload-pypi:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Check For setup.py
id: need-pypi
run: |
echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
- name: Set up Python
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Install dependencies
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
env:
TWINE_USERNAME: ${{ secrets.pypi_username }}
TWINE_PASSWORD: ${{ secrets.pypi_password }}
run: |
python setup.py sdist
twine upload dist/*

2
.gitignore vendored
View file

@ -4,12 +4,10 @@ __pycache__
_build
*.pyc
.env
build*
bundles
*.DS_Store
.eggs
dist
**/*.egg-info
*.bdf
*.pcf
*.ttf

View file

@ -52,7 +52,7 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option

View file

@ -1,39 +0,0 @@
# This is a common .travis.yml for generating library release zip files for
# CircuitPython library releases using circuitpython-build-tools.
# See https://github.com/adafruit/circuitpython-build-tools for detailed setup
# instructions.
dist: xenial
language: python
python:
- "3.6"
cache:
pip: true
deploy:
- provider: releases
api_key: "$GITHUB_TOKEN"
file_glob: true
file: "$TRAVIS_BUILD_DIR/bundles/*"
skip_cleanup: true
overwrite: true
on:
tags: true
- provider: pypi
user: adafruit-travis
password:
secure: "P09U1Li5o8i5+piX6J5wIbfCOqtgcl7DAVoSQ37Bq5B7IMKt4ACKUG3Qe3rkt6YoRFIs0HGAb0+qU4h4ITOFZ8fo0Nj/0MwSdJ7Fox5zHyh1p/IQwZT2o6U95Tghztbkezu7TXzRgAbI80WCOEX8AFGJjNcecBMJl+445FYN3JhVzgJ5KxklgTRdSe7aas0Pc7FK3+aTgJGTbSWrA5UiqlJ0zBniFq8rMt53YSNKZbfJJzkPVvc29Uz+HU5QUelLYJdtgu32b1dndo3tMl1ZOpFpxb0MTYW30XA6PTVb1r1Z7y/uHi1BogBu5Ok016GUbodjMLwosFjNW0Y3S7vg9EKMfCXs46auDaEEt/LHVKqfUGJvIXyfRD3AEVHzU7LUeF41ZWU3LCcOeVvEGfNJGdfrCSpph3TV0ZUOqmIL+0juu+hzgUW4EU5v55x1uRk0gnlg8U2IcC/VRSTY4QH6PgdLJS1eGZFiH5SbrBkTLfpxHJbQjPammnjNe86yjO4nFSJLrbucIxbJQfOHJCLTHryVHnPCCf0ElwYYEnIV/MgRE3UQY/g0CEiAAIWYtddBqqX/kKlUYqQES/5Jpu7SpqPFKsJOXhThAJfcvI3ipLIAgiyf6/AJqHY1NCwtn6+A0oCy380T4CL7KRcWIuQfUBYYmiDgS47vBASrLClc99s="
on:
tags: true
install:
- pip install -r requirements.txt
- pip install circuitpython-build-tools Sphinx sphinx-rtd-theme
- pip install --force-reinstall pylint==1.9.2
script:
- pylint adafruit_bitmap_font/*.py
- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.py)
- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-bitmap_font --library_location .
- cd docs && sphinx-build -E -W -b html . _build/html && cd ..

View file

@ -34,6 +34,8 @@ Examples of unacceptable behavior by participants include:
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* Trolling, insulting/derogatory comments, and personal or political attacks
* Promoting or spreading disinformation, lies, or conspiracy theories against
a person, group, organisation, project, or community
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
@ -72,10 +74,10 @@ You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an
open message from any channel, or a direct message to @kattni#1507,
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@Andon#8175.
to all Community Moderators by tagging @community moderators. You may
also send an open message from any channel, or a direct message to
@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442,
@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175.
Email and direct message reports will be kept confidential.

View file

@ -2,15 +2,15 @@ Introduction
============
.. image:: https://readthedocs.org/projects/adafruit-circuitpython-bitmap_font/badge/?version=latest
:target: https://circuitpython.readthedocs.io/projects/bitmap_font/en/latest/
:target: https://circuitpython.readthedocs.io/projects/bitmap-font/en/latest/
:alt: Documentation Status
.. image:: https://img.shields.io/discord/327254708534116352.svg
:target: https://discord.gg/nBQh6qu
:target: https://adafru.it/discord
:alt: Discord
.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.svg?branch=master
:target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Bitmap_Font
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/workflows/Build%20CI/badge.svg
:target: https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/actions/
:alt: Build Status
Loads bitmap fonts into CircuitPython's displayio. BDF files are well supported. PCF and TTF
@ -68,52 +68,7 @@ Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/blob/master/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming.
Building locally
================
Documentation
=============
Zip release files
-----------------
To build this library locally you'll need to install the
`circuitpython-build-tools <https://github.com/adafruit/circuitpython-build-tools>`_ package.
.. code-block:: shell
python3 -m venv .env
source .env/bin/activate
pip install circuitpython-build-tools
Once installed, make sure you are in the virtual environment:
.. code-block:: shell
source .env/bin/activate
Then run the build:
.. code-block:: shell
circuitpython-build-bundles --filename_prefix adafruit-circuitpython-bitmap_font --library_location .
Sphinx documentation
-----------------------
Sphinx is used to build the documentation based on rST files and comments in the code. First,
install dependencies (feel free to reuse the virtual environment from above):
.. code-block:: shell
python3 -m venv .env
source .env/bin/activate
pip install Sphinx sphinx-rtd-theme
Now, once you have the virtual environment activated:
.. code-block:: shell
cd docs
sphinx-build -E -W -b html . _build/html
This will output the documentation to ``docs/_build/html``. Open the index.html in your browser to
view them. It will also (due to -W) error out on any warning like Travis will. This is a good way to
locally verify it will pass.
For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.

View file

@ -40,14 +40,16 @@ Implementation Notes
"""
import gc
from displayio import Glyph
from fontio import Glyph
from .glyph_cache import GlyphCache
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
class BDF(GlyphCache):
"""Loads glyphs from a BDF file in the given bitmap_class."""
def __init__(self, f, bitmap_class):
super().__init__()
self.file = f
@ -86,7 +88,20 @@ class BDF(GlyphCache):
current_info = {}
current_y = 0
rounded_x = 1
total_remaining = len(code_points)
if isinstance(code_points, int):
remaining = set()
remaining.add(code_points)
elif isinstance(code_points, str):
remaining = set(ord(c) for c in code_points)
elif isinstance(code_points, set):
remaining = code_points
else:
remaining = set(code_points)
for code_point in remaining:
if code_point in self._glyphs and self._glyphs[code_point]:
remaining.remove(code_point)
if not remaining:
return
x, _, _, _ = self.get_bounding_box()
@ -110,16 +125,19 @@ class BDF(GlyphCache):
if desired_character:
bounds = current_info["bounds"]
shift = current_info["shift"]
self._glyphs[code_point] = Glyph(current_info["bitmap"],
gc.collect()
self._glyphs[code_point] = Glyph(
current_info["bitmap"],
0,
bounds[0],
bounds[1],
bounds[2],
bounds[3],
shift[0],
shift[1])
gc.collect()
if total_remaining == 0:
shift[1],
)
remaining.remove(code_point)
if not remaining:
return
desired_character = False
elif line.startswith(b"BBX"):
@ -143,9 +161,7 @@ class BDF(GlyphCache):
elif line.startswith(b"ENCODING"):
_, code_point = line.split()
code_point = int(code_point)
if code_point == code_points or code_point in code_points:
total_remaining -= 1
if code_point not in self._glyphs or not self._glyphs[code_point]:
if code_point in remaining:
desired_character = True
current_info = {"bitmap": None, "bounds": None, "shift": None}
elif line.startswith(b"DWIDTH"):

View file

@ -45,19 +45,23 @@ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
def load_font(filename, bitmap=None):
"""Loads a font file. Returns None if unsupported."""
# pylint: disable=import-outside-toplevel
if not bitmap:
import displayio
bitmap = displayio.Bitmap
font_file = open(filename, "rb")
first_four = font_file.read(4)
#print(first_four)
if filename.endswith("bdf") and first_four == b"STAR":
from . import bdf
return bdf.BDF(font_file, bitmap)
if filename.endswith("pcf") and first_four == b"\x01fcp":
import pcf
return pcf.PCF(font_file)
if filename.endswith("ttf") and first_four == b"\x00\x01\x00\x00":
import ttf
return ttf.TTF(font_file)
return None

View file

@ -47,12 +47,12 @@ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
class GlyphCache:
"""Caches glyphs loaded by a subclass."""
def __init__(self):
self._glyphs = {}
def load_glyphs(self, code_points):
"""Loads displayio.Glyph objects into the GlyphCache from the font."""
pass
def get_glyph(self, code_point):
"""Returns a displayio.Glyph for the given code point or None is unsupported."""

View file

@ -5,28 +5,29 @@ from .glyph_cache import GlyphCache
import displayio
import struct
_PCF_PROPERTIES = (1<<0)
_PCF_ACCELERATORS = (1<<1)
_PCF_METRICS = (1<<2)
_PCF_BITMAPS = (1<<3)
_PCF_INK_METRICS = (1<<4)
_PCF_BDF_ENCODINGS = (1<<5)
_PCF_SWIDTHS = (1<<6)
_PCF_GLYPH_NAMES = (1<<7)
_PCF_BDF_ACCELERATORS = (1<<8)
_PCF_PROPERTIES = 1 << 0
_PCF_ACCELERATORS = 1 << 1
_PCF_METRICS = 1 << 2
_PCF_BITMAPS = 1 << 3
_PCF_INK_METRICS = 1 << 4
_PCF_BDF_ENCODINGS = 1 << 5
_PCF_SWIDTHS = 1 << 6
_PCF_GLYPH_NAMES = 1 << 7
_PCF_BDF_ACCELERATORS = 1 << 8
_PCF_DEFAULT_FORMAT = 0x00000000
_PCF_INKBOUNDS = 0x00000200
_PCF_ACCEL_W_INKBOUNDS = 0x00000100
_PCF_COMPRESSED_METRICS = 0x00000100
_PCF_GLYPH_PAD_MASK = (3<<0) # See the bitmap table for explanation */
_PCF_BYTE_MASK = (1<<2) # If set then Most Sig Byte First */
_PCF_BIT_MASK = (1<<3) # If set then Most Sig Bit First */
_PCF_SCAN_UNIT_MASK = (3<<4)
_PCF_GLYPH_PAD_MASK = 3 << 0 # See the bitmap table for explanation */
_PCF_BYTE_MASK = 1 << 2 # If set then Most Sig Byte First */
_PCF_BIT_MASK = 1 << 3 # If set then Most Sig Bit First */
_PCF_SCAN_UNIT_MASK = 3 << 4
# https://fontforge.github.io/en-US/documentation/reference/pcf-format/
class PCF(GlyphCache):
def __init__(self, f):
super().__init__()
@ -47,17 +48,17 @@ class PCF(GlyphCache):
def get_bounding_box(self):
property_table_offset = self.tables[_PCF_PROPERTIES]["offset"]
self.file.seek(property_table_offset)
format, = self.read("<I")
(format,) = self.read("<I")
if format & _PCF_BYTE_MASK == 0:
raise RuntimeError("Only big endian supported")
nprops, = self.read(">I")
(nprops,) = self.read(">I")
self.file.seek(property_table_offset + 8 + 9 * nprops)
pos = self.file.tell()
if pos % 4 > 0:
self.file.read(4 - pos % 4)
string_size, = self.read(">I")
(string_size,) = self.read(">I")
strings = self.file.read(string_size)
string_map = {}
@ -153,7 +154,9 @@ class PCF(GlyphCache):
for i in range(rounded_x):
val = (bits >> ((rounded_x - i - 1) * 8)) & 0xFF
scratch_row[i] = val
current_info["bitmap"]._load_row(current_y, scratch_row[:bytes_per_row])
current_info["bitmap"]._load_row(
current_y, scratch_row[:bytes_per_row]
)
current_y += 1
elif metadata:
# print(lineno, line.strip())

View file

@ -6,6 +6,7 @@ import struct
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
class TTF:
def __init__(self, f):
f.seek(0)

View file

@ -2,7 +2,8 @@
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------
@ -10,42 +11,45 @@ sys.path.insert(0, os.path.abspath('..'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
]
# TODO: Please Read!
# Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning.
autodoc_mock_imports = ["displayio"]
autodoc_mock_imports = ["fontio"]
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = u'Adafruit Bitmap_Font Library'
copyright = u'2019 Scott Shawcroft'
author = u'Scott Shawcroft'
project = "Adafruit Bitmap_Font Library"
copyright = "2019 Scott Shawcroft"
author = "Scott Shawcroft"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0'
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = u'1.0'
release = "1.0"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@ -57,7 +61,7 @@ language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
@ -69,7 +73,7 @@ default_role = "any"
add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
@ -84,32 +88,33 @@ napoleon_numpy_docstring = False
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except:
html_theme = 'default'
html_theme_path = ['.']
html_theme = "default"
html_theme_path = ["."]
else:
html_theme_path = ['.']
html_theme_path = ["."]
# 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']
html_static_path = ["_static"]
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = '_static/favicon.ico'
html_favicon = "_static/favicon.ico"
# Output file base name for HTML help builder.
htmlhelp_basename = 'AdafruitBitmap_fontLibrarydoc'
htmlhelp_basename = "AdafruitBitmap_fontLibrarydoc"
# -- Options for LaTeX output ---------------------------------------------
@ -117,15 +122,12 @@ 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',
@ -135,8 +137,13 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'AdafruitBitmap_FontLibrary.tex', u'AdafruitBitmap_Font Library Documentation',
author, 'manual'),
(
master_doc,
"AdafruitBitmap_FontLibrary.tex",
"AdafruitBitmap_Font Library Documentation",
author,
"manual",
),
]
# -- Options for manual page output ---------------------------------------
@ -144,8 +151,13 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'AdafruitBitmap_Fontlibrary', u'Adafruit Bitmap_Font Library Documentation',
[author], 1)
(
master_doc,
"AdafruitBitmap_Fontlibrary",
"Adafruit Bitmap_Font Library Documentation",
[author],
1,
)
]
# -- Options for Texinfo output -------------------------------------------
@ -154,7 +166,13 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'AdafruitBitmap_FontLibrary', u'Adafruit Bitmap_Font Library Documentation',
author, 'AdafruitBitmap_FontLibrary', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"AdafruitBitmap_FontLibrary",
"Adafruit Bitmap_Font Library Documentation",
author,
"AdafruitBitmap_FontLibrary",
"One line description of project.",
"Miscellaneous",
),
]

View file

@ -0,0 +1,65 @@
"""
This example runs on PyPortal, or any Circuit Python device
with a built-in screen that is at least 320x240 pixels.
It will use adafruit_bitmap_font to load a font and fill a
bitmap with pixels matching glyphs from a given String
"""
import board
from adafruit_bitmap_font import bitmap_font # pylint: disable=wrong-import-position
import displayio
font = bitmap_font.load_font("fonts/Arial-16.bdf")
bitmap = displayio.Bitmap(320, 240, 2)
palette = displayio.Palette(2)
palette[0] = 0x000000
palette[1] = 0xFFFFFF
_, height, _, dy = font.get_bounding_box()
for y in range(height):
pixels = []
for c in "Adafruit CircuitPython":
glyph = font.get_glyph(ord(c))
if not glyph:
continue
glyph_y = y + (glyph.height - (height + dy)) + glyph.dy
if 0 <= glyph_y < glyph.height:
for i in range(glyph.width):
value = glyph.bitmap[i, glyph_y]
pixel = 0
if value > 0:
pixel = 1
pixels.append(pixel)
else:
# empty section for this glyph
for i in range(glyph.width):
pixels.append(0)
# one space between glyph
pixels.append(0)
if pixels:
for x, pixel in enumerate(pixels):
bitmap[x, y] = pixel
# Create a TileGrid to hold the bitmap
tile_grid = displayio.TileGrid(bitmap, pixel_shader=palette)
# Create a Group to hold the TileGrid
group = displayio.Group()
group.x = 20
# Add the TileGrid to the Group
group.append(tile_grid)
# Add the Group to the Display
board.DISPLAY.show(group)
while True:
pass

View file

@ -0,0 +1,28 @@
"""
This example uses addfruit_display_text.label to display text using a custom font
loaded by adafruit_bitmap_font
"""
import board
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
display = board.DISPLAY
# Set text, font, and color
text = "HELLO WORLD"
font = bitmap_font.load_font("fonts/Arial-16.bdf")
color = 0xFF00FF
# Create the tet label
text_area = label.Label(font, text=text, color=color)
# Set the location
text_area.x = 20
text_area.y = 20
# Show it
display.show(text_area)
while True:
pass

View file

@ -3,8 +3,11 @@
import os
import sys
from adafruit_bitmap_font import bitmap_font
sys.path.append(os.path.join(sys.path[0], "test"))
# Add paths so this runs in CPython in-place.
sys.path.append(os.path.join(sys.path[0], ".."))
from adafruit_bitmap_font import bitmap_font # pylint: disable=wrong-import-position
sys.path.append(os.path.join(sys.path[0], "../test"))
font = bitmap_font.load_font(sys.argv[1])
_, height, _, dy = font.get_bounding_box()

7366
examples/fonts/Arial-16.bdf Normal file

File diff suppressed because it is too large Load diff

View file

@ -6,6 +6,7 @@ https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
@ -13,51 +14,40 @@ from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
with open(path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
setup(
name='adafruit-circuitpython-bitmap_font',
name="adafruit-circuitpython-bitmap_font",
use_scm_version=True,
setup_requires=['setuptools_scm'],
description='Loads bitmap fonts into CircuitPython displayio.',
setup_requires=["setuptools_scm"],
description="Loads bitmap fonts into CircuitPython displayio.",
long_description=long_description,
long_description_content_type='text/x-rst',
long_description_content_type="text/x-rst",
# The project's main homepage.
url='https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font',
url="https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font",
# Author details
author='Adafruit Industries',
author_email='circuitpython@adafruit.com',
install_requires=[
'Adafruit-Blinka'
],
author="Adafruit Industries",
author_email="circuitpython@adafruit.com",
install_requires=["Adafruit-Blinka"],
# Choose your license
license='MIT',
license="MIT",
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Hardware',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"Topic :: System :: Hardware",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
# What does your project relate to?
keywords='adafruit blinka circuitpython micropython font text displayio bitmap',
keywords="adafruit blinka circuitpython micropython font text displayio bitmap",
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER,
# CHANGE `py_modules=['...']` TO `packages=['...']`
py_modules=['adafruit_bitmap_font'],
packages=["adafruit_bitmap_font"],
)

View file

@ -1,5 +1,3 @@
import collections
class Bitmap:
def __init__(self, width, height, color_count):
self.width = width
@ -20,5 +18,3 @@ class Bitmap:
def __len__(self):
return self.width * self.height
Glyph = collections.namedtuple("Glyph", ["bitmap", "tile_index", "width", "height", "dx", "dy", "shift_x", "shift_y"])

6
test/fontio.py Normal file
View file

@ -0,0 +1,6 @@
import collections
Glyph = collections.namedtuple(
"Glyph",
["bitmap", "tile_index", "width", "height", "dx", "dy", "shift_x", "shift_y"],
)