Compare commits

..

No commits in common. "master" and "kattni-patch-1" have entirely different histories.

20 changed files with 226 additions and 7776 deletions

View file

@ -1,57 +0,0 @@
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

View file

@ -1,81 +0,0 @@
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,10 +4,12 @@ __pycache__
_build _build
*.pyc *.pyc
.env .env
build*
bundles bundles
*.DS_Store *.DS_Store
.eggs .eggs
dist dist
**/*.egg-info **/*.egg-info
*.bdf
*.pcf *.pcf
*.ttf *.ttf

View file

@ -52,7 +52,7 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes # no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W" # --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=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,bad-continuation 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
# Enable the message, report, category or checker with the given id(s). You can # 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 # either give multiple identifier separated by comma (,) or put this option

39
.travis.yml Normal file
View file

@ -0,0 +1,39 @@
# 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,8 +34,6 @@ Examples of unacceptable behavior by participants include:
* Excessive or unwelcome helping; answering outside the scope of the question * Excessive or unwelcome helping; answering outside the scope of the question
asked asked
* Trolling, insulting/derogatory comments, and personal or political attacks * 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 * Public or private harassment
* Publishing others' private information, such as a physical or electronic * Publishing others' private information, such as a physical or electronic
address, without explicit permission address, without explicit permission
@ -74,10 +72,10 @@ You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>. 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 On the Adafruit Discord, you may send an open message from any channel
to all Community Moderators by tagging @community moderators. You may to all Community Helpers by tagging @community helpers. You may also send an
also send an open message from any channel, or a direct message to open message from any channel, or a direct message to @kattni#1507,
@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, @tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. @Andon#8175.
Email and direct message reports will be kept confidential. 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 .. 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 :alt: Documentation Status
.. image:: https://img.shields.io/discord/327254708534116352.svg .. image:: https://img.shields.io/discord/327254708534116352.svg
:target: https://adafru.it/discord :target: https://discord.gg/nBQh6qu
:alt: Discord :alt: Discord
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/workflows/Build%20CI/badge.svg .. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.svg?branch=master
:target: https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/actions/ :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Bitmap_Font
:alt: Build Status :alt: Build Status
Loads bitmap fonts into CircuitPython's displayio. BDF files are well supported. PCF and TTF Loads bitmap fonts into CircuitPython's displayio. BDF files are well supported. PCF and TTF
@ -68,7 +68,52 @@ Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/blob/master/CODE_OF_CONDUCT.md>`_ <https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/blob/master/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming. before contributing to help this project stay welcoming.
Documentation Building locally
============= ================
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>`_. 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.

View file

@ -40,16 +40,14 @@ Implementation Notes
""" """
import gc import gc
from fontio import Glyph from displayio import Glyph
from .glyph_cache import GlyphCache from .glyph_cache import GlyphCache
__version__ = "0.0.0-auto.0" __version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
class BDF(GlyphCache): class BDF(GlyphCache):
"""Loads glyphs from a BDF file in the given bitmap_class.""" """Loads glyphs from a BDF file in the given bitmap_class."""
def __init__(self, f, bitmap_class): def __init__(self, f, bitmap_class):
super().__init__() super().__init__()
self.file = f self.file = f
@ -88,20 +86,7 @@ class BDF(GlyphCache):
current_info = {} current_info = {}
current_y = 0 current_y = 0
rounded_x = 1 rounded_x = 1
if isinstance(code_points, int): total_remaining = len(code_points)
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() x, _, _, _ = self.get_bounding_box()
@ -118,26 +103,23 @@ class BDF(GlyphCache):
pass pass
elif line.startswith(b"STARTCHAR"): elif line.startswith(b"STARTCHAR"):
# print(lineno, line.strip()) # print(lineno, line.strip())
# _, character_name = line.split() #_, character_name = line.split()
character = True character = True
elif line.startswith(b"ENDCHAR"): elif line.startswith(b"ENDCHAR"):
character = False character = False
if desired_character: if desired_character:
bounds = current_info["bounds"] bounds = current_info["bounds"]
shift = current_info["shift"] shift = current_info["shift"]
self._glyphs[code_point] = Glyph(current_info["bitmap"],
0,
bounds[0],
bounds[1],
bounds[2],
bounds[3],
shift[0],
shift[1])
gc.collect() gc.collect()
self._glyphs[code_point] = Glyph( if total_remaining == 0:
current_info["bitmap"],
0,
bounds[0],
bounds[1],
bounds[2],
bounds[3],
shift[0],
shift[1],
)
remaining.remove(code_point)
if not remaining:
return return
desired_character = False desired_character = False
elif line.startswith(b"BBX"): elif line.startswith(b"BBX"):
@ -161,9 +143,11 @@ class BDF(GlyphCache):
elif line.startswith(b"ENCODING"): elif line.startswith(b"ENCODING"):
_, code_point = line.split() _, code_point = line.split()
code_point = int(code_point) code_point = int(code_point)
if code_point in remaining: if code_point == code_points or code_point in code_points:
desired_character = True total_remaining -= 1
current_info = {"bitmap": None, "bounds": None, "shift": None} if code_point not in self._glyphs or not self._glyphs[code_point]:
desired_character = True
current_info = {"bitmap": None, "bounds": None, "shift": None}
elif line.startswith(b"DWIDTH"): elif line.startswith(b"DWIDTH"):
if desired_character: if desired_character:
_, shift_x, shift_y = line.split() _, shift_x, shift_y = line.split()
@ -179,7 +163,7 @@ class BDF(GlyphCache):
start = current_y * width start = current_y * width
x = 0 x = 0
for i in range(rounded_x): for i in range(rounded_x):
val = (bits >> ((rounded_x - i - 1) * 8)) & 0xFF val = (bits >> ((rounded_x-i-1)*8)) & 0xFF
for j in range(7, -1, -1): for j in range(7, -1, -1):
if x >= width: if x >= width:
break break
@ -190,5 +174,5 @@ class BDF(GlyphCache):
x += 1 x += 1
current_y += 1 current_y += 1
elif metadata: elif metadata:
# print(lineno, line.strip()) #print(lineno, line.strip())
pass pass

View file

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

View file

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

View file

@ -5,29 +5,28 @@ from .glyph_cache import GlyphCache
import displayio import displayio
import struct import struct
_PCF_PROPERTIES = 1 << 0 _PCF_PROPERTIES = (1<<0)
_PCF_ACCELERATORS = 1 << 1 _PCF_ACCELERATORS = (1<<1)
_PCF_METRICS = 1 << 2 _PCF_METRICS = (1<<2)
_PCF_BITMAPS = 1 << 3 _PCF_BITMAPS = (1<<3)
_PCF_INK_METRICS = 1 << 4 _PCF_INK_METRICS = (1<<4)
_PCF_BDF_ENCODINGS = 1 << 5 _PCF_BDF_ENCODINGS = (1<<5)
_PCF_SWIDTHS = 1 << 6 _PCF_SWIDTHS = (1<<6)
_PCF_GLYPH_NAMES = 1 << 7 _PCF_GLYPH_NAMES = (1<<7)
_PCF_BDF_ACCELERATORS = 1 << 8 _PCF_BDF_ACCELERATORS = (1<<8)
_PCF_DEFAULT_FORMAT = 0x00000000 _PCF_DEFAULT_FORMAT = 0x00000000
_PCF_INKBOUNDS = 0x00000200 _PCF_INKBOUNDS = 0x00000200
_PCF_ACCEL_W_INKBOUNDS = 0x00000100 _PCF_ACCEL_W_INKBOUNDS = 0x00000100
_PCF_COMPRESSED_METRICS = 0x00000100 _PCF_COMPRESSED_METRICS = 0x00000100
_PCF_GLYPH_PAD_MASK = 3 << 0 # See the bitmap table for explanation */ _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_BYTE_MASK = (1<<2) # If set then Most Sig Byte First */
_PCF_BIT_MASK = 1 << 3 # If set then Most Sig Bit First */ _PCF_BIT_MASK = (1<<3) # If set then Most Sig Bit First */
_PCF_SCAN_UNIT_MASK = 3 << 4 _PCF_SCAN_UNIT_MASK = (3<<4)
# https://fontforge.github.io/en-US/documentation/reference/pcf-format/ # https://fontforge.github.io/en-US/documentation/reference/pcf-format/
class PCF(GlyphCache): class PCF(GlyphCache):
def __init__(self, f): def __init__(self, f):
super().__init__() super().__init__()
@ -48,17 +47,17 @@ class PCF(GlyphCache):
def get_bounding_box(self): def get_bounding_box(self):
property_table_offset = self.tables[_PCF_PROPERTIES]["offset"] property_table_offset = self.tables[_PCF_PROPERTIES]["offset"]
self.file.seek(property_table_offset) self.file.seek(property_table_offset)
(format,) = self.read("<I") format, = self.read("<I")
if format & _PCF_BYTE_MASK == 0: if format & _PCF_BYTE_MASK == 0:
raise RuntimeError("Only big endian supported") raise RuntimeError("Only big endian supported")
(nprops,) = self.read(">I") nprops, = self.read(">I")
self.file.seek(property_table_offset + 8 + 9 * nprops) self.file.seek(property_table_offset + 8 + 9 * nprops)
pos = self.file.tell() pos = self.file.tell()
if pos % 4 > 0: if pos % 4 > 0:
self.file.read(4 - pos % 4) self.file.read(4 - pos % 4)
(string_size,) = self.read(">I") string_size, = self.read(">I")
strings = self.file.read(string_size) strings = self.file.read(string_size)
string_map = {} string_map = {}
@ -90,7 +89,7 @@ class PCF(GlyphCache):
x, _, _, _ = self.get_bounding_box() x, _, _, _ = self.get_bounding_box()
# create a scratch bytearray to load pixels into # create a scratch bytearray to load pixels into
scratch_row = memoryview(bytearray((((x - 1) // 32) + 1) * 4)) scratch_row = memoryview(bytearray((((x-1)//32)+1) * 4))
self.file.seek(0) self.file.seek(0)
while True: while True:
@ -105,7 +104,7 @@ class PCF(GlyphCache):
pass pass
elif line.startswith(b"STARTCHAR"): elif line.startswith(b"STARTCHAR"):
# print(lineno, line.strip()) # print(lineno, line.strip())
# _, character_name = line.split() #_, character_name = line.split()
character = True character = True
elif line.startswith(b"ENDCHAR"): elif line.startswith(b"ENDCHAR"):
character = False character = False
@ -152,12 +151,10 @@ class PCF(GlyphCache):
if desired_character: if desired_character:
bits = int(line.strip(), 16) bits = int(line.strip(), 16)
for i in range(rounded_x): for i in range(rounded_x):
val = (bits >> ((rounded_x - i - 1) * 8)) & 0xFF val = (bits >> ((rounded_x-i-1)*8)) & 0xFF
scratch_row[i] = val scratch_row[i] = val
current_info["bitmap"]._load_row( current_info["bitmap"]._load_row(current_y, scratch_row[:bytes_per_row])
current_y, scratch_row[:bytes_per_row]
)
current_y += 1 current_y += 1
elif metadata: elif metadata:
# print(lineno, line.strip()) #print(lineno, line.strip())
pass pass

View file

@ -6,7 +6,6 @@ import struct
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
class TTF: class TTF:
def __init__(self, f): def __init__(self, f):
f.seek(0) f.seek(0)
@ -42,7 +41,7 @@ class TTF:
while f.tell() < glyf_offset + glyf_length: while f.tell() < glyf_offset + glyf_length:
numberOfContours, xMin, yMin, xMax, yMax = read(">hhhhh") numberOfContours, xMin, yMin, xMax, yMax = read(">hhhhh")
if numberOfContours > 0: # Simple if numberOfContours > 0: # Simple
print(numberOfContours) print(numberOfContours)
ends = [] ends = []
for _ in range(numberOfContours): for _ in range(numberOfContours):

View file

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

View file

@ -1,65 +0,0 @@
"""
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

@ -1,28 +0,0 @@
"""
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,11 +3,8 @@
import os import os
import sys import sys
# Add paths so this runs in CPython in-place. from adafruit_bitmap_font import bitmap_font
sys.path.append(os.path.join(sys.path[0], "..")) sys.path.append(os.path.join(sys.path[0], "test"))
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]) font = bitmap_font.load_font(sys.argv[1])
_, height, _, dy = font.get_bounding_box() _, height, _, dy = font.get_bounding_box()

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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