diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
index 71ef8f8..8de294e 100644
--- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
+++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
@@ -4,7 +4,7 @@
Thank you for contributing! Before you submit a pull request, please read the following.
-Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://circuitpython.readthedocs.io/en/latest/docs/design_guide.html
+Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html
If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index ca35544..041a337 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -10,66 +10,5 @@ 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.7
- uses: actions/setup-python@v1
- with:
- python-version: 3.7
- - 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 Sphinx, pre-commit
- run: |
- pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit
- - name: Library version
- run: git describe --dirty --always --tags
- - name: Pre-commit hooks
- run: |
- pre-commit run --all-files
- - name: Build assets
- run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- - name: Archive bundles
- uses: actions/upload-artifact@v2
- with:
- name: bundles
- path: ${{ github.workspace }}/bundles/
- - name: Build docs
- working-directory: docs
- run: sphinx-build -E -W -b html . _build/html
- - name: Check For setup.py
- id: need-pypi
- run: |
- echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
- - name: Build Python package
- if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
- run: |
- pip install --upgrade setuptools wheel twine readme_renderer testresources
- python setup.py sdist
- python setup.py bdist_wheel --universal
- twine check dist/*
- - name: Setup problem matchers
- uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1
+ - name: Run Build CI workflow
+ uses: adafruit/workflows-circuitpython-libs/build@main
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
deleted file mode 100644
index 6d0015a..0000000
--- a/.github/workflows/release.yml
+++ /dev/null
@@ -1,85 +0,0 @@
-# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
-#
-# SPDX-License-Identifier: MIT
-
-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/*
diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml
new file mode 100644
index 0000000..9acec60
--- /dev/null
+++ b/.github/workflows/release_gh.yml
@@ -0,0 +1,19 @@
+# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+
+name: GitHub Release Actions
+
+on:
+ release:
+ types: [published]
+
+jobs:
+ upload-release-assets:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Run GitHub Release CI workflow
+ uses: adafruit/workflows-circuitpython-libs/release-gh@main
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ upload-url: ${{ github.event.release.upload_url }}
diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml
new file mode 100644
index 0000000..65775b7
--- /dev/null
+++ b/.github/workflows/release_pypi.yml
@@ -0,0 +1,19 @@
+# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+
+name: PyPI Release Actions
+
+on:
+ release:
+ types: [published]
+
+jobs:
+ upload-release-assets:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Run PyPI Release CI workflow
+ uses: adafruit/workflows-circuitpython-libs/release-pypi@main
+ with:
+ pypi-username: ${{ secrets.pypi_username }}
+ pypi-password: ${{ secrets.pypi_password }}
diff --git a/.gitignore b/.gitignore
index 5865216..db3d538 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,18 +1,48 @@
-# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
+# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries
#
-# SPDX-License-Identifier: Unlicense
+# SPDX-License-Identifier: MIT
+# Do not include files and directories created by your personal work environment, such as the IDE
+# you use, except for those already listed here. Pull requests including changes to this file will
+# not be accepted.
+
+# This .gitignore file contains rules for files generated by working with CircuitPython libraries,
+# including building Sphinx, testing with pip, and creating a virual environment, as well as the
+# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs.
+
+# If you find that there are files being generated on your machine that should not be included in
+# your git commit, you should create a .gitignore_global file on your computer to include the
+# files created by your personal setup. To do so, follow the two steps below.
+
+# First, create a file called .gitignore_global somewhere convenient for you, and add rules for
+# the files you want to exclude from git commits.
+
+# Second, configure Git to use the exclude file for all Git repositories by running the
+# following via commandline, replacing "path/to/your/" with the actual path to your newly created
+# .gitignore_global file:
+# git config --global core.excludesfile path/to/your/.gitignore_global
+
+# CircuitPython-specific files
+*.mpy
+
+# Python-specific files
__pycache__
-_build
*.pyc
+
+# Sphinx build-specific files
+_build
+
+# This file results from running `pip -e install .` in a local repository
+*.egg-info
+
+# Virtual environment-specific files
.env
-bundles
-.idea/
-venv/
+.venv
+
+# MacOS-specific files
+*.DS_Store
+
+# IDE-specific files
+.idea
.vscode
-.DS_STORE
-develop-eggs/
-eggs/
-.eggs/
-*.egg-info/
-*.egg
+*~
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 1b9fadc..f27b786 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,42 +1,22 @@
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
+# SPDX-FileCopyrightText: 2024 Justin Myers
#
# SPDX-License-Identifier: Unlicense
repos:
-- repo: https://github.com/python/black
- rev: 20.8b1
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.5.0
hooks:
- - id: black
-- repo: https://github.com/fsfe/reuse-tool
- rev: v0.12.1
+ - id: check-yaml
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ rev: v0.3.4
hooks:
- - id: reuse
-- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v2.3.0
+ - id: ruff-format
+ - id: ruff
+ args: ["--fix"]
+ - repo: https://github.com/fsfe/reuse-tool
+ rev: v3.0.1
hooks:
- - id: check-yaml
- - id: end-of-file-fixer
- - id: trailing-whitespace
-- repo: https://github.com/pycqa/pylint
- rev: v2.11.1
- hooks:
- - id: pylint
- name: pylint (library code)
- types: [python]
- args:
- - --disable=consider-using-f-string
- exclude: "^(docs/|examples/|tests/|setup.py$)"
- - id: pylint
- name: pylint (example code)
- description: Run pylint rules on "examples/*.py" files
- types: [python]
- files: "^examples/"
- args:
- - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code
- - id: pylint
- name: pylint (test code)
- description: Run pylint rules on "tests/*.py" files
- types: [python]
- files: "^tests/"
- args:
- - --disable=missing-docstring,consider-using-f-string,duplicate-code
+ - id: reuse
diff --git a/.pylintrc b/.pylintrc
deleted file mode 100644
index b86962e..0000000
--- a/.pylintrc
+++ /dev/null
@@ -1,436 +0,0 @@
-# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
-#
-# SPDX-License-Identifier: Unlicense
-
-[MASTER]
-
-# A comma-separated list of package or module names from where C extensions may
-# be loaded. Extensions are loading into the active Python interpreter and may
-# run arbitrary code
-extension-pkg-whitelist=
-
-# Add files or directories to the blacklist. They should be base names, not
-# paths.
-ignore=CVS,adafruit_imageload/tests
-
-# Add files or directories matching the regex patterns to the blacklist. The
-# regex matches against base names, not paths.
-ignore-patterns=
-
-# Python code to execute, usually for sys.path manipulation such as
-# pygtk.require().
-#init-hook=
-
-# Use multiple processes to speed up Pylint.
-jobs=1
-
-# List of plugins (as comma separated values of python modules names) to load,
-# usually to register additional checkers.
-load-plugins=
-
-# Pickle collected data for later comparisons.
-persistent=yes
-
-# Specify a configuration file.
-#rcfile=
-
-# Allow loading of arbitrary C extensions. Extensions are imported into the
-# active Python interpreter and may run arbitrary code.
-unsafe-load-any-extension=no
-
-
-[MESSAGES CONTROL]
-
-# Only show warnings with the listed confidence levels. Leave empty to show
-# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
-confidence=
-
-# Disable the message, report, category or checker with the given id(s). You
-# can either give multiple identifiers separated by comma (,) or put this
-# option multiple times (only on the command line, not in the configuration
-# file where it should appear only once).You can also use "--disable=all" to
-# disable everything first and then reenable specific checks. For example, if
-# you want to run only the similarities checker, you can use "--disable=all
-# --enable=similarities". If you want to run only the classes checker, but have
-# 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,bad-continuation,unspecified-encoding
-
-# 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
-# multiple time (only on the command line, not in the configuration file where
-# it should appear only once). See also the "--disable" option for examples.
-enable=
-
-
-[REPORTS]
-
-# Python expression which should return a note less than 10 (10 is the highest
-# note). You have access to the variables errors warning, statement which
-# respectively contain the number of errors / warnings messages and the total
-# number of statements analyzed. This is used by the global evaluation report
-# (RP0004).
-evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
-
-# Template used to display messages. This is a python new-style format string
-# used to format the message information. See doc for all details
-#msg-template=
-
-# Set the output format. Available formats are text, parseable, colorized, json
-# and msvs (visual studio).You can also give a reporter class, eg
-# mypackage.mymodule.MyReporterClass.
-output-format=text
-
-# Tells whether to display a full report or only the messages
-reports=no
-
-# Activate the evaluation score.
-score=yes
-
-
-[REFACTORING]
-
-# Maximum number of nested blocks for function / method body
-max-nested-blocks=5
-
-
-[LOGGING]
-
-# Logging modules to check that the string format arguments are in logging
-# function parameter format
-logging-modules=logging
-
-
-[SPELLING]
-
-# Spelling dictionary name. Available dictionaries: none. To make it working
-# install python-enchant package.
-spelling-dict=
-
-# List of comma separated words that should not be checked.
-spelling-ignore-words=
-
-# A path to a file that contains private dictionary; one word per line.
-spelling-private-dict-file=
-
-# Tells whether to store unknown words to indicated private dictionary in
-# --spelling-private-dict-file option instead of raising a message.
-spelling-store-unknown-words=no
-
-
-[MISCELLANEOUS]
-
-# List of note tags to take in consideration, separated by a comma.
-# notes=FIXME,XXX,TODO
-notes=FIXME,XXX
-
-
-[TYPECHECK]
-
-# List of decorators that produce context managers, such as
-# contextlib.contextmanager. Add to this list to register other decorators that
-# produce valid context managers.
-contextmanager-decorators=contextlib.contextmanager
-
-# List of members which are set dynamically and missed by pylint inference
-# system, and so shouldn't trigger E1101 when accessed. Python regular
-# expressions are accepted.
-generated-members=
-
-# Tells whether missing members accessed in mixin class should be ignored. A
-# mixin class is detected if its name ends with "mixin" (case insensitive).
-ignore-mixin-members=yes
-
-# This flag controls whether pylint should warn about no-member and similar
-# checks whenever an opaque object is returned when inferring. The inference
-# can return multiple potential results while evaluating a Python object, but
-# some branches might not be evaluated, which results in partial inference. In
-# that case, it might be useful to still emit no-member and other checks for
-# the rest of the inferred objects.
-ignore-on-opaque-inference=yes
-
-# List of class names for which member attributes should not be checked (useful
-# for classes with dynamically set attributes). This supports the use of
-# qualified names.
-ignored-classes=optparse.Values,thread._local,_thread._local
-
-# List of module names for which member attributes should not be checked
-# (useful for modules/projects where namespaces are manipulated during runtime
-# and thus existing member attributes cannot be deduced by static analysis. It
-# supports qualified module names, as well as Unix pattern matching.
-ignored-modules=board
-
-# Show a hint with possible names when a member name was not found. The aspect
-# of finding the hint is based on edit distance.
-missing-member-hint=yes
-
-# The minimum edit distance a name should have in order to be considered a
-# similar match for a missing member name.
-missing-member-hint-distance=1
-
-# The total number of similar names that should be taken in consideration when
-# showing a hint for a missing member.
-missing-member-max-choices=1
-
-
-[VARIABLES]
-
-# List of additional names supposed to be defined in builtins. Remember that
-# you should avoid to define new builtins when possible.
-additional-builtins=
-
-# Tells whether unused global variables should be treated as a violation.
-allow-global-unused-variables=yes
-
-# List of strings which can identify a callback function by name. A callback
-# name must start or end with one of those strings.
-callbacks=cb_,_cb
-
-# A regular expression matching the name of dummy variables (i.e. expectedly
-# not used).
-dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
-
-# Argument names that match this expression will be ignored. Default to name
-# with leading underscore
-ignored-argument-names=_.*|^ignored_|^unused_
-
-# Tells whether we should check for unused import in __init__ files.
-init-import=no
-
-# List of qualified module names which can have objects that can redefine
-# builtins.
-redefining-builtins-modules=six.moves,future.builtins
-
-
-[FORMAT]
-
-# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
-# expected-line-ending-format=
-expected-line-ending-format=LF
-
-# Regexp for a line that is allowed to be longer than the limit.
-ignore-long-lines=^\s*(# )??$
-
-# Number of spaces of indent required inside a hanging or continued line.
-indent-after-paren=4
-
-# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
-# tab).
-indent-string=' '
-
-# Maximum number of characters on a single line.
-max-line-length=100
-
-# Maximum number of lines in a module
-max-module-lines=1000
-
-# List of optional constructs for which whitespace checking is disabled. `dict-
-# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
-# `trailing-comma` allows a space between comma and closing bracket: (a, ).
-# `empty-line` allows space-only lines.
-no-space-check=trailing-comma,dict-separator
-
-# Allow the body of a class to be on the same line as the declaration if body
-# contains single statement.
-single-line-class-stmt=no
-
-# Allow the body of an if to be on the same line as the test if there is no
-# else.
-single-line-if-stmt=no
-
-
-[SIMILARITIES]
-
-# Ignore comments when computing similarities.
-ignore-comments=yes
-
-# Ignore docstrings when computing similarities.
-ignore-docstrings=yes
-
-# Ignore imports when computing similarities.
-ignore-imports=yes
-
-# Minimum lines number of a similarity.
-min-similarity-lines=4
-
-
-[BASIC]
-
-# Naming hint for argument names
-argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct argument names
-argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Naming hint for attribute names
-attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct attribute names
-attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Bad variable names which should always be refused, separated by a comma
-bad-names=foo,bar,baz,toto,tutu,tata
-
-# Naming hint for class attribute names
-class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
-
-# Regular expression matching correct class attribute names
-class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
-
-# Naming hint for class names
-# class-name-hint=[A-Z_][a-zA-Z0-9]+$
-class-name-hint=[A-Z_][a-zA-Z0-9_]+$
-
-# Regular expression matching correct class names
-# class-rgx=[A-Z_][a-zA-Z0-9]+$
-class-rgx=[A-Z_][a-zA-Z0-9_]+$
-
-# Naming hint for constant names
-const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
-
-# Regular expression matching correct constant names
-const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
-
-# Minimum line length for functions/classes that require docstrings, shorter
-# ones are exempt.
-docstring-min-length=-1
-
-# Naming hint for function names
-function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct function names
-function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Good variable names which should always be accepted, separated by a comma
-# good-names=i,j,k,ex,Run,_
-good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_
-
-# Include a hint for the correct naming format with invalid-name
-include-naming-hint=no
-
-# Naming hint for inline iteration names
-inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
-
-# Regular expression matching correct inline iteration names
-inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
-
-# Naming hint for method names
-method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct method names
-method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Naming hint for module names
-module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
-
-# Regular expression matching correct module names
-module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
-
-# Colon-delimited sets of names that determine each other's naming style when
-# the name regexes allow several styles.
-name-group=
-
-# Regular expression which should only match function or class names that do
-# not require a docstring.
-no-docstring-rgx=^_
-
-# List of decorators that produce properties, such as abc.abstractproperty. Add
-# to this list to register other decorators that produce valid properties.
-property-classes=abc.abstractproperty
-
-# Naming hint for variable names
-variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct variable names
-variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-
-[IMPORTS]
-
-# Allow wildcard imports from modules that define __all__.
-allow-wildcard-with-all=no
-
-# Analyse import fallback blocks. This can be used to support both Python 2 and
-# 3 compatible code, which means that the block might have code that exists
-# only in one or another interpreter, leading to false positives when analysed.
-analyse-fallback-blocks=no
-
-# Deprecated modules which should not be used, separated by a comma
-deprecated-modules=optparse,tkinter.tix
-
-# Create a graph of external dependencies in the given file (report RP0402 must
-# not be disabled)
-ext-import-graph=
-
-# Create a graph of every (i.e. internal and external) dependencies in the
-# given file (report RP0402 must not be disabled)
-import-graph=
-
-# Create a graph of internal dependencies in the given file (report RP0402 must
-# not be disabled)
-int-import-graph=
-
-# Force import order to recognize a module as part of the standard
-# compatibility libraries.
-known-standard-library=
-
-# Force import order to recognize a module as part of a third party library.
-known-third-party=enchant
-
-
-[CLASSES]
-
-# List of method names used to declare (i.e. assign) instance attributes.
-defining-attr-methods=__init__,__new__,setUp
-
-# List of member names, which should be excluded from the protected access
-# warning.
-exclude-protected=_asdict,_fields,_replace,_source,_make
-
-# List of valid names for the first argument in a class method.
-valid-classmethod-first-arg=cls
-
-# List of valid names for the first argument in a metaclass class method.
-valid-metaclass-classmethod-first-arg=mcs
-
-
-[DESIGN]
-
-# Maximum number of arguments for function / method
-max-args=5
-
-# Maximum number of attributes for a class (see R0902).
-# max-attributes=7
-max-attributes=11
-
-# Maximum number of boolean expressions in a if statement
-max-bool-expr=5
-
-# Maximum number of branch for function / method body
-max-branches=12
-
-# Maximum number of locals for function / method body
-max-locals=15
-
-# Maximum number of parents for a class (see R0901).
-max-parents=7
-
-# Maximum number of public methods for a class (see R0904).
-max-public-methods=20
-
-# Maximum number of return / yield for function / method body
-max-returns=6
-
-# Maximum number of statements in function / method body
-max-statements=50
-
-# Minimum number of public methods for a class (see R0903).
-min-public-methods=1
-
-
-[EXCEPTIONS]
-
-# Exceptions that will emit a warning when being caught. Defaults to
-# "Exception"
-overgeneral-exceptions=Exception
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
index 95ec218..88bca9f 100644
--- a/.readthedocs.yaml
+++ b/.readthedocs.yaml
@@ -8,8 +8,15 @@
# Required
version: 2
+sphinx:
+ configuration: docs/conf.py
+
+build:
+ os: ubuntu-20.04
+ tools:
+ python: "3"
+
python:
- version: "3.6"
install:
- requirements: docs/requirements.txt
- requirements: requirements.txt
diff --git a/README.rst b/README.rst
index 3ff633e..c698f93 100644
--- a/README.rst
+++ b/README.rst
@@ -2,10 +2,10 @@ Introduction
============
.. image:: https://readthedocs.org/projects/adafruit-circuitpython-imageload/badge/?version=latest
- :target: https://circuitpython.readthedocs.io/projects/imageload/en/latest/
+ :target: https://docs.circuitpython.org/projects/imageload/en/latest/
:alt: Documentation Status
-.. image:: https://img.shields.io/discord/327254708534116352.svg
+.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg
:target: https://adafru.it/discord
:alt: Discord
@@ -13,6 +13,10 @@ Introduction
:target: https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad/actions/
:alt: Build Status
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
+ :target: https://github.com/astral-sh/ruff
+ :alt: Code Style: Ruff
+
This library decodes an image file into new bitmap and palette objects of the provided type. It's
designed to load code needed during decoding as needed. This is meant to minimize the memory
overhead of the decoding code.
@@ -36,8 +40,7 @@ Usage Example
group = displayio.Group()
group.append(tile_grid)
- board.DISPLAY.show(group)
-
+ board.DISPLAY.root_group = group
while True:
pass
@@ -45,7 +48,9 @@ Usage Example
Documentation
=============
-API documentation for this library can be found on `Read the Docs `_.
+API documentation for this library can be found on `Read the Docs `_.
+
+For information on building library documentation, please check out `this guide `_.
Contributing
============
@@ -53,8 +58,3 @@ Contributing
Contributions are welcome! Please read our `Code of Conduct
`_
before contributing to help this project stay welcoming.
-
-Documentation
-=============
-
-For information on building library documentation, please check out `this guide `_.
diff --git a/adafruit_imageload/__init__.py b/adafruit_imageload/__init__.py
index 23e7151..e149c41 100644
--- a/adafruit_imageload/__init__.py
+++ b/adafruit_imageload/__init__.py
@@ -1,4 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
#
# SPDX-License-Identifier: MIT
@@ -8,22 +9,43 @@
Load pixel values (indices or colors) into a bitmap and colors into a palette.
-* Author(s): Scott Shawcroft
+* Author(s): Scott Shawcroft, Matt Land
"""
-# pylint: disable=import-outside-toplevel
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import (
+ Iterable,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ )
+
+ from displayio import Bitmap, ColorConverter, Palette
+
+ from .displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file_or_filename, *, bitmap=None, palette=None):
+def load(
+ file_or_filename: Union[str, BufferedReader],
+ *,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Bitmap, Optional[Union[Palette, ColorConverter]]]:
"""Load pixel values (indices or colors) into a bitmap and colors into a palette.
bitmap is the desired type. It must take width, height and color_depth in the constructor. It
must also have a _load_row method to load a row's worth of pixel data.
- palette is the desired pallete type. The constructor should take the number of colors and
+ palette is the desired palette type. The constructor should take the number of colors and
support assignment to indices via [].
"""
if not bitmap or not palette:
@@ -56,7 +78,20 @@ def load(file_or_filename, *, bitmap=None, palette=None):
return pnm.load(file, header, bitmap=bitmap, palette=palette)
if header.startswith(b"GIF"):
+ if not bitmap:
+ raise RuntimeError("bitmap argument required")
+
from . import gif
return gif.load(file, bitmap=bitmap, palette=palette)
+ if header.startswith(b"\x89PN"):
+ if not bitmap:
+ raise RuntimeError("bitmap argument required")
+ from . import png
+
+ return png.load(file, bitmap=bitmap, palette=palette)
+ if header.startswith(b"\xff\xd8"):
+ from . import jpg
+
+ return jpg.load(file, bitmap=bitmap)
raise RuntimeError("Unsupported image format")
diff --git a/adafruit_imageload/bmp/__init__.py b/adafruit_imageload/bmp/__init__.py
old mode 100644
new mode 100755
index bab3c54..5c9c1df
--- a/adafruit_imageload/bmp/__init__.py
+++ b/adafruit_imageload/bmp/__init__.py
@@ -1,4 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
#
# SPDX-License-Identifier: MIT
@@ -8,28 +9,45 @@
Load pixel values (indices or colors) into a bitmap and colors into a palette from a BMP file.
-* Author(s): Scott Shawcroft
+* Author(s): Scott Shawcroft, Matt Land
"""
-# pylint: disable=import-outside-toplevel
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import List, Optional, Set, Tuple, Union
+
+ from displayio import Bitmap, ColorConverter, Palette
+
+ from ..displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, *, bitmap=None, palette=None):
+def load(
+ file: BufferedReader,
+ *,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Union[Palette, ColorConverter]]]:
"""Loads a bmp image from the open ``file``.
- Returns tuple of bitmap object and palette object.
+ Returns tuple of `displayio.Bitmap` object and
+ `displayio.Palette` object, or `displayio.ColorConverter` object.
+ :param io.BufferedReader file: Open file handle or compatible (like `io.BytesIO`)
+ with the data of a BMP file.
:param object bitmap: Type to store bitmap data. Must have API similar to `displayio.Bitmap`.
Will be skipped if None
:param object palette: Type to store the palette. Must have API similar to
`displayio.Palette`. Will be skipped if None"""
file.seek(10)
data_start = int.from_bytes(file.read(4), "little")
- # f.seek(14)
- # bmp_header_length = int.from_bytes(file.read(4), 'little')
+ file.seek(14)
+ bmp_header_length = int.from_bytes(file.read(4), "little")
# print(bmp_header_length)
file.seek(0x12) # Width of the bitmap in pixels
_width = int.from_bytes(file.read(4), "little")
@@ -45,15 +63,34 @@ def load(file, *, bitmap=None, palette=None):
compression = int.from_bytes(file.read(2), "little")
file.seek(0x2E) # Number of colors in the color palette
colors = int.from_bytes(file.read(4), "little")
+ bitfield_masks = None
+ if compression == 3 and bmp_header_length >= 56:
+ bitfield_masks = {}
+ endianess = "little" if color_depth == 16 else "big"
+ file.seek(0x36)
+ bitfield_masks["red"] = int.from_bytes(file.read(4), endianess)
+ file.seek(0x3A)
+ bitfield_masks["green"] = int.from_bytes(file.read(4), endianess)
+ file.seek(0x3E)
+ bitfield_masks["blue"] = int.from_bytes(file.read(4), endianess)
- if colors == 0 and color_depth >= 16:
- raise NotImplementedError("True color BMP unsupported")
-
- if compression > 2:
+ if compression > 3:
raise NotImplementedError("bitmask compression unsupported")
+ if colors == 0 and color_depth >= 16:
+ from . import truecolor
+
+ return truecolor.load(
+ file,
+ _width,
+ _height,
+ data_start,
+ color_depth,
+ bitfield_masks,
+ bitmap=bitmap,
+ )
if colors == 0:
- colors = 2 ** color_depth
+ colors = 2**color_depth
from . import indexed
return indexed.load(
diff --git a/adafruit_imageload/bmp/indexed.py b/adafruit_imageload/bmp/indexed.py
index 1fed132..8168921 100755
--- a/adafruit_imageload/bmp/indexed.py
+++ b/adafruit_imageload/bmp/indexed.py
@@ -1,4 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
#
# SPDX-License-Identifier: MIT
@@ -8,33 +9,44 @@
Load pixel values (indices or colors) into a bitmap and colors into a palette from an indexed BMP.
-* Author(s): Scott Shawcroft
+* Author(s): Scott Shawcroft, Matt Land
"""
-__version__ = "0.0.0-auto.0"
-__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-
import sys
+try:
+ from io import BufferedReader
+ from typing import Optional, Tuple
+
+ from displayio import Bitmap, Palette
+
+ from ..displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
try:
from bitmaptools import readinto as _bitmap_readinto
except ImportError:
- _bitmap_readinto = None # pylint: disable=invalid-name
+ _bitmap_readinto = None
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(
- file,
- width,
- height,
- data_start,
- colors,
- color_depth,
- compression,
+
+def load( # noqa: PLR0913, PLR0912, Too many arguments in function definition, Too many branches
+ file: BufferedReader,
+ width: int,
+ height: int,
+ data_start: int,
+ colors: int,
+ color_depth: int,
+ compression: int,
*,
- bitmap=None,
- palette=None
-):
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""Loads indexed bitmap data into bitmap and palette objects.
:param file file: The open bmp file
@@ -43,31 +55,34 @@ def load(
:param int data_start: Byte location where the data starts (after headers)
:param int colors: Number of distinct colors in the image
:param int color_depth: Number of bits used to store a value
- :param int compression: 0 - none, 1 - 8bit RLE, 2 - 4bit RLE"""
- # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
+ :param int compression: 0 - none, 1 - 8bit RLE, 2 - 4bit RLE
+ :param BitmapConstructor bitmap: a function that returns a displayio.Bitmap
+ :param PaletteConstructor palette: a function that returns a displayio.Palette
+ """
+ palette_obj = None
if palette:
- palette = palette(colors)
+ palette_obj = palette(colors)
file.seek(data_start - colors * 4)
for value in range(colors):
c_bytes = file.read(4)
# Need to swap red & blue bytes (bytes 0 and 2)
- palette[value] = bytes(
+ palette_obj[value] = bytes(
b"".join([c_bytes[2:3], c_bytes[1:2], c_bytes[0:1], c_bytes[3:1]])
)
+ bitmap_obj = None
if bitmap:
minimum_color_depth = 1
- while colors > 2 ** minimum_color_depth:
+ while colors > 2**minimum_color_depth:
minimum_color_depth *= 2
if sys.maxsize > 1073741823:
- # pylint: disable=import-outside-toplevel, relative-beyond-top-level
from .negative_height_check import negative_height_check
# convert unsigned int to signed int when height is negative
height = negative_height_check(height)
- bitmap = bitmap(width, abs(height), colors)
+ bitmap_obj = bitmap(width, abs(height), colors)
file.seek(data_start)
line_size = width // (8 // color_depth)
if width % (8 // color_depth) != 0:
@@ -86,10 +101,9 @@ def load(
range3 = 1
if compression == 0:
-
if _bitmap_readinto:
_bitmap_readinto(
- bitmap,
+ bitmap_obj,
file,
bits_per_pixel=color_depth,
element_size=4,
@@ -106,25 +120,28 @@ def load(
for x in range(width):
i = x // pixels_per_byte
- pixel = (
- chunk[i] >> (8 - color_depth * (x % pixels_per_byte + 1))
- ) & mask
- bitmap[offset + x] = pixel
+ pixel = (chunk[i] >> (8 - color_depth * (x % pixels_per_byte + 1))) & mask
+ bitmap_obj[offset + x] = pixel
elif compression in (1, 2):
decode_rle(
- bitmap=bitmap,
+ bitmap=bitmap_obj,
file=file,
compression=compression,
y_range=(range1, range2, range3),
width=width,
)
- return bitmap, palette
+ return bitmap_obj, palette_obj
-def decode_rle(bitmap, file, compression, y_range, width):
+def decode_rle( # noqa: PLR0912 Too many branches
+ bitmap: Bitmap,
+ file: BufferedReader,
+ compression: int,
+ y_range: Tuple[int, int, int],
+ width: int,
+) -> None:
"""Helper to decode RLE images"""
- # pylint: disable=too-many-locals,too-many-nested-blocks,too-many-branches
# RLE algorithm, either 8-bit (1) or 4-bit (2)
#
diff --git a/adafruit_imageload/bmp/negative_height_check.py b/adafruit_imageload/bmp/negative_height_check.py
index 99317a8..f16b79e 100644
--- a/adafruit_imageload/bmp/negative_height_check.py
+++ b/adafruit_imageload/bmp/negative_height_check.py
@@ -1,4 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
+# SPDX-FileCopyrightText: 2022 Matt Land
#
# SPDX-License-Identifier: MIT
@@ -6,10 +7,12 @@
Check for negative height on the BMP.
Seperated into it's own file to support builds
without longint.
+
+* Author(s): Tim Cocks, Matt Land
"""
-def negative_height_check(height):
+def negative_height_check(height: int) -> int:
"""Check the height return modified if negative."""
if height > 0x7FFFFFFF:
return height - 4294967296
diff --git a/adafruit_imageload/bmp/truecolor.py b/adafruit_imageload/bmp/truecolor.py
new file mode 100755
index 0000000..fe4baac
--- /dev/null
+++ b/adafruit_imageload/bmp/truecolor.py
@@ -0,0 +1,131 @@
+# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Melissa LeBlanc-Williams
+#
+# SPDX-License-Identifier: MIT
+
+"""
+`adafruit_imageload.bmp.truecolor`
+====================================================
+
+Load pixel colors into a bitmap from an truecolor BMP and return the correct colorconverter.
+
+* Author(s): Melissa LeBlanc-Williams
+
+"""
+
+import sys
+
+try:
+ from io import BufferedReader
+ from typing import Optional, Tuple, Union
+
+ from ..displayio_types import BitmapConstructor
+except ImportError:
+ pass
+
+from displayio import Bitmap, ColorConverter, Colorspace
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
+
+bitfield_colorspaces = (
+ { # 16-bit RGB555
+ "mask_values": (0x00007C00, 0x000003E0, 0x0000001F),
+ "color_space": Colorspace.RGB555,
+ },
+ { # 16-bit RGB565
+ "mask_values": (0x0000F800, 0x000007E0, 0x0000001F),
+ "color_space": Colorspace.RGB565,
+ },
+ { # 24 or 32-bit RGB888 (Alpha ignored for 32-bit)
+ "mask_values": (0x0000FF00, 0x00FF0000, 0xFF000000),
+ "color_space": Colorspace.RGB888,
+ },
+)
+
+
+def bitfield_format(bitfield_mask):
+ """Returns the colorspace for the given bitfield mask"""
+ mask = (bitfield_mask["red"], bitfield_mask["green"], bitfield_mask["blue"])
+ for colorspace in bitfield_colorspaces:
+ if colorspace["mask_values"] == mask:
+ return colorspace["color_space"]
+ return None
+
+
+def load( # noqa: PLR0912, PLR0913, Too many branches, Too many arguments in function definition
+ file: BufferedReader,
+ width: int,
+ height: int,
+ data_start: int,
+ color_depth: int,
+ bitfield_masks: Union[dict, None],
+ *,
+ bitmap: Optional[BitmapConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[ColorConverter]]:
+ """Loads truecolor bitmap data into bitmap and palette objects. Due to the 16-bit limit
+ that the bitmap object can hold, colors will be converted to 16-bit RGB565 values.
+
+ :param file file: The open bmp file
+ :param int width: Image width in pixels
+ :param int height: Image height in pixels
+ :param int data_start: Byte location where the data starts (after headers)
+ :param int color_depth: Number of bits used to store a value
+ :param dict bitfield_masks: The bitfield masks for each color if using bitfield compression
+ :param BitmapConstructor bitmap: a function that returns a displayio.Bitmap
+ """
+ converter_obj = None
+ bitmap_obj = None
+ if bitmap:
+ # Set up a ColorConverter object and set appropriate colorspace
+ # to convert from based on the color depth
+ input_colorspace = Colorspace.RGB888
+ if bitfield_masks is not None:
+ colorspace = bitfield_format(bitfield_masks)
+ if colorspace is not None:
+ input_colorspace = colorspace
+ else:
+ raise NotImplementedError("Bitfield mask not supported")
+ elif color_depth == 16:
+ input_colorspace = Colorspace.RGB555
+ converter_obj = ColorConverter(input_colorspace=input_colorspace)
+ if sys.maxsize > 1073741823:
+ from .negative_height_check import negative_height_check
+
+ # convert unsigned int to signed int when height is negative
+ height = negative_height_check(height)
+ bitmap_obj = bitmap(width, abs(height), 65535)
+ file.seek(data_start)
+ line_size = width * (color_depth // 8)
+ # Set the seek direction based on whether the height value is negative or positive
+ if height > 0:
+ range1 = height - 1
+ range2 = -1
+ range3 = -1
+ else:
+ range1 = 0
+ range2 = abs(height)
+ range3 = 1
+ chunk = bytearray(line_size)
+ for y in range(range1, range2, range3):
+ file.readinto(chunk)
+ bytes_per_pixel = color_depth // 8
+ offset = y * width
+
+ for x in range(width):
+ i = x * bytes_per_pixel
+ if bitfield_masks is not None:
+ color = 0
+ for byte in range(bytes_per_pixel):
+ color |= chunk[i + byte] << (8 * byte)
+ mask = bitfield_masks["red"] | bitfield_masks["green"] | bitfield_masks["blue"]
+ if color_depth in (24, 32):
+ mask = mask >> 8
+ pixel = color & mask
+ elif color_depth == 16:
+ pixel = chunk[i] | chunk[i + 1] << 8
+ else:
+ pixel = chunk[i + 2] << 16 | chunk[i + 1] << 8 | chunk[i]
+ bitmap_obj[offset + x] = converter_obj.convert(pixel)
+
+ return bitmap_obj, ColorConverter(input_colorspace=Colorspace.RGB565)
diff --git a/adafruit_imageload/displayio_types.py b/adafruit_imageload/displayio_types.py
new file mode 100644
index 0000000..f2adcc7
--- /dev/null
+++ b/adafruit_imageload/displayio_types.py
@@ -0,0 +1,28 @@
+# SPDX-FileCopyrightText: 2022 Matt Land
+#
+# SPDX-License-Identifier: MIT
+"""
+`adafruit_imageload.displayio_types`
+====================================================
+
+This is a utility file for type aliases.
+https://mypy.readthedocs.io/en/stable/kinds_of_types.html#type-aliases
+Type aliases contain compound declarations (used many places in the project) with a single
+definition readable by humans.
+
+* Author(s): Matt Land
+
+"""
+
+try:
+ from typing import Callable
+
+ from displayio import Bitmap, Palette
+
+ PaletteConstructor = Callable[[int], Palette]
+ BitmapConstructor = Callable[[int, int, int], Bitmap]
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
diff --git a/adafruit_imageload/gif.py b/adafruit_imageload/gif.py
index 8f1dc04..e5183c1 100644
--- a/adafruit_imageload/gif.py
+++ b/adafruit_imageload/gif.py
@@ -1,4 +1,5 @@
# SPDX-FileCopyrightText: 2019 Radomir Dopieralski for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
#
# SPDX-License-Identifier: MIT
@@ -9,31 +10,46 @@
Load pixel values (indices or colors) into a bitmap and colors into a palette
from a GIF file.
-* Author(s): Radomir Dopieralski
+* Author(s): Radomir Dopieralski, Matt Land
"""
import struct
+try:
+ from io import BufferedReader
+ from typing import Iterator, List, Optional, Tuple
-__version__ = "0.0.0-auto.0"
+ from displayio import Bitmap, Palette
+
+ from .displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, *, bitmap=None, palette=None):
+def load(
+ file: BufferedReader, *, bitmap: BitmapConstructor, palette: Optional[PaletteConstructor] = None
+) -> Tuple[Bitmap, Optional[Palette]]:
"""Loads a GIF image from the open ``file``.
Returns tuple of bitmap object and palette object.
+ :param io.BufferedReader file: Open file handle or compatible (like `io.BytesIO`)
+ with the data of a GIF file.
:param object bitmap: Type to store bitmap data. Must have API similar to `displayio.Bitmap`.
- Will be skipped if None
:param object palette: Type to store the palette. Must have API similar to
- `displayio.Palette`. Will be skipped if None"""
+ `displayio.Palette`. Will be skipped if None.
+ """
header = file.read(6)
if header not in {b"GIF87a", b"GIF89a"}:
raise ValueError("Not a GIF file")
width, height, flags, _, _ = struct.unpack(" None:
+ """Read a single frame and apply it to the bitmap."""
ddx, ddy, width, _, flags = struct.unpack(" Iterator[int]:
"""Read a block from a file."""
while True:
size = file.read(1)[0]
@@ -95,21 +111,21 @@ class EndOfData(Exception):
class LZWDict:
"""A dictionary of LZW codes."""
- def __init__(self, code_size):
+ def __init__(self, code_size: int) -> None:
self.code_size = code_size
self.clear_code = 1 << code_size
self.end_code = self.clear_code + 1
- self.codes = []
- self.last = None
+ self.codes = [] # type: List[bytes]
+ self.last = b""
self.clear()
- def clear(self):
+ def clear(self) -> None:
"""Reset the dictionary to default codes."""
self.last = b""
self.code_len = self.code_size + 1
self.codes[:] = []
- def decode(self, code):
+ def decode(self, code: int) -> bytes:
"""Decode a code."""
if code == self.clear_code:
self.clear()
@@ -124,21 +140,18 @@ def decode(self, code):
value = self.last + self.last[0:1]
if self.last:
self.codes.append(self.last + value[0:1])
- if (
- len(self.codes) + self.end_code + 1 >= 1 << self.code_len
- and self.code_len < 12
- ):
+ if len(self.codes) + self.end_code + 1 >= 1 << self.code_len and self.code_len < 12:
self.code_len += 1
self.last = value
return value
-def lzw_decode(data, code_size):
+def lzw_decode(data: Iterator[int], code_size: int) -> Iterator[bytes]:
"""Decode LZW-compressed data."""
dictionary = LZWDict(code_size)
bit = 0
try:
- byte = next(data) # pylint: disable=stop-iteration-return
+ byte = next(data)
try:
while True:
code = 0
@@ -147,10 +160,10 @@ def lzw_decode(data, code_size):
bit += 1
if bit >= 8:
bit = 0
- byte = next(data) # pylint: disable=stop-iteration-return
+ byte = next(data)
yield dictionary.decode(code)
except EndOfData:
while True:
- next(data) # pylint: disable=stop-iteration-return
+ next(data)
except StopIteration:
pass
diff --git a/adafruit_imageload/jpg.py b/adafruit_imageload/jpg.py
new file mode 100644
index 0000000..ad5174c
--- /dev/null
+++ b/adafruit_imageload/jpg.py
@@ -0,0 +1,57 @@
+# SPDX-FileCopyrightText: 2024 Channing Ramos
+#
+# SPDX-License-Identifier: MIT
+
+"""
+`adafruit_imageload.jpg`
+====================================================
+
+Load a JPG into a bitmap by calling the jpegio class.
+
+* Author(s): Channing Ramos
+
+"""
+
+# A separate try for jpegio. Not every board supports it and this import may fail.
+# If that happens an ImportError with a proper message needs to be raised
+try:
+ from jpegio import JpegDecoder
+except ImportError:
+ print("jpegio not supported on this board.")
+
+try:
+ from io import BufferedReader
+ from typing import Optional, Tuple
+
+ from .displayio_types import BitmapConstructor
+except ImportError:
+ pass
+
+from displayio import Bitmap, ColorConverter, Colorspace
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
+
+
+def load(
+ file: BufferedReader,
+ *,
+ bitmap: BitmapConstructor,
+) -> Tuple[Bitmap, Optional[ColorConverter]]:
+ """
+ Loads a JPG image from the open ''file''.
+ The JPG must be a Baseline JPG, Progressive and Lossless JPG formats are not supported.
+
+ Returns tuple of bitmap object and ColorConverter object.
+
+ :param io.BufferedReader file: Open file handle or compatible (like 'io.BytesIO')
+ :param object bitmap: Type to store bitmap data.
+ Must have API similar to 'displayio.Bitmap'. Will be skipped if None.
+ Will be skipped if None.
+ """
+ decoder = JpegDecoder()
+ width, height = decoder.open(file)
+ bitmap_obj = bitmap(width, height, 65535)
+ decoder.decode(bitmap_obj)
+
+ return bitmap_obj, ColorConverter(input_colorspace=Colorspace.RGB565_SWAPPED)
diff --git a/adafruit_imageload/png.py b/adafruit_imageload/png.py
new file mode 100755
index 0000000..215e313
--- /dev/null
+++ b/adafruit_imageload/png.py
@@ -0,0 +1,225 @@
+# SPDX-FileCopyrightText: 2022 Radomir Dopieralski
+# SPDX-FileCopyrightText: 2023 Matt Land
+# SPDX-FileCopyrightText: 2024 Channing Ramos
+#
+# SPDX-License-Identifier: MIT
+
+"""
+`adafruit_imageload.png`
+====================================================
+
+Load pixel values (indices or colors) into a bitmap and colors into a palette
+from a PNG file.
+
+* Author(s): Radomir Dopieralski, Matt Land, Channing Ramos
+
+"""
+
+try:
+ from io import BufferedReader
+ from typing import Optional, Tuple
+
+ from displayio import Bitmap, Palette
+
+ from .displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+import struct
+import zlib
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
+
+
+def load( # noqa: PLR0912, PLR0915, Too many branches, Too many statements
+ file: BufferedReader, *, bitmap: BitmapConstructor, palette: Optional[PaletteConstructor] = None
+) -> Tuple[Bitmap, Optional[Palette]]:
+ """
+ Loads a PNG image from the open ``file``.
+ Only supports indexed color images.
+
+ Returns tuple of bitmap object and palette object.
+
+ :param io.BufferedReader file: Open file handle or compatible (like `io.BytesIO`)
+ with the data of a PNG file.
+ :param object bitmap: Type to store bitmap data. Must have API similar to
+ `displayio.Bitmap`.
+ :param object palette: Type to store the palette. Must have API similar to
+ `displayio.Palette`. Will be skipped if None.
+ """
+ header = file.read(8)
+ if header != b"\x89PNG\r\n\x1a\n":
+ raise ValueError("Not a PNG file")
+ del header
+ data = bytearray()
+ pal = None
+ mode = None
+ depth = 0
+ width = 0
+ height = 0
+ while True:
+ size, chunk = struct.unpack(">I4s", file.read(8))
+ if chunk == b"IHDR":
+ (
+ width,
+ height,
+ depth,
+ mode,
+ compression,
+ filters,
+ interlaced,
+ ) = struct.unpack(">IIBBBBB", file.read(13))
+ if interlaced:
+ raise NotImplementedError("Interlaced images unsupported")
+ # compression and filters must be 0 with current spec
+ assert compression == 0
+ assert filters == 0
+ elif chunk == b"PLTE":
+ if palette is None:
+ file.seek(size, 1)
+ else:
+ if mode != 3:
+ raise NotImplementedError("Palette in non-indexed image")
+ pal_size = size // 3
+ pal = palette(pal_size)
+ for i in range(pal_size):
+ pal[i] = file.read(3)
+ elif chunk == b"tRNS":
+ if size > len(pal):
+ raise ValueError("More transparency entries than palette entries")
+ trns_data = file.read(size)
+ for i in range(len(trns_data)):
+ if trns_data[i] == 0:
+ pal.make_transparent(i)
+ del trns_data
+ elif chunk == b"IDAT":
+ data.extend(file.read(size))
+ elif chunk == b"IEND":
+ break
+ else:
+ file.seek(size, 1) # skip unknown chunks
+ file.seek(4, 1) # skip CRC
+ data_bytes = zlib.decompress(data)
+ unit = (1, 0, 3, 1, 2, 0, 4)[mode]
+ scanline = (width * depth * unit + 7) // 8
+ if mode == 3: # indexed
+ bmp = bitmap(width, height, 1 << depth)
+ pixels_per_byte = 8 // depth
+ src = 0
+ pixmask = (1 << depth) - 1
+ line = bytearray(scanline)
+ prev = bytearray(scanline)
+ for y in range(height):
+ filter_ = data_bytes[src]
+ src_b = src + 1
+ for x in range(0, width, pixels_per_byte):
+ # relative position on the line
+ pos = x // pixels_per_byte
+ byte = data_bytes[src_b]
+ if filter_ == 0:
+ pass
+ elif filter_ == 1: # sub
+ prev_b = line[pos - unit] if pos >= unit else 0
+ byte = (byte + prev_b) & 0xFF
+ elif filter_ == 2: # up
+ byte = (byte + prev[pos]) & 0xFF
+ elif filter_ == 3: # average
+ prev_b = line[pos - unit] if pos >= unit else 0
+ byte = (byte + (prev_b + prev[pos]) // 2) & 0xFF
+ elif filter_ == 4: # paeth
+ a = line[pos - unit] if pos >= unit else 0
+ if y > 0:
+ b = prev[pos]
+ c = prev[pos - unit] if pos >= unit else 0
+ else:
+ b = c = 0
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc:
+ p = a
+ elif pb <= pc:
+ p = b
+ else:
+ p = c
+ byte = (byte + p) & 0xFF
+ else:
+ raise ValueError("Wrong filter.")
+ line[pos] = byte
+ for pixel in range(pixels_per_byte):
+ if x + pixel < width:
+ bmp[x + pixel, y] = (
+ byte >> ((pixels_per_byte - pixel - 1) * depth)
+ ) & pixmask
+ src_b += 1
+ src += scanline + 1
+ prev, line = line, prev
+ return bmp, pal
+ # RGB, RGBA or Grayscale
+ import displayio
+
+ if depth != 8:
+ raise ValueError("Must be 8bit depth.")
+ pal = displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB888)
+ bmp = bitmap(width, height, 65536)
+ prev = bytearray(scanline)
+ line = bytearray(scanline)
+ for y in range(height):
+ src = y * (scanline + 1)
+ filter_ = data_bytes[src]
+ src += 1
+ if filter_ == 0:
+ line[0:scanline] = data_bytes[src : src + scanline]
+ elif filter_ == 1: # sub
+ for i in range(scanline):
+ a = line[i - unit] if i >= unit else 0
+ line[i] = (data_bytes[src] + a) & 0xFF
+ src += 1
+ elif filter_ == 2: # up
+ for i in range(scanline):
+ b = prev[i]
+ line[i] = (data_bytes[src] + b) & 0xFF
+ src += 1
+ elif filter_ == 3: # average
+ for i in range(scanline):
+ a = line[i - unit] if i >= unit else 0
+ b = prev[i]
+ line[i] = (data_bytes[src] + ((a + b) >> 1)) & 0xFF
+ src += 1
+ elif filter_ == 4: # paeth
+ for i in range(scanline):
+ a = line[i - unit] if i >= unit else 0
+ b = prev[i]
+ c = prev[i - unit] if i >= unit else 0
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc:
+ p = a
+ elif pb <= pc:
+ p = b
+ else:
+ p = c
+ line[i] = (data_bytes[src] + p) & 0xFF
+ src += 1
+ else:
+ raise ValueError("Wrong filter.")
+ if mode in (0, 4): # grayscale
+ for x in range(width):
+ c = line[x * unit]
+ bmp[x, y] = pal.convert((c << 16) | (c << 8) | c)
+ elif mode in {2, 6}: # rgb
+ for x in range(width):
+ bmp[x, y] = pal.convert(
+ (line[x * unit + 0] << 16) | (line[x * unit + 1] << 8) | line[x * unit + 2]
+ )
+ else:
+ raise ValueError("Unsupported color mode.")
+
+ prev, line = line, prev
+
+ pal = displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565)
+ return bmp, pal
diff --git a/adafruit_imageload/pnm/__init__.py b/adafruit_imageload/pnm/__init__.py
index d9631d9..b178299 100644
--- a/adafruit_imageload/pnm/__init__.py
+++ b/adafruit_imageload/pnm/__init__.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -14,24 +14,46 @@
* Author(s): Matt Land, Brooke Storm, Sam McGahan
"""
-# pylint: disable=import-outside-toplevel
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import (
+ Callable,
+ Iterable,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ )
+
+ from displayio import Bitmap, Palette
+
+ from ..displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, header, *, bitmap=None, palette=None):
+def load( # noqa: PLR0912 Too many branches
+ file: BufferedReader,
+ header: bytes,
+ *,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""
- Scan for netpbm format info, skip over comments, and and delegate to a submodule
+ Scan for netpbm format info, skip over comments, and delegate to a submodule
to do the actual data loading.
Formats P1, P4 have two space padded pieces of information: width and height.
All other formats have three: width, height, and max color value.
This load function will move the file stream pointer to the start of data in all cases.
"""
- # pylint: disable=too-many-branches
magic_number = header[:2]
file.seek(2)
- pnm_header = []
+ pnm_header = [] # type: List[int]
next_value = bytearray()
while True:
# We have all we need at length 3 for formats P2, P3, P5, P6
@@ -40,44 +62,70 @@ def load(file, header, *, bitmap=None, palette=None):
from . import pgm
return pgm.load(
- file, magic_number, pnm_header, bitmap=bitmap, palette=palette
+ file,
+ magic_number,
+ pnm_header,
+ bitmap=bitmap,
+ palette=palette,
)
if magic_number == b"P3":
from . import ppm_ascii
return ppm_ascii.load(
- file, pnm_header[0], pnm_header[1], bitmap=bitmap, palette=palette
+ file,
+ pnm_header[0],
+ pnm_header[1],
+ bitmap=bitmap,
+ palette=palette,
)
if magic_number == b"P6":
from . import ppm_binary
return ppm_binary.load(
- file, pnm_header[0], pnm_header[1], bitmap=bitmap, palette=palette
+ file,
+ pnm_header[0],
+ pnm_header[1],
+ bitmap=bitmap,
+ palette=palette,
)
if len(pnm_header) == 2 and magic_number in [b"P1", b"P4"]:
- bitmap = bitmap(pnm_header[0], pnm_header[1], 1)
+ if not bitmap:
+ raise RuntimeError(
+ "A bitmap constructor is required for this type of pnm format file"
+ )
+ bitmap_obj = bitmap(pnm_header[0], pnm_header[1], 1)
+ palette_obj = None
if palette:
- palette = palette(1)
- palette[0] = b"\xFF\xFF\xFF"
+ palette_obj = palette(1)
+ palette_obj[0] = b"\xff\xff\xff"
if magic_number.startswith(b"P1"):
from . import pbm_ascii
return pbm_ascii.load(
- file, pnm_header[0], pnm_header[1], bitmap=bitmap, palette=palette
+ file,
+ pnm_header[0],
+ pnm_header[1],
+ bitmap=bitmap_obj,
+ palette=palette_obj,
)
from . import pbm_binary
return pbm_binary.load(
- file, pnm_header[0], pnm_header[1], bitmap=bitmap, palette=palette
+ file,
+ pnm_header[0],
+ pnm_header[1],
+ bitmap=bitmap_obj,
+ palette=palette_obj,
)
next_byte = file.read(1)
if next_byte == b"":
- raise RuntimeError("Unsupported image format {}".format(magic_number))
+ # mpy-cross does not support !r in f-string substitution, so ignore ruff rule
+ raise RuntimeError("Unsupported image format {!r}".format(magic_number)) # noqa: UP032, f-string
if next_byte == b"#": # comment found, seek until a newline or EOF is found
while file.read(1) not in [b"", b"\n"]: # EOF or NL
pass
diff --git a/adafruit_imageload/pnm/pbm_ascii.py b/adafruit_imageload/pnm/pbm_ascii.py
index c0206f9..872846c 100644
--- a/adafruit_imageload/pnm/pbm_ascii.py
+++ b/adafruit_imageload/pnm/pbm_ascii.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -16,15 +16,29 @@
"""
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import Optional, Tuple
+
+ from displayio import Bitmap, Palette
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, width, height, bitmap=None, palette=None):
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Bitmap,
+ palette: Optional[Palette] = None,
+) -> Tuple[Bitmap, Optional[Palette]]:
"""
Load a P1 'PBM' ascii image into the displayio.Bitmap
"""
- next_byte = True
+ next_byte = b"1" # just to start the iterator
for y in range(height):
x = 0
while next_byte:
diff --git a/adafruit_imageload/pnm/pbm_binary.py b/adafruit_imageload/pnm/pbm_binary.py
index 0bd6ce1..53d92df 100644
--- a/adafruit_imageload/pnm/pbm_binary.py
+++ b/adafruit_imageload/pnm/pbm_binary.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -16,14 +16,29 @@
"""
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import Iterator, Optional, Tuple
+
+ from displayio import Bitmap, Palette
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, width, height, bitmap=None, palette=None):
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Bitmap,
+ palette: Optional[Palette] = None,
+) -> Tuple[Bitmap, Optional[Palette]]:
"""
- Load a P4 'PBM' binary image into the displayio.Bitmap
+ Load a P4 'PBM' binary image into the Bitmap
"""
+ padded_width = (width + 7) // 8 * 8
x = 0
y = 0
while True:
@@ -31,9 +46,10 @@ def load(file, width, height, bitmap=None, palette=None):
if not next_byte:
break # out of bits
for bit in iterbits(next_byte):
- bitmap[x, y] = bit
+ if x < width:
+ bitmap[x, y] = bit
x += 1
- if x > width - 1:
+ if x > padded_width - 1:
y += 1
x = 0
if y > height - 1:
@@ -41,7 +57,7 @@ def load(file, width, height, bitmap=None, palette=None):
return bitmap, palette
-def iterbits(b):
+def iterbits(b: bytes) -> Iterator[int]:
"""
generator to iterate over the bits in a byte (character)
"""
@@ -50,7 +66,7 @@ def iterbits(b):
yield (in_char >> i) & 1
-def reverse(b):
+def reverse(b: int) -> int:
"""
reverse bit order so the iterbits works
"""
diff --git a/adafruit_imageload/pnm/pgm/__init__.py b/adafruit_imageload/pnm/pgm/__init__.py
index e496327..8acefb5 100644
--- a/adafruit_imageload/pnm/pgm/__init__.py
+++ b/adafruit_imageload/pnm/pgm/__init__.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -14,10 +14,26 @@
* Author(s): Matt Land, Brooke Storm, Sam McGahan
"""
-# pylint: disable=import-outside-toplevel
+try:
+ from io import BufferedReader
+ from typing import List, Optional, Set, Tuple
-def load(file, magic_number, header, *, bitmap=None, palette=None):
+ from displayio import Bitmap, Palette
+
+ from ...displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+
+def load(
+ file: BufferedReader,
+ magic_number: bytes,
+ header: List[int],
+ *,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""
Perform the load of Netpbm greyscale images (P2, P5)
"""
diff --git a/adafruit_imageload/pnm/pgm/ascii.py b/adafruit_imageload/pnm/pgm/ascii.py
index 777f0c4..7c597ca 100644
--- a/adafruit_imageload/pnm/pgm/ascii.py
+++ b/adafruit_imageload/pnm/pgm/ascii.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -15,8 +15,24 @@
"""
+try:
+ from io import BufferedReader
+ from typing import Optional, Set, Tuple
-def load(file, width, height, bitmap=None, palette=None):
+ from displayio import Bitmap, Palette
+
+ from ...displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""
Load a PGM ascii file (P2)
"""
@@ -33,11 +49,12 @@ def load(file, width, height, bitmap=None, palette=None):
_palette_colors.add(int_pixel)
pixel = bytearray()
pixel += byte
+ palette_obj = None
if palette:
- palette = build_palette(palette, _palette_colors)
+ palette_obj = build_palette(palette, _palette_colors)
+ bitmap_obj = None
if bitmap:
- bitmap = bitmap(width, height, len(_palette_colors))
- _palette_colors = list(_palette_colors)
+ bitmap_obj = bitmap(width, height, len(_palette_colors))
file.seek(data_start)
for y in range(height):
for x in range(width):
@@ -48,11 +65,11 @@ def load(file, width, height, bitmap=None, palette=None):
break
pixel += byte
int_pixel = int("".join(["%c" % char for char in pixel]))
- bitmap[x, y] = _palette_colors.index(int_pixel)
- return bitmap, palette
+ bitmap_obj[x, y] = list(_palette_colors).index(int_pixel)
+ return bitmap_obj, palette_obj
-def build_palette(palette_class, palette_colors): # pylint: disable=duplicate-code
+def build_palette(palette_class: PaletteConstructor, palette_colors: Set[int]) -> Palette:
"""
construct the Palette, and populate it with the set of palette_colors
"""
diff --git a/adafruit_imageload/pnm/pgm/binary.py b/adafruit_imageload/pnm/pgm/binary.py
index dcacabd..700b563 100644
--- a/adafruit_imageload/pnm/pgm/binary.py
+++ b/adafruit_imageload/pnm/pgm/binary.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -15,32 +15,49 @@
"""
+try:
+ from io import BufferedReader
+ from typing import Optional, Set, Tuple
-def load(file, width, height, bitmap=None, palette=None):
+ from displayio import Bitmap, Palette
+
+ from ...displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""
Load a P5 format file (binary), handle PGM (greyscale)
"""
- palette_colors = set()
+ palette_colors = set() # type: Set[int]
data_start = file.tell()
for y in range(height):
data_line = iter(bytes(file.read(width)))
for pixel in data_line:
palette_colors.add(pixel)
+ palette_obj = None
if palette:
- palette = build_palette(palette, palette_colors)
+ palette_obj = build_palette(palette, palette_colors)
+ bitmap_obj = None
if bitmap:
- bitmap = bitmap(width, height, len(palette_colors))
- palette_colors = list(palette_colors)
+ bitmap_obj = bitmap(width, height, len(palette_colors))
file.seek(data_start)
for y in range(height):
data_line = iter(bytes(file.read(width)))
for x, pixel in enumerate(data_line):
- bitmap[x, y] = palette_colors.index(pixel)
- return bitmap, palette
+ bitmap_obj[x, y] = list(palette_colors).index(pixel)
+ return bitmap_obj, palette_obj
-def build_palette(palette_class, palette_colors):
+def build_palette(palette_class: PaletteConstructor, palette_colors: Set[int]) -> Palette:
"""
construct the Palette, and populate it with the set of palette_colors
"""
diff --git a/adafruit_imageload/pnm/ppm_ascii.py b/adafruit_imageload/pnm/ppm_ascii.py
index 2c7929a..e79b70b 100644
--- a/adafruit_imageload/pnm/ppm_ascii.py
+++ b/adafruit_imageload/pnm/ppm_ascii.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -16,11 +16,33 @@
"""
-__version__ = "0.0.0-auto.0"
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
+try:
+ from io import BufferedReader
+ from typing import (
+ Iterator,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ )
-def load(file, width, height, bitmap=None, palette=None):
+ from displayio import Bitmap, Palette
+
+ from ..displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
"""
:param stream file: infile with the position set at start of data
:param int width:
@@ -30,34 +52,35 @@ def load(file, width, height, bitmap=None, palette=None):
:param palette: displayio.Palette class
:return tuple:
"""
- palette_colors = set()
+ palette_colors = set() # type: Set[bytes]
data_start = file.tell()
for triplet in read_three_colors(file):
palette_colors.add(triplet)
+ palette_obj = None
if palette:
- palette = palette(len(palette_colors))
+ palette_obj = palette(len(palette_colors))
for counter, color in enumerate(palette_colors):
- palette[counter] = color
+ palette_obj[counter] = color
+ bitmap_obj = None
if bitmap:
file.seek(data_start)
- bitmap = bitmap(width, height, len(palette_colors))
- palette_colors = list(palette_colors)
+ bitmap_obj = bitmap(width, height, len(palette_colors))
for y in range(height):
for x in range(width):
for color in read_three_colors(file):
- bitmap[x, y] = palette_colors.index(color)
+ bitmap_obj[x, y] = list(palette_colors).index(color)
break # exit the inner generator
- return bitmap, palette
+ return bitmap_obj, palette_obj
-def read_three_colors(file):
+def read_three_colors(file: BufferedReader) -> Iterator[bytes]:
"""
Generator to read integer values from file, in groups of three.
Each value can be len 1-3, for values 0 - 255, space padded.
- :return tuple[int]:
+ :return Iterator[bytes]:
"""
- triplet = []
+ triplet = [] # type: List[int]
color = bytearray()
while True:
this_byte = file.read(1)
diff --git a/adafruit_imageload/pnm/ppm_binary.py b/adafruit_imageload/pnm/ppm_binary.py
index 8ecb5e8..56540d3 100644
--- a/adafruit_imageload/pnm/ppm_binary.py
+++ b/adafruit_imageload/pnm/ppm_binary.py
@@ -1,5 +1,5 @@
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
-# SPDX-FileCopyrightText: Matt Land
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
@@ -16,16 +16,34 @@
"""
-__version__ = "0.0.0-auto.0"
+try:
+ from io import BufferedReader
+ from typing import Optional, Set, Tuple
+
+ from displayio import Bitmap, Palette
+
+ from ..displayio_types import BitmapConstructor, PaletteConstructor
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
-def load(file, width, height, bitmap=None, palette=None):
- """Load pixel values (indices or colors) into a bitmap and for a binary
- ppm, return None for pallet."""
+def load(
+ file: BufferedReader,
+ width: int,
+ height: int,
+ bitmap: Optional[BitmapConstructor] = None,
+ palette: Optional[PaletteConstructor] = None,
+) -> Tuple[Optional[Bitmap], Optional[Palette]]:
+ """
+ Load pixel values (indices or colors) into a bitmap and for a binary
+ ppm, return None for pallet.
+ """
data_start = file.tell()
- palette_colors = set()
+ palette_colors = set() # type: Set[Tuple[int, int, int]]
line_size = width * 3
for y in range(height):
@@ -34,22 +52,23 @@ def load(file, width, height, bitmap=None, palette=None):
# red, green, blue
palette_colors.add((red, next(data_line), next(data_line)))
+ palette_obj = None
if palette:
- palette = palette(len(palette_colors))
+ palette_obj = palette(len(palette_colors))
for counter, color in enumerate(palette_colors):
- palette[counter] = bytes(color)
+ palette_obj[counter] = bytes(color)
+ bitmap_obj = None
if bitmap:
- bitmap = bitmap(width, height, len(palette_colors))
+ bitmap_obj = bitmap(width, height, len(palette_colors))
file.seek(data_start)
- palette_colors = list(palette_colors)
for y in range(height):
x = 0
data_line = iter(bytes(file.read(line_size)))
for red in data_line:
# red, green, blue
- bitmap[x, y] = palette_colors.index(
+ bitmap_obj[x, y] = list(palette_colors).index(
(red, next(data_line), next(data_line))
)
x += 1
- return bitmap, palette
+ return bitmap_obj, palette_obj
diff --git a/adafruit_imageload/tilegrid_inflator.py b/adafruit_imageload/tilegrid_inflator.py
new file mode 100644
index 0000000..89a3458
--- /dev/null
+++ b/adafruit_imageload/tilegrid_inflator.py
@@ -0,0 +1,109 @@
+# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
+#
+# SPDX-License-Identifier: MIT
+
+"""
+`adafruit_imageload.tilegrid_inflator`
+====================================================
+
+Use a 3x3 spritesheet to inflate a larger grid of tiles, duplicating the center rows and
+columns as many times as needed to reach a target size.
+
+* Author(s): Tim Cocks, Matt Land
+
+"""
+
+import displayio
+
+import adafruit_imageload
+
+try:
+ from typing import List, Optional, Tuple, Union
+
+ from displayio import Bitmap, OnDiskBitmap, Palette, TileGrid
+except ImportError:
+ pass
+
+__version__ = "0.0.0+auto.0"
+__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
+
+
+def inflate_tilegrid( # noqa: PLR0913, PLR0912, Too many arguments in function definition, Too many branches
+ bmp_path: Optional[str] = None,
+ target_size: Tuple[int, int] = (3, 3),
+ tile_size: Optional[List[int]] = None,
+ transparent_index: Optional[Union[tuple, int]] = None,
+ bmp_obj: Optional[OnDiskBitmap] = None,
+ bmp_palette: Optional[Palette] = None,
+) -> TileGrid:
+ """
+ inflate a TileGrid of ``target_size`` in tiles from a 3x3 spritesheet by duplicating
+ the center rows and columns.
+
+ :param Optional[str] bmp_path: filepath to the 3x3 spritesheet bitmap file
+ :param tuple[int, int] target_size: desired size in tiles (target_width, target_height)
+ :param Optional[List[int]] tile_size: size of the tiles in the 3x3 spritesheet. If
+ None is used it will equally divide the width and height of the Bitmap by 3.
+ :param Optional[Union[tuple, int]] transparent_index: a single index within the palette to
+ make transparent, or a tuple of multiple indexes to make transparent
+ :param Optional[OnDiskBitmap] bmp_obj: Already loaded 3x3 spritesheet in an OnDiskBitmap
+ :param Optional[Palette] bmp_palette: Already loaded spritesheet Palette
+ """
+
+ if bmp_path is None and (bmp_obj is None and bmp_palette is None):
+ raise AttributeError("Must pass either bmp_path or bmp_obj and bmp_palette")
+
+ image: Bitmap
+ palette: Palette
+ if bmp_path is not None:
+ image, palette = adafruit_imageload.load(bmp_path) # type: ignore[assignment]
+ else:
+ image = bmp_obj # type: ignore[assignment]
+ palette = bmp_palette # type: ignore[assignment]
+
+ if transparent_index is not None:
+ if isinstance(transparent_index, tuple):
+ for index in transparent_index:
+ palette.make_transparent(index)
+ elif isinstance(transparent_index, int):
+ palette.make_transparent(transparent_index)
+
+ if tile_size is None:
+ tile_width = image.width // 3
+ tile_height = image.height // 3
+ else:
+ tile_width = tile_size[0]
+ tile_height = tile_size[1]
+
+ target_width = target_size[0]
+ target_height = target_size[1]
+
+ tile_grid = displayio.TileGrid(
+ image,
+ pixel_shader=palette,
+ height=target_height,
+ width=target_width,
+ tile_width=tile_width,
+ tile_height=tile_height,
+ )
+
+ # corners
+ tile_grid[0, 0] = 0 # upper left
+ tile_grid[tile_grid.width - 1, 0] = 2 # upper right
+ tile_grid[0, tile_grid.height - 1] = 6 # lower left
+ tile_grid[tile_grid.width - 1, tile_grid.height - 1] = 8 # lower right
+
+ for x in range(target_size[0] - 2):
+ tile_grid[x + 1, 0] = 1
+ tile_grid[x + 1, tile_grid.height - 1] = 7
+
+ for y in range(target_size[1] - 2):
+ tile_grid[0, y + 1] = 3
+ tile_grid[tile_grid.width - 1, y + 1] = 5
+
+ for y in range(target_size[1] - 2):
+ for x in range(target_size[0] - 2):
+ tile_grid[x + 1, y + 1] = 4
+
+ return tile_grid
diff --git a/docs/api.rst b/docs/api.rst
index 5ef6ad1..14b5c05 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -12,3 +12,12 @@
.. automodule:: adafruit_imageload.bmp.indexed
:members:
+
+.. automodule:: adafruit_imageload.gif
+ :members:
+
+.. automodule:: adafruit_imageload.png
+ :members:
+
+.. automodule:: adafruit_imageload.tilegrid_inflator
+ :members:
diff --git a/docs/conf.py b/docs/conf.py
index bf49375..15c9fc0 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,9 +1,8 @@
-# -*- coding: utf-8 -*-
-
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
+import datetime
import os
import sys
@@ -16,6 +15,7 @@
# ones.
extensions = [
"sphinx.ext.autodoc",
+ "sphinxcontrib.jquery",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
@@ -29,8 +29,8 @@
intersphinx_mapping = {
- "python": ("https://docs.python.org/3.4", None),
- "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
+ "python": ("https://docs.python.org/3", None),
+ "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None),
}
# Add any paths that contain templates here, relative to this directory.
@@ -43,7 +43,12 @@
# General information about the project.
project = "Adafruit_ ImageLoad Library"
-copyright = "2018 Scott Shawcroft"
+creation_year = "2018"
+current_year = str(datetime.datetime.now().year)
+year_duration = (
+ current_year if current_year == creation_year else creation_year + " - " + current_year
+)
+copyright = year_duration + " Scott Shawcroft"
author = "Scott Shawcroft"
# The version info for the project you're documenting, acts as replacement for
@@ -60,7 +65,7 @@
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
-language = None
+language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
@@ -92,19 +97,9 @@
# 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"
-
-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(), "."]
- except:
- html_theme = "default"
- html_theme_path = ["."]
-else:
- html_theme_path = ["."]
+import sphinx_rtd_theme
+
+html_theme = "sphinx_rtd_theme"
# 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,
diff --git a/docs/developing.rst b/docs/developing.rst
index 7b1d345..9b6a8fd 100644
--- a/docs/developing.rst
+++ b/docs/developing.rst
@@ -115,3 +115,18 @@ For example, the Bitmap coordinate ``[0,0]`` has the value (integer) ``5``.
This corresponds to the the Palette object's, ``[5]`` which is ``b'\x00\x00\xff\x00'``. This is a byte string that represents a color.
+
+====================
+Mypy & type checking
+====================
+
+Mypy was tested with version 0.950 and the mypy.ini in project root.
+Since checks are not currently not passing, it is not installed as a commit hook.
+
+Setup: In your virtual environment, run:
+
+ pip3 install mypy==0.050
+
+Developing: To manually run checks, run:
+
+ mypy .
diff --git a/docs/examples.rst b/docs/examples.rst
index 039d649..6dc236d 100644
--- a/docs/examples.rst
+++ b/docs/examples.rst
@@ -15,3 +15,12 @@ Loads image that is fetched using adafruit_request
.. literalinclude:: ../examples/imageload_from_web.py
:caption: examples/imageload_from_web.py
:linenos:
+
+Inflate TileGrid test
+---------------------
+
+Load 3x3 spritesheet and inflate it to a larger sized TileGrid
+
+.. literalinclude:: ../examples/imageload_tilegrid_inflator_simpletest.py
+ :caption: examples/imageload_tilegrid_inflator_simpletest.py
+ :linenos:
diff --git a/docs/index.rst b/docs/index.rst
index 0023060..9b7d0a4 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -42,8 +42,9 @@ Table of Contents
.. toctree::
:caption: Other Links
- Download
- CircuitPython Reference Documentation
+ Download from GitHub
+ Download Library Bundle
+ CircuitPython Reference Documentation
CircuitPython Support Forum
Discord Chat
Adafruit Learning System
diff --git a/docs/requirements.txt b/docs/requirements.txt
index 88e6733..979f568 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -2,4 +2,6 @@
#
# SPDX-License-Identifier: Unlicense
-sphinx>=4.0.0
+sphinx
+sphinxcontrib-jquery
+sphinx-rtd-theme
diff --git a/examples/imageload_colorwheel.py b/examples/imageload_colorwheel.py
index 5946db9..58bc889 100644
--- a/examples/imageload_colorwheel.py
+++ b/examples/imageload_colorwheel.py
@@ -3,6 +3,7 @@
import board
import displayio
+
import adafruit_imageload
display = board.DISPLAY
@@ -15,6 +16,6 @@
group = displayio.Group()
group.append(tile_grid)
-display.show(group)
+display.root_group = group
while True:
pass
diff --git a/examples/imageload_from_web.py b/examples/imageload_from_web.py
index 9168cd3..79c78dd 100644
--- a/examples/imageload_from_web.py
+++ b/examples/imageload_from_web.py
@@ -4,34 +4,33 @@
imageload example for esp32s2 that loads an image fetched via
adafruit_requests using BytesIO
"""
+
from io import BytesIO
-import ssl
-import wifi
-import socketpool
+from os import getenv
+import adafruit_connection_manager
+import adafruit_requests as requests
import board
import displayio
-import adafruit_requests as requests
+import wifi
+
import adafruit_imageload
-# Get wifi details and more from a secrets.py file
-try:
- from secrets import secrets
-except ImportError:
- print("WiFi secrets are kept in secrets.py, please add them there!")
- raise
+# Get WiFi details, ensure these are setup in settings.toml
+ssid = getenv("CIRCUITPY_WIFI_SSID")
+password = getenv("CIRCUITPY_WIFI_PASSWORD")
-wifi.radio.connect(secrets["ssid"], secrets["password"])
+wifi.radio.connect(ssid, password)
print("My IP address is", wifi.radio.ipv4_address)
-socket = socketpool.SocketPool(wifi.radio)
-https = requests.Session(socket, ssl.create_default_context())
+pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
+ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
+https = requests.Session(pool, ssl_context)
-# pylint: disable=line-too-long
url = "https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_ImageLoad/main/examples/images/4bit.bmp"
-print("Fetching text from %s" % url)
+print(f"Fetching text from {url}")
response = https.get(url)
print("GET complete")
@@ -41,7 +40,7 @@
group = displayio.Group(scale=1)
group.append(tile_grid)
-board.DISPLAY.show(group)
+board.DISPLAY.root_group = group
response.close()
diff --git a/examples/imageload_jpg_simpletest.py b/examples/imageload_jpg_simpletest.py
new file mode 100644
index 0000000..93f2a2f
--- /dev/null
+++ b/examples/imageload_jpg_simpletest.py
@@ -0,0 +1,23 @@
+# SPDX-FileCopyrightText: 2024 Channing Ramos
+#
+# SPDX-License-Identifier: MIT
+
+"""
+Basic JPG imageload example
+"""
+
+import board
+import displayio
+
+import adafruit_imageload
+
+group = displayio.Group()
+board.DISPLAY.root_group = group
+
+image, color_converter = adafruit_imageload.load("images/jpg_test.jpg")
+
+tile_grid = displayio.TileGrid(image, pixel_shader=color_converter)
+group.append(tile_grid)
+
+while True:
+ pass
diff --git a/examples/imageload_magtag_simpletest.py b/examples/imageload_magtag_simpletest.py
index 04651cf..cbee121 100644
--- a/examples/imageload_magtag_simpletest.py
+++ b/examples/imageload_magtag_simpletest.py
@@ -5,9 +5,12 @@
Basic imageload example script
adapted for use on MagTag.
"""
+
import time
+
import board
import displayio
+
import adafruit_imageload
# use built in display (PyPortal, PyGamer, PyBadge, CLUE, etc.)
@@ -27,7 +30,7 @@
group.append(tile_grid)
# show the group and refresh
-display.show(group)
+display.root_group = group
display.refresh()
while True:
diff --git a/examples/imageload_netpbm.py b/examples/imageload_netpbm.py
index c6347b4..06ca3f1 100644
--- a/examples/imageload_netpbm.py
+++ b/examples/imageload_netpbm.py
@@ -12,9 +12,10 @@
"""
+import adafruit_ili9341
import board
import displayio
-import adafruit_ili9341
+
import adafruit_imageload
spi = board.SPI()
@@ -28,7 +29,7 @@
# Make the display context
splash = displayio.Group()
-display.show(splash)
+display.root_group = splash
# image = "images/netpbm_p1_mono_ascii.pbm"
# image = "images/netpbm_p2_ascii.pgm"
# image = "images/netpbm_p3_rgb_ascii.ppm"
@@ -36,9 +37,7 @@
# image = "images/netpbm_p5_binary.pgm"
image = "images/netpbm_p6_binary.ppm"
-bitmap, palette = adafruit_imageload.load(
- image, bitmap=displayio.Bitmap, palette=displayio.Palette
-)
+bitmap, palette = adafruit_imageload.load(image, bitmap=displayio.Bitmap, palette=displayio.Palette)
bg_sprite = displayio.TileGrid(bitmap, pixel_shader=palette, x=0, y=0)
diff --git a/examples/imageload_png_simpletest.py b/examples/imageload_png_simpletest.py
new file mode 100644
index 0000000..106ea69
--- /dev/null
+++ b/examples/imageload_png_simpletest.py
@@ -0,0 +1,45 @@
+# SPDX-FileCopyrightText: 2022 Tim Cocks
+# SPDX-License-Identifier: MIT
+
+import board
+import displayio
+from vectorio import Rectangle
+
+import adafruit_imageload
+
+# built-in display
+display = board.DISPLAY
+
+# load png image. Uncomment to try other supported formats.
+image, palette = adafruit_imageload.load("images/test_image.png")
+# image, palette = adafruit_imageload.load("images/test_image_grayscale.png")
+# image, palette = adafruit_imageload.load("images/test_image_rgb.png")
+# image, palette = adafruit_imageload.load("images/test_image_2bit.png")
+
+# Set the transparency index color to be hidden
+palette.make_transparent(0)
+
+# make tilegrid for the loaded image
+tile_grid = displayio.TileGrid(image, pixel_shader=palette)
+tile_grid.x = display.width // 2 - tile_grid.tile_width // 2
+tile_grid.y = display.height // 2 - tile_grid.tile_height // 2
+
+# make a blank background
+bg_palette = displayio.Palette(1)
+bg_palette[0] = 0xFFFFFF
+rect = Rectangle(pixel_shader=bg_palette, width=display.width, height=display.height, x=0, y=0)
+
+# make a group to show on the display
+group = displayio.Group()
+
+# add background
+group.append(rect)
+# add loaded image tilegrid
+group.append(tile_grid)
+
+# show our group
+board.DISPLAY.root_group = group
+
+# loop forever so it stays on the display
+while True:
+ pass
diff --git a/examples/imageload_simpletest.py b/examples/imageload_simpletest.py
index 692f013..1481791 100644
--- a/examples/imageload_simpletest.py
+++ b/examples/imageload_simpletest.py
@@ -3,6 +3,7 @@
import board
import displayio
+
import adafruit_imageload
image, palette = adafruit_imageload.load("images/4bit.bmp")
@@ -11,7 +12,7 @@
group = displayio.Group()
group.append(tile_grid)
-board.DISPLAY.show(group)
+board.DISPLAY.root_group = group
while True:
pass
diff --git a/examples/imageload_tilegrid_inflator_simpletest.py b/examples/imageload_tilegrid_inflator_simpletest.py
new file mode 100644
index 0000000..867b6b5
--- /dev/null
+++ b/examples/imageload_tilegrid_inflator_simpletest.py
@@ -0,0 +1,18 @@
+# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries
+# SPDX-License-Identifier: MIT
+
+import board
+import displayio
+
+import adafruit_imageload
+from adafruit_imageload.tilegrid_inflator import inflate_tilegrid
+
+image, palette = adafruit_imageload.load("images/castle_spritesheet.bmp")
+tile_grid = inflate_tilegrid(bmp_obj=image, bmp_palette=palette, target_size=(10, 8))
+
+group = displayio.Group()
+group.append(tile_grid)
+board.DISPLAY.root_group = group
+
+while True:
+ pass
diff --git a/examples/images/castle_spritesheet.bmp b/examples/images/castle_spritesheet.bmp
new file mode 100644
index 0000000..587bef7
Binary files /dev/null and b/examples/images/castle_spritesheet.bmp differ
diff --git a/examples/images/castle_spritesheet.bmp.license b/examples/images/castle_spritesheet.bmp.license
new file mode 100644
index 0000000..a784acf
--- /dev/null
+++ b/examples/images/castle_spritesheet.bmp.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/jpg_test.jpg b/examples/images/jpg_test.jpg
new file mode 100644
index 0000000..7479826
Binary files /dev/null and b/examples/images/jpg_test.jpg differ
diff --git a/examples/images/jpg_test.jpg.license b/examples/images/jpg_test.jpg.license
new file mode 100644
index 0000000..d2f8702
--- /dev/null
+++ b/examples/images/jpg_test.jpg.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2024 Channing Ramos
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/netpbm_p4_mono_width.pbm b/examples/images/netpbm_p4_mono_width.pbm
new file mode 100644
index 0000000..ef6a9e6
--- /dev/null
+++ b/examples/images/netpbm_p4_mono_width.pbm
@@ -0,0 +1,3 @@
+P4
+14 20
+ÏÌ·´·´·´·´·´·´·´·´{x|øøg˜Cøø{x¼ôßìà
\ No newline at end of file
diff --git a/examples/images/netpbm_p4_mono_width.pbm.license b/examples/images/netpbm_p4_mono_width.pbm.license
new file mode 100644
index 0000000..5e64ae4
--- /dev/null
+++ b/examples/images/netpbm_p4_mono_width.pbm.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2025 Karolis Stasaitis
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/test_image.png b/examples/images/test_image.png
new file mode 100644
index 0000000..9e196dc
Binary files /dev/null and b/examples/images/test_image.png differ
diff --git a/examples/images/test_image.png.license b/examples/images/test_image.png.license
new file mode 100644
index 0000000..ad03cf2
--- /dev/null
+++ b/examples/images/test_image.png.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2022 ladyada for Adafruit Industries
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/test_image_2bit.png b/examples/images/test_image_2bit.png
new file mode 100644
index 0000000..9cc7416
Binary files /dev/null and b/examples/images/test_image_2bit.png differ
diff --git a/examples/images/test_image_2bit.png.license b/examples/images/test_image_2bit.png.license
new file mode 100644
index 0000000..6a552de
--- /dev/null
+++ b/examples/images/test_image_2bit.png.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2024 Foamyguy
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/test_image_grayscale.png b/examples/images/test_image_grayscale.png
new file mode 100644
index 0000000..f86ed29
Binary files /dev/null and b/examples/images/test_image_grayscale.png differ
diff --git a/examples/images/test_image_grayscale.png.license b/examples/images/test_image_grayscale.png.license
new file mode 100644
index 0000000..ad03cf2
--- /dev/null
+++ b/examples/images/test_image_grayscale.png.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2022 ladyada for Adafruit Industries
+# SPDX-License-Identifier: MIT
diff --git a/examples/images/test_image_rgb.png b/examples/images/test_image_rgb.png
new file mode 100644
index 0000000..975fe89
Binary files /dev/null and b/examples/images/test_image_rgb.png differ
diff --git a/examples/images/test_image_rgb.png.license b/examples/images/test_image_rgb.png.license
new file mode 100644
index 0000000..ad03cf2
--- /dev/null
+++ b/examples/images/test_image_rgb.png.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2022 ladyada for Adafruit Industries
+# SPDX-License-Identifier: MIT
diff --git a/mypy.ini b/mypy.ini
new file mode 100644
index 0000000..a24b0e4
--- /dev/null
+++ b/mypy.ini
@@ -0,0 +1,14 @@
+# SPDX-FileCopyrightText: 2022-2023 Matt Land
+#
+# SPDX-License-Identifier: Unlicense
+[mypy]
+python_version = 3.7
+disallow_untyped_defs = True
+disable_error_code = no-redef
+exclude = (examples|tests|setup.py|docs)
+
+[mypy-displayio]
+ignore_missing_imports = True
+
+[mypy-bitmaptools]
+ignore_missing_imports = True
diff --git a/optional_requirements.txt b/optional_requirements.txt
new file mode 100644
index 0000000..d4e27c4
--- /dev/null
+++ b/optional_requirements.txt
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
+#
+# SPDX-License-Identifier: Unlicense
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..34513c6
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,52 @@
+# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+
+[build-system]
+requires = [
+ "setuptools",
+ "wheel",
+ "setuptools-scm",
+]
+
+[project]
+name = "adafruit-circuitpython-imageload"
+description = "Displays text using CircuitPython's displayio."
+version = "0.0.0+auto.0"
+readme = "README.rst"
+authors = [
+ {name = "Adafruit Industries", email = "circuitpython@adafruit.com"}
+]
+urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad"}
+keywords = [
+ "adafruit",
+ "blinka",
+ "circuitpython",
+ "micropython",
+ "bitmap",
+ "fonts",
+ "text",
+ "display",
+ "tft",
+ "lcd",
+ "displayio",
+ "imageload",
+ "image",
+]
+license = {text = "MIT"}
+classifiers = [
+ "Intended Audience :: Developers",
+ "Topic :: Software Development :: Libraries",
+ "Topic :: Software Development :: Embedded Systems",
+ "Topic :: System :: Hardware",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3",
+]
+dynamic = ["dependencies", "optional-dependencies"]
+
+[tool.setuptools]
+packages = ["adafruit_imageload"]
+
+[tool.setuptools.dynamic]
+dependencies = {file = ["requirements.txt"]}
+optional-dependencies = {optional = {file = ["optional_requirements.txt"]}}
diff --git a/requirements.txt b/requirements.txt
index 44cdfd8..274b851 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,4 @@
-# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
+# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
diff --git a/ruff.toml b/ruff.toml
new file mode 100644
index 0000000..db37c83
--- /dev/null
+++ b/ruff.toml
@@ -0,0 +1,99 @@
+# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+
+target-version = "py38"
+line-length = 100
+
+[lint]
+select = ["I", "PL", "UP"]
+
+extend-select = [
+ "D419", # empty-docstring
+ "E501", # line-too-long
+ "W291", # trailing-whitespace
+ "PLC0414", # useless-import-alias
+ "PLC2401", # non-ascii-name
+ "PLC2801", # unnecessary-dunder-call
+ "PLC3002", # unnecessary-direct-lambda-call
+ "E999", # syntax-error
+ "PLE0101", # return-in-init
+ "F706", # return-outside-function
+ "F704", # yield-outside-function
+ "PLE0116", # continue-in-finally
+ "PLE0117", # nonlocal-without-binding
+ "PLE0241", # duplicate-bases
+ "PLE0302", # unexpected-special-method-signature
+ "PLE0604", # invalid-all-object
+ "PLE0605", # invalid-all-format
+ "PLE0643", # potential-index-error
+ "PLE0704", # misplaced-bare-raise
+ "PLE1141", # dict-iter-missing-items
+ "PLE1142", # await-outside-async
+ "PLE1205", # logging-too-many-args
+ "PLE1206", # logging-too-few-args
+ "PLE1307", # bad-string-format-type
+ "PLE1310", # bad-str-strip-call
+ "PLE1507", # invalid-envvar-value
+ "PLE2502", # bidirectional-unicode
+ "PLE2510", # invalid-character-backspace
+ "PLE2512", # invalid-character-sub
+ "PLE2513", # invalid-character-esc
+ "PLE2514", # invalid-character-nul
+ "PLE2515", # invalid-character-zero-width-space
+ "PLR0124", # comparison-with-itself
+ "PLR0202", # no-classmethod-decorator
+ "PLR0203", # no-staticmethod-decorator
+ "UP004", # useless-object-inheritance
+ "PLR0206", # property-with-parameters
+ "PLR0904", # too-many-public-methods
+ "PLR0911", # too-many-return-statements
+ "PLR0912", # too-many-branches
+ "PLR0913", # too-many-arguments
+ "PLR0914", # too-many-locals
+ "PLR0915", # too-many-statements
+ "PLR0916", # too-many-boolean-expressions
+ "PLR1702", # too-many-nested-blocks
+ "PLR1704", # redefined-argument-from-local
+ "PLR1711", # useless-return
+ "C416", # unnecessary-comprehension
+ "PLR1733", # unnecessary-dict-index-lookup
+ "PLR1736", # unnecessary-list-index-lookup
+
+ # ruff reports this rule is unstable
+ #"PLR6301", # no-self-use
+
+ "PLW0108", # unnecessary-lambda
+ "PLW0120", # useless-else-on-loop
+ "PLW0127", # self-assigning-variable
+ "PLW0129", # assert-on-string-literal
+ "B033", # duplicate-value
+ "PLW0131", # named-expr-without-context
+ "PLW0245", # super-without-brackets
+ "PLW0406", # import-self
+ "PLW0602", # global-variable-not-assigned
+ "PLW0603", # global-statement
+ "PLW0604", # global-at-module-level
+
+ # fails on the try: import typing used by libraries
+ #"F401", # unused-import
+
+ "F841", # unused-variable
+ "E722", # bare-except
+ "PLW0711", # binary-op-exception
+ "PLW1501", # bad-open-mode
+ "PLW1508", # invalid-envvar-default
+ "PLW1509", # subprocess-popen-preexec-fn
+ "PLW2101", # useless-with-lock
+ "PLW3301", # nested-min-max
+]
+
+ignore = [
+ "PLR2004", # magic-value-comparison
+ "UP030", # format literals
+ "PLW1514", # unspecified-encoding
+
+]
+
+[format]
+line-ending = "lf"
diff --git a/setup.py b/setup.py
deleted file mode 100644
index 73083c5..0000000
--- a/setup.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
-#
-# SPDX-License-Identifier: MIT
-
-"""A setuptools based setup module.
-See:
-https://packaging.python.org/en/latest/distributing.html
-https://github.com/pypa/sampleproject
-"""
-
-from setuptools import setup, find_packages
-
-# To use a consistent encoding
-from codecs import open
-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:
- long_description = f.read()
-
-setup(
- name="adafruit-circuitpython-imageload",
- use_scm_version=True,
- setup_requires=["setuptools_scm"],
- description="Displays text using CircuitPython's displayio.",
- long_description=long_description,
- long_description_content_type="text/x-rst",
- # The project's main homepage.
- url="https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad",
- # Author details
- author="Adafruit Industries",
- author_email="circuitpython@adafruit.com",
- install_requires=[
- "Adafruit-Blinka",
- "adafruit-blinka-displayio",
- ],
- # Choose your license
- 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",
- ],
- # What does your project relate to?
- keywords="adafruit blinka circuitpython micropython bitmap fonts text display tft lcd displayio imageload image",
- # You can just specify the packages manually here if your project is
- # simple. Or you can use find_packages().
- packages=["adafruit_imageload", "adafruit_imageload.bmp", "adafruit_imageload.pnm"],
-)
diff --git a/tests/displayio_shared_bindings.py b/tests/displayio_shared_bindings.py
index fcd96bc..5d796d7 100644
--- a/tests/displayio_shared_bindings.py
+++ b/tests/displayio_shared_bindings.py
@@ -34,6 +34,7 @@
* Author(s): Matt Land
"""
+
from typing import Union
@@ -76,9 +77,7 @@ def __setitem__(self, key: Union[tuple, int], value: int) -> None:
if value > 255:
raise ValueError(f"pixel value {value} too large")
if self.data.get(key):
- raise ValueError(
- f"pixel {self._decode(key)}/{key} already set, cannot set again"
- )
+ raise ValueError(f"pixel {self._decode(key)}/{key} already set, cannot set again")
self.data[key] = value
def __getitem__(self, item: Union[tuple, int]) -> bytearray:
@@ -89,9 +88,7 @@ def __getitem__(self, item: Union[tuple, int]) -> bytearray:
try:
return self.data[item]
except KeyError as err:
- raise RuntimeError(
- "no data at {} [{}]".format(self._decode(item), item)
- ) from err
+ raise RuntimeError(f"no data at {self._decode(item)} [{item}]") from err
def validate(self, detect_empty_image=True) -> None:
"""
@@ -160,9 +157,7 @@ def __setitem__(self, key: int, value: Union[bytes, int, bytearray]) -> None:
if isinstance(value, int) and value > 0xFFFFFF:
raise ValueError(f"palette color int {value} is too large")
if self.colors.get(key):
- raise ValueError(
- f"palette color {key} was already set, should not reassign"
- )
+ raise ValueError(f"palette color {key} was already set, should not reassign")
self.colors[key] = value
def __getitem__(self, item: int) -> Union[bytes, int, bytearray]:
@@ -171,9 +166,7 @@ def __getitem__(self, item: int) -> Union[bytes, int, bytearray]:
It is provided here for debugging purposes.
"""
if item >= self.num_colors:
- raise ValueError(
- f"palette index {item} should be less than {self.num_colors}"
- )
+ raise ValueError(f"palette index {item} should be less than {self.num_colors}")
if not self.colors.get(item):
raise ValueError(f"palette index {item} is not set")
return self.colors[item]
@@ -186,17 +179,14 @@ def validate(self):
raise IndexError("no palette colors were set")
if len(self.colors) != self.num_colors:
raise IndexError(
- "palette was initialized for {} colors, but only {} were inserted".format(
- self.num_colors, len(self.colors)
- )
+ f"palette was initialized for {self.num_colors} "
+ f"colors, but only {len(self.colors)} were inserted"
)
for i in range(self.num_colors):
try:
self.colors
except IndexError as err:
- raise ValueError(
- "missing color `{}` in palette color list".format(i)
- ) from err
+ raise ValueError(f"missing color `{i}` in palette color list") from err
def __str__(self):
"""
diff --git a/tests/test_bitmap_c_interface.py b/tests/test_bitmap_c_interface.py
index c9cb703..e4d8727 100644
--- a/tests/test_bitmap_c_interface.py
+++ b/tests/test_bitmap_c_interface.py
@@ -28,7 +28,9 @@
* Author(s): Matt Land
"""
+
from unittest import TestCase
+
from .displayio_shared_bindings import Bitmap_C_Interface
@@ -41,7 +43,7 @@ def test_init(self):
def test_abs(self):
b = Bitmap_C_Interface(5, 2, 1)
- self.assertEqual(9, b._abs_pos(4, 1)) # pylint: disable=protected-access
+ self.assertEqual(9, b._abs_pos(4, 1))
def test_set_tuple(self):
b = Bitmap_C_Interface(2, 4, 1)
@@ -76,7 +78,7 @@ def test_max(self):
def test_uninitialized(self):
b = Bitmap_C_Interface(2, 4, 1)
with self.assertRaises(RuntimeError):
- b[1, 1] # pylint: disable=pointless-statement
+ b[1, 1]
def test_validate_throws(self):
b = Bitmap_C_Interface(2, 4, 1)
@@ -95,6 +97,6 @@ def test_repr(self):
def test_decode(self):
b = Bitmap_C_Interface(4, 4, 1)
- self.assertEqual((0, 0), b._decode(0)) # pylint: disable=protected-access
- encoded = b._abs_pos(3, 3) # pylint: disable=protected-access
- self.assertEqual((3, 3), b._decode(encoded)) # pylint: disable=protected-access
+ self.assertEqual((0, 0), b._decode(0))
+ encoded = b._abs_pos(3, 3)
+ self.assertEqual((3, 3), b._decode(encoded))
diff --git a/tests/test_bmp_indexed_load.py b/tests/test_bmp_indexed_load.py
index 5e72a38..b9c87f1 100644
--- a/tests/test_bmp_indexed_load.py
+++ b/tests/test_bmp_indexed_load.py
@@ -29,15 +29,15 @@
import os
from unittest import TestCase
+
from adafruit_imageload import load
+
from .displayio_shared_bindings import Bitmap_C_Interface, Palette_C_Interface
class TestBmpIndexedLoad(TestCase):
def test_order_bgra_to_rgba(self):
- test_file = os.path.join(
- os.path.dirname(__file__), "..", "examples", "images", "4bit.bmp"
- )
+ test_file = os.path.join(os.path.dirname(__file__), "..", "examples", "images", "4bit.bmp")
bitmap, palette = load(
file_or_filename=test_file,
diff --git a/tests/test_palette_c_interface.py b/tests/test_palette_c_interface.py
index 457f468..e9c56c8 100644
--- a/tests/test_palette_c_interface.py
+++ b/tests/test_palette_c_interface.py
@@ -28,7 +28,9 @@
* Author(s): Matt Land
"""
+
from unittest import TestCase
+
from .displayio_shared_bindings import Palette_C_Interface
@@ -54,17 +56,17 @@ def test_get_int(self):
@staticmethod
def test_set_byte():
palette = Palette_C_Interface(1)
- palette[0] = b"\xFF\xFF\xFF"
+ palette[0] = b"\xff\xff\xff"
def test_get_byte(self):
palette = Palette_C_Interface(1)
- palette[0] = b"\xFF\xFF\xFF"
- self.assertEqual(b"\xFF\xFF\xFF", palette[0])
+ palette[0] = b"\xff\xff\xff"
+ self.assertEqual(b"\xff\xff\xff", palette[0])
@staticmethod
def test_set_bytearray():
palette = Palette_C_Interface(1)
- palette[0] = bytearray(b"\xFF\xFF\xFF")
+ palette[0] = bytearray(b"\xff\xff\xff")
def test_prevents_out_of_range(self):
palette = Palette_C_Interface(1)
@@ -78,7 +80,7 @@ def test_prevents_out_of_range(self):
def test_prevents_set_non_allowed(self):
palette = Palette_C_Interface(1)
try:
- palette[0] = "\xFF\xFF\xFF" # attempt with a string, which is not allowed
+ palette[0] = "\xff\xff\xff" # attempt with a string, which is not allowed
self.fail("exception should have thrown")
except ValueError as err:
if "should be" not in str(err):
@@ -87,12 +89,12 @@ def test_prevents_set_non_allowed(self):
@staticmethod
def test_validate_success():
palette = Palette_C_Interface(1)
- palette[0] = b"\xFF\xFF\xFF"
+ palette[0] = b"\xff\xff\xff"
palette.validate()
def test_validate_fails(self):
palette = Palette_C_Interface(2)
- palette[1] = b"\xFF\xFF\xFF"
+ palette[1] = b"\xff\xff\xff"
try:
palette.validate()
self.fail("exception should have thrown")
@@ -103,5 +105,5 @@ def test_validate_fails(self):
@staticmethod
def test_str():
palette = Palette_C_Interface(1)
- palette[0] = b"\xFF\xFF\xFF"
+ palette[0] = b"\xff\xff\xff"
print(str(palette))
diff --git a/tests/test_pbm_load.py b/tests/test_pbm_load.py
index bc653eb..e999657 100644
--- a/tests/test_pbm_load.py
+++ b/tests/test_pbm_load.py
@@ -26,23 +26,24 @@
* Author(s): Matt Land
"""
+
import os
from io import BytesIO
from unittest import TestCase
+
from adafruit_imageload import pnm
from adafruit_imageload.pnm.pbm_binary import iterbits, reverse
+
from .displayio_shared_bindings import Bitmap_C_Interface, Palette_C_Interface
class TestPbmLoad(TestCase):
- def test_load_fails_with_no_header_data(self): # pylint: disable=invalid-name
+ def test_load_fails_with_no_header_data(self):
file = BytesIO(b"some initial binary data: \x00\x01")
try:
- pnm.load(
- file, b"P1", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
- )
+ pnm.load(file, b"P1", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface)
self.fail("should have failed")
- except Exception as caught_exception: # pylint: disable=broad-except
+ except Exception as caught_exception:
if "Unsupported image format" not in str(caught_exception):
raise
@@ -71,7 +72,7 @@ def test_load_works_p1_ascii(self):
palette.validate()
def test_load_works_p4_in_mem(self):
- file = BytesIO(b"P4\n4 2\n\x55")
+ file = BytesIO(b"P4\n4 2\n\x5f\x5f")
bitmap, palette = pnm.load(
file, b"P4", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
)
@@ -102,7 +103,28 @@ def test_load_works_p4_binary(self):
self.assertEqual(15, bitmap.height)
bitmap.validate()
- def test_load_works_p4_binary_high_res(self): # pylint: disable=invalid-name
+ def test_load_works_p4_binary_padded_width(self):
+ test_file = os.path.join(
+ os.path.dirname(__file__),
+ "..",
+ "examples",
+ "images",
+ "netpbm_p4_mono_width.pbm",
+ )
+ with open(test_file, "rb") as file:
+ bitmap, palette = pnm.load(
+ file, b"P4", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
+ )
+ self.assertEqual(1, palette.num_colors)
+ palette.validate()
+ self.assertEqual(b"\xff\xff\xff", palette[0])
+ self.assertTrue(isinstance(bitmap, Bitmap_C_Interface))
+ self.assertEqual(1, bitmap.colors)
+ self.assertEqual(14, bitmap.width)
+ self.assertEqual(20, bitmap.height)
+ bitmap.validate()
+
+ def test_load_works_p4_binary_high_res(self):
test_file = os.path.join(
os.path.dirname(__file__),
"..",
diff --git a/tests/test_pgm_load.py b/tests/test_pgm_load.py
index dd1bc09..e5c0445 100644
--- a/tests/test_pgm_load.py
+++ b/tests/test_pgm_load.py
@@ -26,9 +26,12 @@
* Author(s): Matt Land
"""
+
import os
from unittest import TestCase
+
from adafruit_imageload import pnm
+
from .displayio_shared_bindings import Bitmap_C_Interface, Palette_C_Interface
diff --git a/tests/test_png.png b/tests/test_png.png
new file mode 100644
index 0000000..314173a
Binary files /dev/null and b/tests/test_png.png differ
diff --git a/tests/test_png.png.license b/tests/test_png.png.license
new file mode 100644
index 0000000..beff0b4
--- /dev/null
+++ b/tests/test_png.png.license
@@ -0,0 +1,2 @@
+# SPDX-FileCopyrightText: 2025 Tim Cocks for Adafruit Industries
+# SPDX-License-Identifier: MIT
diff --git a/tests/test_png_load.py b/tests/test_png_load.py
new file mode 100644
index 0000000..78e0a1c
--- /dev/null
+++ b/tests/test_png_load.py
@@ -0,0 +1,24 @@
+# SPDX-FileCopyrightText: 2025 Tim Cocks for Adafruit Industries
+# SPDX-License-Identifier: MIT
+
+from unittest import TestCase
+
+from adafruit_imageload import load
+
+
+class TestPngLoad(TestCase):
+ def test_expected_pixels(self):
+ img, palette = load("tests/test_png.png")
+ self.assertEqual(len(palette), 3)
+ self.assertEqual(img.width, 4)
+ self.assertEqual(img.height, 4)
+
+ self.assertEqual(img[0, 0], 0)
+ self.assertEqual(img[1, 0], 2)
+ self.assertEqual(img[2, 0], 1)
+ self.assertEqual(img[3, 0], 0)
+
+ self.assertEqual(img[0, 3], 0)
+ self.assertEqual(img[1, 3], 2)
+ self.assertEqual(img[2, 3], 1)
+ self.assertEqual(img[3, 3], 0)
diff --git a/tests/test_ppm_load.py b/tests/test_ppm_load.py
index bb8de7b..dfe081c 100644
--- a/tests/test_ppm_load.py
+++ b/tests/test_ppm_load.py
@@ -26,11 +26,14 @@
* Author(s): Matt Land
"""
+
import os
from io import BytesIO
from unittest import TestCase
+
from adafruit_imageload import pnm
from adafruit_imageload.pnm.ppm_ascii import read_three_colors
+
from .displayio_shared_bindings import Bitmap_C_Interface, Palette_C_Interface