diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md new file mode 100644 index 0000000..8de294e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +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://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 + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5abe58d..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + name: Build CI on: [pull_request, push] @@ -6,58 +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.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install pylint, black, & Sphinx - run: | - pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - - name: Library version - run: git describe --dirty --always --tags - - name: Check formatting - run: | - black --check --target-version=py35 . - - name: PyLint - run: | - pylint $( find . -path './adafruit*.py' ) - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" )) - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Build docs - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Build Python package - run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/failure-help-text.yml b/.github/workflows/failure-help-text.yml new file mode 100644 index 0000000..0b1194f --- /dev/null +++ b/.github/workflows/failure-help-text.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Failure help text + +on: + workflow_run: + workflows: ["Build CI"] + types: + - completed + +jobs: + post-help: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} + steps: + - name: Post comment to help + uses: adafruit/circuitpython-action-library-ci-failed@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 18efb9c..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install deps - run: | - source actions-ci/install.sh - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Upload Release Assets - # the 'official' actions version does not yet support dynamically - # supplying asset names to upload. @csexton's version chosen based on - # discussion in the issue below, as its the simplest to implement and - # allows for selecting files with a pattern. - # https://github.com/actions/upload-release-asset/issues/4 - #uses: actions/upload-release-asset@v1.0.1 - uses: csexton/release-asset-action@master - with: - pattern: "bundles/*" - github-token: ${{ secrets.GITHUB_TOKEN }} - - upload-pypi: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - uses: actions/setup-python@v1 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - python setup.py sdist - twine upload dist/* 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 a176055..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,48 @@ +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries +# +# 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 +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..f27b786 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers +# +# SPDX-License-Identifier: Unlicense + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - 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: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 390e636..0000000 --- a/.pylintrc +++ /dev/null @@ -1,433 +0,0 @@ -[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 -jobs=2 - -# 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 - -# 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=no - -# 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 new file mode 100644 index 0000000..88bca9f --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +sphinx: + configuration: docs/conf.py + +build: + os: ubuntu-20.04 + tools: + python: "3" + +python: + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index f4243ad..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,3 +0,0 @@ -python: - version: 3 -requirements_file: requirements.txt diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 134d510..8a55c07 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,3 +1,9 @@ + + # Adafruit Community Code of Conduct ## Our Pledge @@ -43,7 +49,7 @@ Examples of unacceptable behavior by participants include: The goal of the standards and moderation guidelines outlined here is to build and maintain a respectful community. We ask that you don’t just aim to be -"technically unimpeachable", but rather try to be your best self. +"technically unimpeachable", but rather try to be your best self. We value many things beyond technical expertise, including collaboration and supporting others within our community. Providing a positive experience for @@ -74,9 +80,9 @@ You may report in the following ways: In any situation, you may send an email to . On the Adafruit Discord, you may send an open message from any channel -to all Community Moderators by tagging @community moderators. You may -also send an open message from any channel, or a direct message to -@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, +to all Community Moderators by tagging @community moderators. You may +also send an open message from any channel, or a direct message to +@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. Email and direct message reports will be kept confidential. diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt new file mode 100644 index 0000000..3f92dfc --- /dev/null +++ b/LICENSES/CC-BY-4.0.txt @@ -0,0 +1,324 @@ +Creative Commons Attribution 4.0 International Creative Commons Corporation +("Creative Commons") is not a law firm and does not provide legal services +or legal advice. Distribution of Creative Commons public licenses does not +create a lawyer-client or other relationship. Creative Commons makes its licenses +and related information available on an "as-is" basis. Creative Commons gives +no warranties regarding its licenses, any material licensed under their terms +and conditions, or any related information. Creative Commons disclaims all +liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions +that creators and other rights holders may use to share original works of +authorship and other material subject to copyright and certain other rights +specified in the public license below. The following considerations are for +informational purposes only, are not exhaustive, and do not form part of our +licenses. + +Considerations for licensors: Our public licenses are intended for use by +those authorized to give the public permission to use material in ways otherwise +restricted by copyright and certain other rights. Our licenses are irrevocable. +Licensors should read and understand the terms and conditions of the license +they choose before applying it. Licensors should also secure all rights necessary +before applying our licenses so that the public can reuse the material as +expected. Licensors should clearly mark any material not subject to the license. +This includes other CC-licensed material, or material used under an exception +or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors + +Considerations for the public: By using one of our public licenses, a licensor +grants the public permission to use the licensed material under specified +terms and conditions. If the licensor's permission is not necessary for any +reason–for example, because of any applicable exception or limitation to copyright–then +that use is not regulated by the license. Our licenses grant only permissions +under copyright and certain other rights that a licensor has authority to +grant. Use of the licensed material may still be restricted for other reasons, +including because others have copyright or other rights in the material. A +licensor may make special requests, such as asking that all changes be marked +or described. Although not required by our licenses, you are encouraged to +respect those requests where reasonable. More considerations for the public +: wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution +4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to +be bound by the terms and conditions of this Creative Commons Attribution +4.0 International Public License ("Public License"). To the extent this Public +License may be interpreted as a contract, You are granted the Licensed Rights +in consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the Licensor +receives from making the Licensed Material available under these terms and +conditions. + +Section 1 – Definitions. + +a. Adapted Material means material subject to Copyright and Similar Rights +that is derived from or based upon the Licensed Material and in which the +Licensed Material is translated, altered, arranged, transformed, or otherwise +modified in a manner requiring permission under the Copyright and Similar +Rights held by the Licensor. For purposes of this Public License, where the +Licensed Material is a musical work, performance, or sound recording, Adapted +Material is always produced where the Licensed Material is synched in timed +relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright and Similar +Rights in Your contributions to Adapted Material in accordance with the terms +and conditions of this Public License. + +c. Copyright and Similar Rights means copyright and/or similar rights closely +related to copyright including, without limitation, performance, broadcast, +sound recording, and Sui Generis Database Rights, without regard to how the +rights are labeled or categorized. For purposes of this Public License, the +rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. Effective Technological Measures means those measures that, in the absence +of proper authority, may not be circumvented under laws fulfilling obligations +under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, +and/or similar international agreements. + +e. Exceptions and Limitations means fair use, fair dealing, and/or any other +exception or limitation to Copyright and Similar Rights that applies to Your +use of the Licensed Material. + +f. Licensed Material means the artistic or literary work, database, or other +material to which the Licensor applied this Public License. + +g. Licensed Rights means the rights granted to You subject to the terms and +conditions of this Public License, which are limited to all Copyright and +Similar Rights that apply to Your use of the Licensed Material and that the +Licensor has authority to license. + +h. Licensor means the individual(s) or entity(ies) granting rights under this +Public License. + +i. Share means to provide material to the public by any means or process that +requires permission under the Licensed Rights, such as reproduction, public +display, public performance, distribution, dissemination, communication, or +importation, and to make material available to the public including in ways +that members of the public may access the material from a place and at a time +individually chosen by them. + +j. Sui Generis Database Rights means rights other than copyright resulting +from Directive 96/9/EC of the European Parliament and of the Council of 11 +March 1996 on the legal protection of databases, as amended and/or succeeded, +as well as other essentially equivalent rights anywhere in the world. + +k. You means the individual or entity exercising the Licensed Rights under +this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + +1. Subject to the terms and conditions of this Public License, the Licensor +hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, +irrevocable license to exercise the Licensed Rights in the Licensed Material +to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + +2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions +and Limitations apply to Your use, this Public License does not apply, and +You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + +4. Media and formats; technical modifications allowed. The Licensor authorizes +You to exercise the Licensed Rights in all media and formats whether now known +or hereafter created, and to make technical modifications necessary to do +so. The Licensor waives and/or agrees not to assert any right or authority +to forbid You from making technical modifications necessary to exercise the +Licensed Rights, including technical modifications necessary to circumvent +Effective Technological Measures. For purposes of this Public License, simply +making modifications authorized by this Section 2(a)(4) never produces Adapted +Material. + + 5. Downstream recipients. + +A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed +Material automatically receives an offer from the Licensor to exercise the +Licensed Rights under the terms and conditions of this Public License. + +B. No downstream restrictions. You may not offer or impose any additional +or different terms or conditions on, or apply any Effective Technological +Measures to, the Licensed Material if doing so restricts exercise of the Licensed +Rights by any recipient of the Licensed Material. + +6. No endorsement. Nothing in this Public License constitutes or may be construed +as permission to assert or imply that You are, or that Your use of the Licensed +Material is, connected with, or sponsored, endorsed, or granted official status +by, the Licensor or others designated to receive attribution as provided in +Section 3(a)(1)(A)(i). + + b. Other rights. + +1. Moral rights, such as the right of integrity, are not licensed under this +Public License, nor are publicity, privacy, and/or other similar personality +rights; however, to the extent possible, the Licensor waives and/or agrees +not to assert any such rights held by the Licensor to the limited extent necessary +to allow You to exercise the Licensed Rights, but not otherwise. + +2. Patent and trademark rights are not licensed under this Public License. + +3. To the extent possible, the Licensor waives any right to collect royalties +from You for the exercise of the Licensed Rights, whether directly or through +a collecting society under any voluntary or waivable statutory or compulsory +licensing scheme. In all other cases the Licensor expressly reserves any right +to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following +conditions. + + a. Attribution. + +1. If You Share the Licensed Material (including in modified form), You must: + +A. retain the following if it is supplied by the Licensor with the Licensed +Material: + +i. identification of the creator(s) of the Licensed Material and any others +designated to receive attribution, in any reasonable manner requested by the +Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + +v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + +B. indicate if You modified the Licensed Material and retain an indication +of any previous modifications; and + +C. indicate the Licensed Material is licensed under this Public License, and +include the text of, or the URI or hyperlink to, this Public License. + +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner +based on the medium, means, and context in which You Share the Licensed Material. +For example, it may be reasonable to satisfy the conditions by providing a +URI or hyperlink to a resource that includes the required information. + +3. If requested by the Licensor, You must remove any of the information required +by Section 3(a)(1)(A) to the extent reasonably practicable. + +4. If You Share Adapted Material You produce, the Adapter's License You apply +must not prevent recipients of the Adapted Material from complying with this +Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to +Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, +reuse, reproduce, and Share all or a substantial portion of the contents of +the database; + +b. if You include all or a substantial portion of the database contents in +a database in which You have Sui Generis Database Rights, then the database +in which You have Sui Generis Database Rights (but not its individual contents) +is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or +a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace +Your obligations under this Public License where the Licensed Rights include +other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. Unless otherwise separately undertaken by the Licensor, to the extent possible, +the Licensor offers the Licensed Material as-is and as-available, and makes +no representations or warranties of any kind concerning the Licensed Material, +whether express, implied, statutory, or other. This includes, without limitation, +warranties of title, merchantability, fitness for a particular purpose, non-infringement, +absence of latent or other defects, accuracy, or the presence or absence of +errors, whether or not known or discoverable. Where disclaimers of warranties +are not allowed in full or in part, this disclaimer may not apply to You. + +b. To the extent possible, in no event will the Licensor be liable to You +on any legal theory (including, without limitation, negligence) or otherwise +for any direct, special, indirect, incidental, consequential, punitive, exemplary, +or other losses, costs, expenses, or damages arising out of this Public License +or use of the Licensed Material, even if the Licensor has been advised of +the possibility of such losses, costs, expenses, or damages. Where a limitation +of liability is not allowed in full or in part, this limitation may not apply +to You. + +c. The disclaimer of warranties and limitation of liability provided above +shall be interpreted in a manner that, to the extent possible, most closely +approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights +licensed here. However, if You fail to comply with this Public License, then +Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section +6(a), it reinstates: + +1. automatically as of the date the violation is cured, provided it is cured +within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + +c. For the avoidance of doubt, this Section 6(b) does not affect any right +the Licensor may have to seek remedies for Your violations of this Public +License. + +d. For the avoidance of doubt, the Licensor may also offer the Licensed Material +under separate terms or conditions or stop distributing the Licensed Material +at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or +conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed +Material not stated herein are separate from and independent of the terms +and conditions of this Public License. + +Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not +be interpreted to, reduce, limit, restrict, or impose conditions on any use +of the Licensed Material that could lawfully be made without permission under +this Public License. + +b. To the extent possible, if any provision of this Public License is deemed +unenforceable, it shall be automatically reformed to the minimum extent necessary +to make it enforceable. If the provision cannot be reformed, it shall be severed +from this Public License without affecting the enforceability of the remaining +terms and conditions. + +c. No term or condition of this Public License will be waived and no failure +to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation +upon, or waiver of, any privileges and immunities that apply to the Licensor +or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative +Commons may elect to apply one of its public licenses to material it publishes +and in those instances will be considered the "Licensor." The text of the +Creative Commons public licenses is dedicated to the public domain under the +CC0 Public Domain Dedication. Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at creativecommons.org/policies, +Creative Commons does not authorize the use of the trademark "Creative Commons" +or any other trademark or logo of Creative Commons without its prior written +consent including, without limitation, in connection with any unauthorized +modifications to any of its public licenses or any other arrangements, understandings, +or agreements concerning use of licensed material. For the avoidance of doubt, +this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..204b93d --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,19 @@ +MIT License Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LICENSES/Unlicense.txt b/LICENSES/Unlicense.txt new file mode 100644 index 0000000..24a8f90 --- /dev/null +++ b/LICENSES/Unlicense.txt @@ -0,0 +1,20 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute +this software, either in source code form or as a compiled binary, for any +purpose, commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and +to the detriment of our heirs and successors. We intend this dedication to +be an overt act of relinquishment in perpetuity of all present and future +rights to this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH +THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, +please refer to diff --git a/README.rst b/README.rst index b5e9437..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,20 +40,21 @@ Usage Example group = displayio.Group() group.append(tile_grid) - board.DISPLAY.show(group) - + board.DISPLAY.root_group = group while True: pass +Documentation +============= + +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out `this guide `_. + 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/README.rst.license b/README.rst.license new file mode 100644 index 0000000..11cd75d --- /dev/null +++ b/README.rst.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries + +SPDX-License-Identifier: MIT diff --git a/adafruit_imageload/__init__.py b/adafruit_imageload/__init__.py index 090b812..e149c41 100644 --- a/adafruit_imageload/__init__.py +++ b/adafruit_imageload/__init__.py @@ -1,47 +1,52 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload` ==================================================== 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(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. + 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 - support assignment to indices via []. + 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: try: @@ -56,7 +61,12 @@ def load(filename, *, bitmap=None, palette=None): # meh, we tried pass - with open(filename, "rb") as file: + if isinstance(file_or_filename, str): + open_file = open(file_or_filename, "rb") + else: + open_file = file_or_filename + + with open_file as file: header = file.read(3) file.seek(0) if header.startswith(b"BM"): @@ -68,7 +78,20 @@ def load(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 4eb9167..5c9c1df --- a/adafruit_imageload/bmp/__init__.py +++ b/adafruit_imageload/bmp/__init__.py @@ -1,82 +1,102 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.bmp` ==================================================== 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 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""" + :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") + _width = int.from_bytes(file.read(4), "little") try: - height = int.from_bytes(file.read(4), "little") - except OverflowError: + _height = int.from_bytes(file.read(4), "little") + except OverflowError as error: raise NotImplementedError( "Negative height BMP files are not supported on builds without longint" - ) + ) from error file.seek(0x1C) # Number of bits per pixel color_depth = int.from_bytes(file.read(2), "little") file.seek(0x1E) # Compression type 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( file, - width, - height, + _width, + _height, data_start, colors, color_depth, diff --git a/adafruit_imageload/bmp/indexed.py b/adafruit_imageload/bmp/indexed.py old mode 100644 new mode 100755 index 4bfe7ff..8168921 --- a/adafruit_imageload/bmp/indexed.py +++ b/adafruit_imageload/bmp/indexed.py @@ -1,85 +1,88 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.bmp.indexed` ==================================================== 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 + + +__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 - :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 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 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 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 + :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 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: @@ -98,33 +101,47 @@ def load( range3 = 1 if compression == 0: - chunk = bytearray(line_size) - for y in range(range1, range2, range3): - file.readinto(chunk) - pixels_per_byte = 8 // color_depth - offset = y * width - - 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 + if _bitmap_readinto: + _bitmap_readinto( + bitmap_obj, + file, + bits_per_pixel=color_depth, + element_size=4, + reverse_pixels_in_element=True, + reverse_rows=True, + ) + + else: # use the standard file.readinto + chunk = bytearray(line_size) + for y in range(range1, range2, range3): + file.readinto(chunk) + pixels_per_byte = 8 // color_depth + offset = y * width + + for x in range(width): + i = x // pixels_per_byte + 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 2d0f228..f16b79e 100644 --- a/adafruit_imageload/bmp/negative_height_check.py +++ b/adafruit_imageload/bmp/negative_height_check.py @@ -1,11 +1,18 @@ +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Matt Land +# +# SPDX-License-Identifier: MIT + """ 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 c5ead05..e5183c1 100644 --- a/adafruit_imageload/gif.py +++ b/adafruit_imageload/gif.py @@ -1,24 +1,8 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2019 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land # -# Copyright (c) 2019 Radomir Dopieralski -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.gif` ==================================================== @@ -26,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. + Returns tuple of bitmap object and palette object. - :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""" + :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`. + :param object palette: Type to store the palette. Must have API similar to + `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] @@ -112,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() @@ -141,30 +140,30 @@ 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 - byte = next(data) # pylint: disable=stop-iteration-return try: - while True: - code = 0 - for i in range(dictionary.code_len): - code |= ((byte >> bit) & 0x01) << i - bit += 1 - if bit >= 8: - bit = 0 - byte = next(data) # pylint: disable=stop-iteration-return - yield dictionary.decode(code) - except EndOfData: - while True: - next(data) # pylint: disable=stop-iteration-return + byte = next(data) + try: + while True: + code = 0 + for i in range(dictionary.code_len): + code |= ((byte >> bit) & 0x01) << i + bit += 1 + if bit >= 8: + bit = 0 + byte = next(data) + yield dictionary.decode(code) + except EndOfData: + while True: + 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 802ab2a..b178299 100644 --- a/adafruit_imageload/pnm/__init__.py +++ b/adafruit_imageload/pnm/__init__.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm` ==================================================== @@ -28,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 @@ -54,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 2415a17..872846c 100644 --- a/adafruit_imageload/pnm/pbm_ascii.py +++ b/adafruit_imageload/pnm/pbm_ascii.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.pbm_ascii` ==================================================== @@ -30,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 4ebac3e..53d92df 100644 --- a/adafruit_imageload/pnm/pbm_binary.py +++ b/adafruit_imageload/pnm/pbm_binary.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.pbm_binary` ==================================================== @@ -30,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: @@ -45,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: @@ -55,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) """ @@ -64,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 167213f..8acefb5 100644 --- a/adafruit_imageload/pnm/pgm/__init__.py +++ b/adafruit_imageload/pnm/pgm/__init__.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.pgm` ==================================================== @@ -28,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 + + from displayio import Bitmap, Palette + + from ...displayio_types import BitmapConstructor, PaletteConstructor +except ImportError: + pass -def load(file, magic_number, header, *, bitmap=None, palette=None): +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 38f5c22..7c597ca 100644 --- a/adafruit_imageload/pnm/pgm/ascii.py +++ b/adafruit_imageload/pnm/pgm/ascii.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.pgm.ascii` ==================================================== @@ -29,13 +15,29 @@ """ +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 + -def load(file, width, height, bitmap=None, palette=None): +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) """ data_start = file.tell() # keep this so we can rewind - palette_colors = set() + _palette_colors = set() pixel = bytearray() # build a set of all colors present in the file, so palette and bitmap can be constructed while True: @@ -44,14 +46,15 @@ def load(file, width, height, bitmap=None, palette=None): break if not byte.isdigit(): int_pixel = int("".join(["%c" % char for char in pixel])) - palette_colors.add(int_pixel) + _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): @@ -62,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): +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 2925280..700b563 100644 --- a/adafruit_imageload/pnm/pgm/binary.py +++ b/adafruit_imageload/pnm/pgm/binary.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.pgm.binary` ==================================================== @@ -29,36 +15,53 @@ """ +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 + -def load(file, width, height, bitmap=None, palette=None): +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 """ - palette = palette_class(len(palette_colors)) + _palette = palette_class(len(palette_colors)) for counter, color in enumerate(palette_colors): - palette[counter] = bytes([color, color, color]) - return palette + _palette[counter] = bytes([color, color, color]) + return _palette diff --git a/adafruit_imageload/pnm/ppm_ascii.py b/adafruit_imageload/pnm/ppm_ascii.py index 013023f..e79b70b 100644 --- a/adafruit_imageload/pnm/ppm_ascii.py +++ b/adafruit_imageload/pnm/ppm_ascii.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.ppm_ascii` ==================================================== @@ -30,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, + ) + + from displayio import Bitmap, Palette + + from ..displayio_types import BitmapConstructor, PaletteConstructor +except ImportError: + pass + -def load(file, width, height, bitmap=None, palette=None): +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: @@ -44,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 d32d71a..56540d3 100644 --- a/adafruit_imageload/pnm/ppm_binary.py +++ b/adafruit_imageload/pnm/ppm_binary.py @@ -1,24 +1,10 @@ -# The MIT License (MIT) +# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries +# SPDX-FileCopyrightText: 2022-2023 Matt Land +# SPDX-FileCopyrightText: Brooke Storm +# SPDX-FileCopyrightText: Sam McGahan # -# Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# SPDX-License-Identifier: MIT + """ `adafruit_imageload.pnm.ppm_binary` ==================================================== @@ -30,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): @@ -48,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/_static/favicon.ico.license b/docs/_static/favicon.ico.license new file mode 100644 index 0000000..86a3fbf --- /dev/null +++ b/docs/_static/favicon.ico.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries + +SPDX-License-Identifier: CC-BY-4.0 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/api.rst.license b/docs/api.rst.license new file mode 100644 index 0000000..9aae48d --- /dev/null +++ b/docs/api.rst.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/conf.py b/docs/conf.py index 0e79813..15c9fc0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,8 @@ -# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT +import datetime import os import sys @@ -12,6 +15,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -25,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. @@ -39,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 @@ -56,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. @@ -88,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/developing.rst.license b/docs/developing.rst.license new file mode 100644 index 0000000..acb2140 --- /dev/null +++ b/docs/developing.rst.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries + +SPDX-License-Identifier: MIT diff --git a/docs/examples.rst b/docs/examples.rst index 6390cd8..6dc236d 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -6,3 +6,21 @@ Ensure your image loads with this simple test. .. literalinclude:: ../examples/imageload_simpletest.py :caption: examples/imageload_simpletest.py :linenos: + +Requests test +------------- + +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/examples.rst.license b/docs/examples.rst.license new file mode 100644 index 0000000..9aae48d --- /dev/null +++ b/docs/examples.rst.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/index.rst b/docs/index.rst index d8882d8..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/index.rst.license b/docs/index.rst.license new file mode 100644 index 0000000..9aae48d --- /dev/null +++ b/docs/index.rst.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..979f568 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/imageload_colorwheel.py b/examples/imageload_colorwheel.py index ceb23d2..58bc889 100644 --- a/examples/imageload_colorwheel.py +++ b/examples/imageload_colorwheel.py @@ -1,5 +1,9 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + import board import displayio + import adafruit_imageload display = board.DISPLAY @@ -12,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 new file mode 100644 index 0000000..79c78dd --- /dev/null +++ b/examples/imageload_from_web.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2021 Tim C for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +imageload example for esp32s2 that loads an image fetched via +adafruit_requests using BytesIO +""" + +from io import BytesIO +from os import getenv + +import adafruit_connection_manager +import adafruit_requests as requests +import board +import displayio +import wifi + +import adafruit_imageload + +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +wifi.radio.connect(ssid, password) + +print("My IP address is", wifi.radio.ipv4_address) + +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) + +url = "https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_ImageLoad/main/examples/images/4bit.bmp" + +print(f"Fetching text from {url}") +response = https.get(url) +print("GET complete") + +bytes_img = BytesIO(response.content) +image, palette = adafruit_imageload.load(bytes_img) +tile_grid = displayio.TileGrid(image, pixel_shader=palette) + +group = displayio.Group(scale=1) +group.append(tile_grid) +board.DISPLAY.root_group = group + +response.close() + +while True: + pass 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 new file mode 100644 index 0000000..cbee121 --- /dev/null +++ b/examples/imageload_magtag_simpletest.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +""" +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.) +# see guide for setting up external displays (TFT / OLED breakouts, RGB matrices, etc.) +# https://learn.adafruit.com/circuitpython-display-support-using-displayio/display-and-display-bus +display = board.DISPLAY + +# wait until the display is ready +time.sleep(display.time_to_refresh) + +image, palette = adafruit_imageload.load("images/magtag_2x2_test.bmp") + +tile_grid = displayio.TileGrid(image, pixel_shader=palette) + +# scale 8 for full screen +group = displayio.Group(scale=8) +group.append(tile_grid) + +# show the group and refresh +display.root_group = group +display.refresh() + +while True: + pass diff --git a/examples/imageload_netpbm.py b/examples/imageload_netpbm.py index 9d3ed51..13c9b58 100644 --- a/examples/imageload_netpbm.py +++ b/examples/imageload_netpbm.py @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + """ This is a hardware testing script for PBM Tested with Feather M4 Express and 2.4" Featherwing @@ -9,9 +12,11 @@ """ +import adafruit_ili9341 import board import displayio -import adafruit_ili9341 +import fourwire + import adafruit_imageload spi = board.SPI() @@ -19,13 +24,13 @@ tft_dc = board.D10 displayio.release_displays() -display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs) +display_bus = fourwire.FourWire(spi, command=tft_dc, chip_select=tft_cs) display = adafruit_ili9341.ILI9341(display_bus, width=320, height=240) # Make the display context -splash = displayio.Group(max_size=10) -display.show(splash) +splash = displayio.Group() +display.root_group = splash # image = "images/netpbm_p1_mono_ascii.pbm" # image = "images/netpbm_p2_ascii.pgm" # image = "images/netpbm_p3_rgb_ascii.ppm" @@ -33,9 +38,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 f36929b..1481791 100644 --- a/examples/imageload_simpletest.py +++ b/examples/imageload_simpletest.py @@ -1,5 +1,9 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + import board import displayio + import adafruit_imageload image, palette = adafruit_imageload.load("images/4bit.bmp") @@ -8,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/1bit-not-byte-aligned.bmp.license b/examples/images/1bit-not-byte-aligned.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/1bit-not-byte-aligned.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/1bit.bmp.license b/examples/images/1bit.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/1bit.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/2bit.bmp.license b/examples/images/2bit.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/2bit.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/4bit.bmp.license b/examples/images/4bit.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/4bit.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/4bit_rle.bmp.license b/examples/images/4bit_rle.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/4bit_rle.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/8bit_rle.bmp.license b/examples/images/8bit_rle.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/8bit_rle.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT 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/color_wheel.bmp.license b/examples/images/color_wheel.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/color_wheel.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/color_wheel_rle.bmp.license b/examples/images/color_wheel_rle.bmp.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/color_wheel_rle.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/magtag_2x2_test.bmp b/examples/images/magtag_2x2_test.bmp new file mode 100644 index 0000000..bae23f7 Binary files /dev/null and b/examples/images/magtag_2x2_test.bmp differ diff --git a/examples/images/magtag_2x2_test.bmp.license b/examples/images/magtag_2x2_test.bmp.license new file mode 100644 index 0000000..132a2e4 --- /dev/null +++ b/examples/images/magtag_2x2_test.bmp.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2020 Foamyguy +# +# SPDX-License-Identifier: Unlicense diff --git a/examples/images/netpbm_p1_mono_ascii.pbm.license b/examples/images/netpbm_p1_mono_ascii.pbm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p1_mono_ascii.pbm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/netpbm_p2_ascii.pgm b/examples/images/netpbm_p2_ascii.pgm index c807b1a..b38401c 100644 --- a/examples/images/netpbm_p2_ascii.pgm +++ b/examples/images/netpbm_p2_ascii.pgm @@ -7,4 +7,4 @@ P2 203 0 255 0 0 62 0 128 0 84 0 62 255 0 84 0 255 0 84 0 0 84 0 128 -0 128 0 128 203 0 255 0 \ No newline at end of file +0 128 0 128 203 0 255 0 diff --git a/examples/images/netpbm_p2_ascii.pgm.license b/examples/images/netpbm_p2_ascii.pgm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p2_ascii.pgm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/netpbm_p3_rgb_ascii.ppm b/examples/images/netpbm_p3_rgb_ascii.ppm index 5030536..5d82f88 100644 --- a/examples/images/netpbm_p3_rgb_ascii.ppm +++ b/examples/images/netpbm_p3_rgb_ascii.ppm @@ -1,3 +1,3 @@ P3 16 16 255 -255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 168 121 251 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 168 121 251 168 121 251 168 121 251 168 121 251 168 121 251 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 168 121 251 214 0 255 214 0 255 214 0 255 168 121 251 168 121 251 109 0 255 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 109 0 255 168 121 251 168 121 251 214 0 255 214 0 255 214 0 255 214 0 255 168 121 251 168 121 251 168 121 251 168 121 251 168 121 251 109 0 255 109 0 255 255 255 255 255 255 255 109 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 109 0 255 109 0 255 255 255 255 255 255 255 109 0 255 230 121 251 230 121 251 230 121 251 230 121 251 230 121 251 214 0 255 230 121 251 230 121 251 230 121 251 230 121 251 230 121 251 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 109 0 255 109 0 255 230 121 251 230 121 251 230 121 251 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 \ No newline at end of file +255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 168 121 251 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 168 121 251 168 121 251 168 121 251 168 121 251 168 121 251 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 168 121 251 214 0 255 214 0 255 214 0 255 168 121 251 168 121 251 109 0 255 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 109 0 255 168 121 251 168 121 251 214 0 255 214 0 255 214 0 255 214 0 255 168 121 251 168 121 251 168 121 251 168 121 251 168 121 251 109 0 255 109 0 255 255 255 255 255 255 255 109 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 214 0 255 109 0 255 109 0 255 255 255 255 255 255 255 109 0 255 230 121 251 230 121 251 230 121 251 230 121 251 230 121 251 214 0 255 230 121 251 230 121 251 230 121 251 230 121 251 230 121 251 109 0 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 109 0 255 109 0 255 230 121 251 230 121 251 230 121 251 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 109 0 255 109 0 255 109 0 255 109 0 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 121 149 251 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 diff --git a/examples/images/netpbm_p3_rgb_ascii.ppm.license b/examples/images/netpbm_p3_rgb_ascii.ppm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p3_rgb_ascii.ppm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/netpbm_p4_mono_binary.pbm.license b/examples/images/netpbm_p4_mono_binary.pbm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p4_mono_binary.pbm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/netpbm_p4_mono_large.pbm.license b/examples/images/netpbm_p4_mono_large.pbm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p4_mono_large.pbm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# 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/netpbm_p5_binary.pgm.license b/examples/images/netpbm_p5_binary.pgm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p5_binary.pgm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/images/netpbm_p6_binary.ppm.license b/examples/images/netpbm_p6_binary.ppm.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/examples/images/netpbm_p6_binary.ppm.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# 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 f99129c..274b851 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,6 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + Adafruit-Blinka adafruit-blinka-displayio 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 c7b7dec..0000000 --- a/setup.py +++ /dev/null @@ -1,50 +0,0 @@ -"""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"], -) diff --git a/tests/__init__.py.license b/tests/__init__.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/__init__.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/tests/displayio_shared_bindings.py b/tests/displayio_shared_bindings.py index 141059e..d938e6c 100644 --- a/tests/displayio_shared_bindings.py +++ b/tests/displayio_shared_bindings.py @@ -24,8 +24,8 @@ ==================================================== The classes in this file are designed to emulate Circuitpython's displayio classes -for Bitmap and Palette. These mimic classes should have the same methods and interface as the real interface, -but with extra validation checks, warnings, and messages to facilitate debugging. +for Bitmap and Palette. These mimic classes should have the same methods and interface as the real +interface, but with extra validation checks, warnings, and messages to facilitate debugging. Code that can be run successfully against these classes will have a good chance of working correctly on hardware running Circuitpython, but without needing to upload code to a board @@ -34,10 +34,11 @@ * Author(s): Matt Land """ + from typing import Union -class Bitmap_C_Interface(object): +class Bitmap_C_Interface: """ A class to simulate the displayio.Bitmap class for testing, based on https://circuitpython.readthedocs.io/en/latest/shared-bindings/displayio/Bitmap.html @@ -49,6 +50,13 @@ def __init__(self, width: int, height: int, colors: int) -> None: self.height = height self.colors = colors self.data = {} + bits = 1 + while (colors - 1) >> bits: + if bits < 8: + bits = bits << 1 + else: + bits += 8 + self._bits_per_value = bits def _abs_pos(self, width: int, height: int) -> int: if height >= self.height: @@ -68,7 +76,7 @@ def __setitem__(self, key: Union[tuple, int], value: int) -> None: """ if isinstance(key, tuple): # order is X, Y from the docs - # https://github.com/adafruit/circuitpython/blob/master/shared-bindings/displayio/Bitmap.c + # https://github.com/adafruit/circuitpython/blob/main/shared-bindings/displayio/Bitmap.c self.__setitem__(self._abs_pos(key[0], key[1]), value) return if not isinstance(value, (int)): @@ -76,9 +84,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: @@ -88,8 +94,8 @@ def __getitem__(self, item: Union[tuple, int]) -> bytearray: raise RuntimeError(f"get position out of range {item}") try: return self.data[item] - except KeyError: - raise RuntimeError("no data at {} [{}]".format(self._decode(item), item)) + except KeyError as err: + raise RuntimeError(f"no data at {self._decode(item)} [{item}]") from err def validate(self, detect_empty_image=True) -> None: """ @@ -103,8 +109,8 @@ def validate(self, detect_empty_image=True) -> None: for x in range(self.width): try: seen_colors.add(self[x, y]) - except KeyError: - raise ValueError(f"missing data at {x},{y}") + except KeyError as err: + raise ValueError(f"missing data at {x},{y}") from err if detect_empty_image and len(seen_colors) < 2: raise ValueError( "image detected as only one color. set detect_empty_image=False to ignore" @@ -131,7 +137,7 @@ def __str__(self) -> str: return out -class Palette_C_Interface(object): +class Palette_C_Interface: """ A class to simulates the displayio.Palette class for testing, based on https://circuitpython.readthedocs.io/en/latest/shared-bindings/displayio/Palette.html @@ -158,9 +164,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]: @@ -169,9 +173,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] @@ -184,15 +186,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: - raise ValueError("missing color `{}` in palette color list".format(i)) + except IndexError as err: + raise ValueError(f"missing color `{i}` in palette color list") from err def __str__(self): """ @@ -207,6 +208,6 @@ def __str__(self): print(str(palette)) """ out = "\nPalette:\n" - for y in range(len(self.colors)): - out += f" [{y}] {self.colors[y]}\n" + for i, color in enumerate(self.colors): + out += f" [{i}] {color}\n" return out diff --git a/tests/displayio_shared_bindings.py.license b/tests/displayio_shared_bindings.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/displayio_shared_bindings.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/tests/test_bitmap_c_interface.py b/tests/test_bitmap_c_interface.py index 4055f51..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 @@ -65,11 +67,8 @@ def test_non_zero(self): def test_throws_x_out_of_range(self): b = Bitmap_C_Interface(2, 4, 1) - try: + with self.assertRaises(ValueError): b[2, 1] = 100 - self.fail("should have thrown") - except ValueError: - pass def test_max(self): b = Bitmap_C_Interface(2, 4, 1) @@ -78,18 +77,13 @@ def test_max(self): def test_uninitialized(self): b = Bitmap_C_Interface(2, 4, 1) - try: + with self.assertRaises(RuntimeError): b[1, 1] - self.fail("should have thrown") - except RuntimeError: - pass def test_validate_throws(self): b = Bitmap_C_Interface(2, 4, 1) - try: + with self.assertRaises(ValueError): b.validate() - except ValueError: - pass def test_repr(self): b = Bitmap_C_Interface(3, 2, 1) diff --git a/tests/test_bitmap_c_interface.py.license b/tests/test_bitmap_c_interface.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_bitmap_c_interface.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/tests/test_bmp_indexed_load.py b/tests/test_bmp_indexed_load.py index c0bb5eb..b9c87f1 100644 --- a/tests/test_bmp_indexed_load.py +++ b/tests/test_bmp_indexed_load.py @@ -29,18 +29,20 @@ 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( - filename=test_file, bitmap=Bitmap_C_Interface, palette=Palette_C_Interface + file_or_filename=test_file, + bitmap=Bitmap_C_Interface, + palette=Palette_C_Interface, ) self.assertTrue(isinstance(bitmap, Bitmap_C_Interface), bitmap) self.assertEqual(16, bitmap.colors) diff --git a/tests/test_bmp_indexed_load.py.license b/tests/test_bmp_indexed_load.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_bmp_indexed_load.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/tests/test_palette_c_interface.py b/tests/test_palette_c_interface.py index 909a772..e9c56c8 100644 --- a/tests/test_palette_c_interface.py +++ b/tests/test_palette_c_interface.py @@ -28,18 +28,23 @@ * Author(s): Matt Land """ + from unittest import TestCase + from .displayio_shared_bindings import Palette_C_Interface class TestPalette_C_Interface(TestCase): - def test_init_mono(self): + @staticmethod + def test_init_mono(): Palette_C_Interface(1) - def test_init_color(self): + @staticmethod + def test_init_color(): Palette_C_Interface(256) - def test_set_int(self): + @staticmethod + def test_set_int(): palette = Palette_C_Interface(1) palette[0] = 0xFFFFFF @@ -48,53 +53,57 @@ def test_get_int(self): palette[0] = 0xFFFFFF self.assertEqual(0xFFFFFF, palette[0]) - def test_set_byte(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]) - def test_set_bytearray(self): + @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) try: palette[1] = 0xFFFFFF self.fail("exception should have already thrown") - except ValueError as e: - if "greater than allowed" not in str(e): + except ValueError as err: + if "greater than allowed" not in str(err): raise 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 e: - if "should be" not in str(e): + except ValueError as err: + if "should be" not in str(err): raise - def test_validate_success(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") - except IndexError as e: - if "palette was initialized" not in str(e): + except IndexError as err: + if "palette was initialized" not in str(err): raise - def test_str(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_palette_c_interface.py.license b/tests/test_palette_c_interface.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_palette_c_interface.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/tests/test_pbm_load.py b/tests/test_pbm_load.py index d7eca5c..e999657 100644 --- a/tests/test_pbm_load.py +++ b/tests/test_pbm_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.pbm_binary import iterbits, reverse + from .displayio_shared_bindings import Bitmap_C_Interface, Palette_C_Interface @@ -38,9 +41,7 @@ class TestPbmLoad(TestCase): 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: if "Unsupported image format" not in str(caught_exception): @@ -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,6 +103,27 @@ def test_load_works_p4_binary(self): self.assertEqual(15, bitmap.height) bitmap.validate() + 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_pbm_load.py.license b/tests/test_pbm_load.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_pbm_load.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT 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_pgm_load.py.license b/tests/test_pgm_load.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_pgm_load.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT 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 diff --git a/tests/test_ppm_load.py.license b/tests/test_ppm_load.py.license new file mode 100644 index 0000000..a784acf --- /dev/null +++ b/tests/test_ppm_load.py.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT