diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf 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 new file mode 100644 index 0000000..041a337 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - 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_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 55f127b..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +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 -.idea + +# 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 -build* -bundles +.venv + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info \ No newline at end of file + +# IDE-specific files +.idea +.vscode +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ff19dde --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# 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 039eaec..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 - -# 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 - -# 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..255dafd --- /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-lts-latest + 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/.travis.yml b/.travis.yml deleted file mode 100644 index 6a11ef3..0000000 --- a/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -# This is a common .travis.yml for generating library release zip files for -# CircuitPython library releases using circuitpython-build-tools. -# See https://github.com/adafruit/circuitpython-build-tools for detailed setup -# instructions. - -dist: xenial -language: python -python: - - "3.6" - -cache: - pip: true - -# TODO: if deployment to PyPi is desired, change 'DEPLOY_PYPI' to "true", -# or remove the env block entirely and remove the condition in the -# deploy block. -env: - - DEPLOY_PYPI="true" - -deploy: - - provider: releases - api_key: "$GITHUB_TOKEN" - file_glob: true - file: "$TRAVIS_BUILD_DIR/bundles/*" - skip_cleanup: true - overwrite: true - on: - tags: true - # TODO: Use 'travis encrypt --com -r adafruit/' to generate - # the encrypted password for adafruit-travis. Paste result below. - - provider: pypi - user: adafruit-travis - password: - secure: ZxsMZrdftjJBqxdW4fowdLWFR5ykdCawV6pQt1BwRO8Q+6PGRloGkpIBQ2tj9eX85YY8q5sBIhqNwODJ5od9/B7nbx3xTo8T79O5Nq//tv9zmZaQS/uqZo8fj9TaHpaq+MVH2aCRfepey9/OzVRRsIZW/nEpaHuDPow7UtaoGFij4VsZ66RoVm88J7Zer8/bVlOdYatmMpb8SOSRE8Hj6jx7F4ayVxF2hVdzd8wOxrKObDkEFZ9ym0xYKHMWdPehtbnCOo/rgm0jtutd8plrKnTm//qNFEp6CdRcLbCEL6cQoPOWzk47p7tGe42yHllquB//f2VqmGzep3+YverAAOrPG2XOxp2ypQFc0RL6KY6CpDqWAdfYh+/H5o74oxCvRVWyUyHZ2eTHrd6YKnwlhxDTk0+A7FwforEPODm/YGxoTrRXduiD+LR4xvPFaQISAyFjIOeCYA1Yyfz4ZTQgcpXwqAa4irLlfb3rdjWRZIRnhR6mQsd1nTqDaxXcqlbL/EIH8KKG0ZBIAXL7F73ajRblaVn2iHvYkrTDKQhR8yaIFBUgAoSXdCBY1TIg3/RWU/knRyQItEKiQHXgua+gVO95GT4a2Hf2yV4y3PoaXCSoAVF24hgnHN9WRIEpyVRHgcMJpH2bLnXmDnl8KPgEqZD586tQaCqZdIdKtNJhUbo= - on: - tags: true - condition: $DEPLOY_PYPI = "true" - -install: - - pip install -r requirements.txt - - pip install circuitpython-build-tools Sphinx sphinx-rtd-theme - - pip install --force-reinstall pylint==1.9.2 - -script: - - pylint adafruit_button.py - - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.py) - - circuitpython-build-bundles --filename_prefix adafruit-circuitpython-display_button --library_location . - - cd docs && sphinx-build -E -W -b html . _build/html && cd .. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 8ee6e44..8a55c07 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,3 +1,9 @@ + + # Adafruit Community Code of Conduct ## Our Pledge @@ -34,6 +40,8 @@ Examples of unacceptable behavior by participants include: * Excessive or unwelcome helping; answering outside the scope of the question asked * Trolling, insulting/derogatory comments, and personal or political attacks +* Promoting or spreading disinformation, lies, or conspiracy theories against + a person, group, organisation, project, or community * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission @@ -41,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 @@ -72,10 +80,10 @@ 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 Helpers by tagging @community helpers. You may also send an -open message from any channel, or a direct message to @kattni#1507, -@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or -@Andon#8175. +to all Community Moderators by tagging @community moderators. You may +also send an open message from any channel, or a direct message to +@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, +@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. Email and direct message reports will be kept confidential. 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 a1c2b73..f88b195 100644 --- a/README.rst +++ b/README.rst @@ -1,18 +1,22 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-display_button/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/display_button/en/latest/ +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-display-button/badge/?version=latest + :target: https://docs.circuitpython.org/projects/display-button/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg - :target: https://discord.gg/nBQh6qu +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg + :target: https://adafru.it/discord :alt: Discord -.. image:: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Display_Button.svg?branch=master - :target: https://travis-ci.com/adafruit/Adafruit_CircuitPython_Display_Button +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Display_Button/workflows/Build%20CI/badge.svg + :target: https://github.com/adafruit/Adafruit_CircuitPython_Display_Button/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 + UI Buttons for displayio @@ -29,37 +33,44 @@ This is easily achieved by downloading Installing from PyPI -------------------- On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from -PyPI `_. To install for current user: +PyPI `_. To install for current user: .. code-block:: shell - pip3 install adafruit-circuitpython-display_button + pip3 install adafruit-circuitpython-display-button To install system-wide (this may be required in some cases): .. code-block:: shell - sudo pip3 install adafruit-circuitpython-display_button + sudo pip3 install adafruit-circuitpython-display-button To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env - source .env/bin/activate - pip3 install adafruit-circuitpython-display_button + python3 -m venv .venv + source .venv/bin/activate + pip3 install adafruit-circuitpython-display-button Usage Example ============= See examples in examples/ folder. +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. Building locally @@ -73,15 +84,15 @@ To build this library locally you'll need to install the .. code-block:: shell - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip install circuitpython-build-tools Once installed, make sure you are in the virtual environment: .. code-block:: shell - source .env/bin/activate + source .venv/bin/activate Then run the build: @@ -97,8 +108,8 @@ install dependencies (feel free to reuse the virtual environment from above): .. code-block:: shell - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip install Sphinx sphinx-rtd-theme Now, once you have the virtual environment activated: 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_button.py b/adafruit_button.py deleted file mode 100755 index 115fc66..0000000 --- a/adafruit_button.py +++ /dev/null @@ -1,202 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2019 Limor Fried for Adafruit Industries -# -# 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. -""" -`adafruit_button` -================================================================================ - -UI Buttons for displayio - - -* Author(s): Limor Fried - -Implementation Notes --------------------- - -**Software and Dependencies:** - -* Adafruit CircuitPython firmware for the supported boards: - https://github.com/adafruit/circuitpython/releases - -""" - -from micropython import const -import displayio -from adafruit_display_text.label import Label -from adafruit_display_shapes.rect import Rect -from adafruit_display_shapes.roundrect import RoundRect - -__version__ = "0.0.0-auto.0" -__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Button.git" - - -def _check_color(color): - # if a tuple is supplied, convert it to a RGB number - if isinstance(color, tuple): - r, g, b = color - return int((r << 16) + (g << 8) + (b & 0xff)) - return color - - -class Button(): - # pylint: disable=too-many-instance-attributes, too-many-locals - """Helper class for creating UI buttons for ``displayio``. - - :param x: The x position of the button. - :param y: The y position of the button. - :param width: The width of the button in pixels. - :param height: The height of the button in pixels. - :param name: The name of the button. - :param style: The style of the button. Can be RECT, ROUNDRECT, SHADOWRECT, SHADOWROUNDRECT. - Defaults to RECT. - :param fill_color: The color to fill the button. Defaults to 0xFFFFFF. - :param outline_color: The color of the outline of the button. - :param label: The text that appears inside the button. Defaults to not displaying the label. - :param label_font: The button label font. - :param label_color: The color of the button label text. Defaults to 0x0. - :param selected_fill: Inverts the fill color. - :param selected_outline: Inverts the outline color. - :param selected_label: Inverts the label color. - - """ - RECT = const(0) - ROUNDRECT = const(1) - SHADOWRECT = const(2) - SHADOWROUNDRECT = const(3) - - def __init__(self, *, x, y, width, height, name=None, style=RECT, - fill_color=0xFFFFFF, outline_color=0x0, - label=None, label_font=None, label_color=0x0, - selected_fill=None, selected_outline=None, - selected_label=None): - self.x = x - self.y = y - self.width = width - self.height = height - self._font = label_font - self._selected = False - self.group = displayio.Group() - self.name = name - self._label = label - self.body = self.fill = self.shadow = None - - self.fill_color = _check_color(fill_color) - self.outline_color = _check_color(outline_color) - self._label_color = label_color - self._label_font = label_font - # Selecting inverts the button colors! - self.selected_fill = _check_color(selected_fill) - self.selected_outline = _check_color(selected_outline) - self.selected_label = _check_color(selected_label) - - if self.selected_fill is None and fill_color is not None: - self.selected_fill = (~self.fill_color) & 0xFFFFFF - if self.selected_outline is None and outline_color is not None: - self.selected_outline = (~self.outline_color) & 0xFFFFFF - - if outline_color or fill_color: - if style == Button.RECT: - self.body = Rect(x, y, width, height, - fill=self.fill_color, outline=self.outline_color) - elif style == Button.ROUNDRECT: - self.body = RoundRect(x, y, width, height, r=10, - fill=self.fill_color, outline=self.outline_color) - elif style == Button.SHADOWRECT: - self.shadow = Rect(x + 2, y + 2, width - 2, height - 2, - fill=outline_color) - self.body = Rect(x, y, width - 2, height - 2, - fill=self.fill_color, outline=self.outline_color) - elif style == Button.SHADOWROUNDRECT: - self.shadow = RoundRect(x + 2, y + 2, width - 2, height - 2, r=10, - fill=self.outline_color) - self.body = RoundRect(x, y, width - 2, height - 2, r=10, - fill=self.fill_color, outline=self.outline_color) - if self.shadow: - self.group.append(self.shadow) - self.group.append(self.body) - - self.label = label - - # else: # ok just a bounding box - # self.bodyshape = displayio.Shape(width, height) - # self.group.append(self.bodyshape) - - @property - def label(self): - """The text label of the button""" - return self._label.text - - @label.setter - def label(self, newtext): - if self._label and (self.group[-1] == self._label): - self.group.pop() - - self._label = None - if not newtext or (self._label_color is None): # no new text - return # nothing to do! - - if not self._label_font: - raise RuntimeError("Please provide label font") - self._label = Label(self._label_font, text=newtext) - dims = self._label.bounding_box - if dims[2] >= self.width or dims[3] >= self.height: - raise RuntimeError("Button not large enough for label") - self._label.x = self.x + (self.width - dims[2]) // 2 - self._label.y = self.y + self.height // 2 - self._label.color = self._label_color - self.group.append(self._label) - - if (self.selected_label is None) and (self._label_color is not None): - self.selected_label = (~self._label_color) & 0xFFFFFF - - - @property - def selected(self): - """Selected inverts the colors.""" - return self._selected - - @selected.setter - def selected(self, value): - if value == self._selected: - return # bail now, nothing more to do - self._selected = value - if self._selected: - new_fill = self.selected_fill - new_out = self.selected_outline - new_label = self.selected_label - else: - new_fill = self.fill_color - new_out = self.outline_color - new_label = self._label_color - # update all relevant colros! - if self.body is not None: - self.body.fill = new_fill - self.body.outline = new_out - if self._label is not None: - self._label.color = new_label - - def contains(self, point): - """Used to determine if a point is contained within a button. For example, - ``button.contains(touch)`` where ``touch`` is the touch point on the screen will allow for - determining that a button has been touched. - """ - return (self.x <= point[0] <= self.x + self.width) and (self.y <= point[1] <= - self.y + self.height) diff --git a/adafruit_button/__init__.py b/adafruit_button/__init__.py new file mode 100644 index 0000000..f521f2e --- /dev/null +++ b/adafruit_button/__init__.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +""" +`adafruit_button` +================================================================================ + +UI Buttons for displayio + + +* Author(s): Limor Fried + +Implementation Notes +-------------------- + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" + +from adafruit_button.button import Button diff --git a/adafruit_button/button.py b/adafruit_button/button.py new file mode 100644 index 0000000..d81e994 --- /dev/null +++ b/adafruit_button/button.py @@ -0,0 +1,297 @@ +# SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries +# SPDX-FileCopyrightText: 2024 Channing Ramos +# +# SPDX-License-Identifier: MIT + +""" +`adafruit_button.button` +================================================================================ + +UI Buttons for displayio + + +* Author(s): Limor Fried, Channing Ramos + +Implementation Notes +-------------------- + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" + +from adafruit_display_shapes.rect import Rect +from adafruit_display_shapes.roundrect import RoundRect +from micropython import const + +from adafruit_button.button_base import ButtonBase, _check_color + +try: + from typing import Optional, Tuple, Union + + from displayio import Group + from fontio import FontProtocol +except ImportError: + pass + +__version__ = "0.0.0+auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Button.git" + + +class Button(ButtonBase): + """Helper class for creating UI buttons for ``displayio``. Provides the following + buttons: + RECT: A rectangular button. SHAWDOWRECT adds a drop shadow. + ROUNDRECT: A rectangular button with rounded corners. SHADOWROUNDRECT adds + a drop shadow. + + :param int x: The x position of the button. + :param int y: The y position of the button. + :param int width: The width of the button in pixels. + :param int height: The height of the button in pixels. + :param Optional[str] name: The name of the button. + :param style: The style of the button. Can be RECT, ROUNDRECT, SHADOWRECT, SHADOWROUNDRECT. + Defaults to RECT. + :param Optional[Union[int, Tuple[int, int, int]]] fill_color: The color to fill the button. + Accepts an int or a tuple of 3 integers representing RGB values. Defaults to 0xFFFFFF. + :param Optional[Union[int, Tuple[int, int, int]]] outline_color: The color of the outline of + the button. Accepts an int or a tuple of 3 integers representing RGB values. Defaults to 0x0. + :param Optional[str] label: The text that appears inside the button. + :param Optional[FontProtocol] label_font: The button label font. Defaults to + ''terminalio.FONT'' + :param Optional[Union[int, Tuple[int, int, int]]] label_color: The color of the button label + text. Accepts an int or a tuple of 3 integers representing RGB values. Defaults to 0x0. + :param Optional[Union[int, Tuple[int, int, int]]] selected_fill: The fill color when the + button is selected. Accepts an int or a tuple of 3 integers representing RGB values. + Defaults to the inverse of the fill_color. + :param Optional[Union[int, Tuple[int, int, int]]] selected_outline: The outline color when the + button is selected. Accepts an int or a tuple of 3 integers representing RGB values. + Defaults to the inverse of outline_color. + :param Optional[Union[int, Tuple[int, int, int]]] selected_label: The label color when the + button is selected. Accepts an int or a tuple of 3 integers representing RGB values. + Defaults to inverting the label_color. + :param Optional[int] label_scale: The scale factor used for the label. Defaults to 1. + """ + + def _empty_self_group(self) -> None: + while len(self) > 0: + self.pop() + + def _create_body(self) -> None: + if (self.outline_color is not None) or (self.fill_color is not None): + if self.style == Button.RECT: + self.body = Rect( + 0, + 0, + self.width, + self.height, + fill=self._fill_color, + outline=self._outline_color, + ) + elif self.style == Button.ROUNDRECT: + self.body = RoundRect( + 0, + 0, + self.width, + self.height, + r=10, + fill=self._fill_color, + outline=self._outline_color, + ) + elif self.style == Button.SHADOWRECT: + self.shadow = Rect(2, 2, self.width - 2, self.height - 2, fill=self.outline_color) + self.body = Rect( + 0, + 0, + self.width - 2, + self.height - 2, + fill=self._fill_color, + outline=self._outline_color, + ) + elif self.style == Button.SHADOWROUNDRECT: + self.shadow = RoundRect( + 2, + 2, + self.width - 2, + self.height - 2, + r=10, + fill=self._outline_color, + ) + self.body = RoundRect( + 0, + 0, + self.width - 2, + self.height - 2, + r=10, + fill=self._fill_color, + outline=self._outline_color, + ) + if self.shadow: + self.append(self.shadow) + + RECT = const(0) + ROUNDRECT = const(1) + SHADOWRECT = const(2) + SHADOWROUNDRECT = const(3) + + def __init__( # noqa: PLR0913 Too many arguments + self, + *, + x: int, + y: int, + width: int, + height: int, + name: Optional[str] = None, + style=RECT, + fill_color: Optional[Union[int, Tuple[int, int, int]]] = 0xFFFFFF, + outline_color: Optional[Union[int, Tuple[int, int, int]]] = 0x0, + label: Optional[str] = None, + label_font: Optional[FontProtocol] = None, + label_color: Optional[Union[int, Tuple[int, int, int]]] = 0x0, + selected_fill: Optional[Union[int, Tuple[int, int, int]]] = None, + selected_outline: Optional[Union[int, Tuple[int, int, int]]] = None, + selected_label: Optional[Union[int, Tuple[int, int, int]]] = None, + label_scale: Optional[int] = 1, + ): + super().__init__( + x=x, + y=y, + width=width, + height=height, + name=name, + label=label, + label_font=label_font, + label_color=label_color, + selected_label=selected_label, + label_scale=label_scale, + ) + + self.body = self.fill = self.shadow = None + self.style = style + + self._fill_color = _check_color(fill_color) + self._outline_color = _check_color(outline_color) + + # Selecting inverts the button colors! + self._selected_fill = _check_color(selected_fill) + self._selected_outline = _check_color(selected_outline) + + if self.selected_fill is None and fill_color is not None: + self.selected_fill = (~_check_color(self._fill_color)) & 0xFFFFFF + if self.selected_outline is None and outline_color is not None: + self.selected_outline = (~_check_color(self._outline_color)) & 0xFFFFFF + + self._create_body() + if self.body: + self.append(self.body) + + self.label = label + + def _subclass_selected_behavior(self, value: bool) -> None: + if self._selected: + new_fill = self.selected_fill + new_out = self.selected_outline + else: + new_fill = self._fill_color + new_out = self._outline_color + # update all relevant colors! + if self.body is not None: + self.body.fill = new_fill + self.body.outline = new_out + + @property + def group(self) -> Group: + """Return self for compatibility with old API.""" + print( + "Warning: The group property is being deprecated. " + "User code should be updated to add the Button directly to the " + "Display or other Groups." + ) + return self + + @property + def fill_color(self) -> Optional[int]: + """The fill color of the button body""" + return self._fill_color + + @fill_color.setter + def fill_color(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._fill_color = _check_color(new_color) + if not self.selected: + self.body.fill = self._fill_color + + @property + def outline_color(self) -> Optional[int]: + """The outline color of the button body""" + return self._outline_color + + @outline_color.setter + def outline_color(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._outline_color = _check_color(new_color) + if not self.selected: + self.body.outline = self._outline_color + + @property + def selected_fill(self) -> Optional[int]: + """The fill color of the button body when selected""" + return self._selected_fill + + @selected_fill.setter + def selected_fill(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._selected_fill = _check_color(new_color) + if self.selected: + self.body.fill = self._selected_fill + + @property + def selected_outline(self) -> Optional[int]: + """The outline color of the button body when selected""" + return self._selected_outline + + @selected_outline.setter + def selected_outline(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._selected_outline = _check_color(new_color) + if self.selected: + self.body.outline = self._selected_outline + + @property + def width(self) -> int: + """The width of the button""" + return self._width + + @width.setter + def width(self, new_width: int) -> None: + self._width = new_width + self._empty_self_group() + self._create_body() + if self.body: + self.append(self.body) + self.label = self.label + + @property + def height(self) -> int: + """The height of the button""" + return self._height + + @height.setter + def height(self, new_height: int) -> None: + self._height = new_height + self._empty_self_group() + self._create_body() + if self.body: + self.append(self.body) + self.label = self.label + + def resize(self, new_width: int, new_height: int) -> None: + """Resize the button to the new width and height given + :param int new_width: The desired width in pixels. + :param int new_height: he desired height in pixels. + """ + self._width = new_width + self._height = new_height + self._empty_self_group() + self._create_body() + if self.body: + self.append(self.body) + self.label = self.label diff --git a/adafruit_button/button_base.py b/adafruit_button/button_base.py new file mode 100644 index 0000000..7e430b6 --- /dev/null +++ b/adafruit_button/button_base.py @@ -0,0 +1,203 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# SPDX-FileCopyrightText: 2024 Channing Ramos +# +# SPDX-License-Identifier: MIT + +""" +`adafruit_button.button` +================================================================================ + +UI Buttons for displayio + + +* Author(s): Limor Fried, Channing Ramos + +Implementation Notes +-------------------- + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" + +import terminalio +from adafruit_display_text.bitmap_label import Label +from displayio import Group + +try: + from typing import Dict, List, Optional, Tuple, Union + + from fontio import FontProtocol +except ImportError: + pass + + +def _check_color(color: Optional[Union[int, tuple[int, int, int]]]) -> int: + # if a tuple is supplied, convert it to a RGB number + if isinstance(color, tuple): + r, g, b = color + return int((r << 16) + (g << 8) + (b & 0xFF)) + return color + + +class ButtonBase(Group): + """Superclass for creating UI buttons for ``displayio``. + + :param int x: The x position of the button. + :param int y: The y position of the button. + :param int width: The width of the button in tiles. + :param int height: The height of the button in tiles. + :param Optional[str] name: A name, or miscellaneous string that is stored on the button. + :param Optional[str] label: The text that appears inside the button. + :param Optional[FontProtocol] label_font: The button label font. + Defaults to ''terminalio.FONT'' + :param Optional[Union[int, Tuple[int, int, int]]] label_color: The color of the label text. + Defaults to 0x0. Accepts an int or a tuple of 3 integers representing RGB values. + :param Optional[Union[int, Tuple[int, int, int]]] selected_label: The color of the label text + when the button is selected. Accepts an int or a tuple of 3 integers representing RGB values. + Defaults to an inverse of label_color. + :param Optional[int] label_scale: The scale factor used for the label. Defaults to 1. + """ + + def __init__( # noqa: PLR0913 Too many arguments + self, + *, + x: int, + y: int, + width: int, + height: int, + name: Optional[str] = None, + label: Optional[str] = None, + label_font: Optional[FontProtocol] = None, + label_color: Optional[Union[int, Tuple[int, int, int]]] = 0x0, + selected_label: Optional[Union[int, Tuple[int, int, int]]] = None, + label_scale: Optional[int] = 1, + ) -> None: + super().__init__(x=x, y=y) + self.x = x + self.y = y + self._width = width + self._height = height + self._font = label_font + self._selected = False + self._name = name + self._label = label + self._label_color = _check_color(label_color) + self._label_font = label_font + self._selected_label = _check_color(selected_label) + self._label_scale = label_scale + + @property + def label(self) -> Optional[str]: + """The text label of the button""" + return getattr(self._label, "text", None) + + @label.setter + def label(self, newtext: str) -> None: + if self._label and self and (self[-1] == self._label): + self.pop() + + self._label = None + if not newtext or (self._label_color is None): # no new text + return # nothing to do! + + if not self._label_font: + self._label_font = terminalio.FONT + self._label = Label(self._label_font, text=newtext, scale=self._label_scale) + dims = list(self._label.bounding_box) + dims[2] *= self._label.scale + dims[3] *= self._label.scale + if dims[2] >= self.width or dims[3] >= self.height: + while len(self._label.text) > 1 and (dims[2] >= self.width or dims[3] >= self.height): + self._label.text = f"{self._label.text[:-2]}." + dims = list(self._label.bounding_box) + dims[2] *= self._label.scale + dims[3] *= self._label.scale + if len(self._label.text) <= 1: + raise RuntimeError("Button not large enough for label") + self._label.x = (self.width - dims[2]) // 2 + self._label.y = self.height // 2 + self._label.color = self._label_color if not self.selected else self._selected_label + self.append(self._label) + + if (self.selected_label is None) and (self._label_color is not None): + self.selected_label = (~_check_color(self._label_color)) & 0xFFFFFF + + def _subclass_selected_behavior(self, value: bool): + # Subclasses should override this! + pass + + @property + def selected(self) -> bool: + """Returns whether the button is selected.""" + return self._selected + + @selected.setter + def selected(self, value: bool) -> None: + if value == self._selected: + return # bail now, nothing more to do + self._selected = value + + if self._selected: + new_label = self.selected_label + else: + new_label = self._label_color + if self._label is not None: + self._label.color = new_label + + self._subclass_selected_behavior(value) + + @property + def selected_label(self) -> int: + """The font color of the button when selected. + If no color is specified it defaults to the inverse of the label_color""" + return self._selected_label + + @selected_label.setter + def selected_label(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._selected_label = _check_color(new_color) + + @property + def label_color(self) -> int: + """The font color of the button""" + return self._label_color + + @label_color.setter + def label_color(self, new_color: Union[int, Tuple[int, int, int]]) -> None: + self._label_color = _check_color(new_color) + self._label.color = self._label_color + + @property + def name(self) -> str: + """The name of the button""" + return self._name + + @name.setter + def name(self, new_name: str) -> None: + self._name = new_name + + def contains(self, point: Union[tuple[int, int], List[int], List[Dict[str, int]]]) -> bool: + """Used to determine if a point is contained within a button. For example, + ``button.contains(touch)`` where ``touch`` is the touch point on the screen will allow for + determining that a button has been touched. + """ + if isinstance(point, tuple) or (isinstance(point, list) and isinstance(point[0], int)): + return (self.x <= point[0] <= self.x + self.width) and ( + self.y <= point[1] <= self.y + self.height + ) + elif isinstance(point, list): + touch_points = point + if len(touch_points) == 0: + return False + for touch_point in touch_points: + if ( + isinstance(touch_point, dict) + and "x" in touch_point.keys() + and "y" in touch_point.keys() + ): + if self.contains((touch_point["x"], touch_point["y"])): + return True + + return False diff --git a/adafruit_button/sprite_button.py b/adafruit_button/sprite_button.py new file mode 100644 index 0000000..e8f2f44 --- /dev/null +++ b/adafruit_button/sprite_button.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# SPDX-FileCopyrightText: 2024 Channing Ramos +# +# SPDX-License-Identifier: MIT + +""" +`adafruit_button.button` +================================================================================ + +Bitmap 3x3 Spritesheet based UI Button for displayio + + +* Author(s): Tim Cocks, Channing Ramos + +Implementation Notes +-------------------- + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" + +from adafruit_imageload import load +from adafruit_imageload.tilegrid_inflator import inflate_tilegrid + +from adafruit_button.button_base import ButtonBase + +try: + from typing import Optional, Tuple, Union + + from fontio import FontProtocol +except ImportError: + pass + + +class SpriteButton(ButtonBase): + """Helper class for creating 3x3 Bitmap Spritesheet UI buttons for ``displayio``. + Compatible with any format supported by ''adafruit_imageload''. + + :param int x: The x position of the button. + :param int y: The y position of the button. + :param int width: The width of the button in tiles. + :param int height: The height of the button in tiles. + :param Optional[str] name: A name, or miscellaneous string that is stored on the button. + :param Optional[str] label: The text that appears inside the button. + :param Optional[FontProtocol] label_font: The button label font. + :param Optional[Union[int, Tuple[int, int, int]]] label_color: The color of the label text. + Accepts either an integer or a tuple of 3 integers representing RGB values. Defaults to 0x0. + :param Optional[Union[int, Tuple[int, int, int]]] selected_label: The color of the button label + text when the button is selected. Accepts either an integer or a tuple of 3 integers + representing RGB values. Defaults to the inverse of label_color. + :param str bmp_path: The path of the 3x3 spritesheet mage file + :param Optional[str] selected_bmp_path: The path of the 3x3 spritesheet image file to use when + pressed + :param Optional[Union[int, Tuple]] transparent_index: Palette index(s) that will be set to + transparent. PNG files have these index(s) set automatically. Not compatible with JPG files. + :param Optional[int] label_scale: The scale multiplier of the button label. Defaults to 1. + """ + + def __init__( # noqa: PLR0913 Too many arguments + self, + *, + x: int, + y: int, + width: int, + height: int, + name: Optional[str] = None, + label: Optional[str] = None, + label_font: Optional[FontProtocol] = None, + label_color: Optional[Union[int, Tuple[int, int, int]]] = 0x0, + selected_label: Optional[Union[int, Tuple[int, int, int]]] = None, + bmp_path: str = None, + selected_bmp_path: Optional[str] = None, + transparent_index: Optional[Union[int, Tuple]] = None, + label_scale: Optional[int] = 1, + ): + if bmp_path is None: + raise ValueError("Please supply bmp_path. It cannot be None.") + + super().__init__( + x=x, + y=y, + width=width, + height=height, + name=name, + label=label, + label_font=label_font, + label_color=label_color, + selected_label=selected_label, + label_scale=label_scale, + ) + + self._bmp, self._bmp_palette = load(bmp_path) + + self._selected_bmp = None + self._selected_bmp_palette = None + self._selected = False + + if selected_bmp_path is not None: + self._selected_bmp, self._selected_bmp_palette = load(selected_bmp_path) + if transparent_index is not None: + if isinstance(transparent_index, tuple): + for _index in transparent_index: + self._selected_bmp_palette.make_transparent(_index) + elif isinstance(transparent_index, int): + self._selected_bmp_palette.make_transparent(transparent_index) + + self._btn_tilegrid = inflate_tilegrid( + bmp_obj=self._bmp, + bmp_palette=self._bmp_palette, + target_size=( + width // (self._bmp.width // 3), + height // (self._bmp.height // 3), + ), + transparent_index=transparent_index, + ) + self.append(self._btn_tilegrid) + + self.label = label + + @property + def width(self) -> int: + """The width of the button. Read-Only""" + return self._width + + @property + def height(self) -> int: + """The height of the button. Read-Only""" + return self._height + + def _subclass_selected_behavior(self, value: bool) -> None: + if self._selected: + if self._selected_bmp is not None: + self._btn_tilegrid.bitmap = self._selected_bmp + self._btn_tilegrid.pixel_shader = self._selected_bmp_palette + else: + self._btn_tilegrid.bitmap = self._bmp + self._btn_tilegrid.pixel_shader = self._bmp_palette diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..d60cf4b --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,8 @@ +/* SPDX-FileCopyrightText: 2025 Sam Blenny + * SPDX-License-Identifier: MIT + */ + +/* Monkey patch the rtd theme to prevent horizontal stacking of short items + * see https://github.com/readthedocs/sphinx_rtd_theme/issues/1301 + */ +.py.property{display: block !important;} 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 49c1de1..b604b89 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -6,3 +6,12 @@ .. automodule:: adafruit_button :members: + +.. automodule:: adafruit_button.button_base + :members: + +.. automodule:: adafruit_button.button + :members: + +.. automodule:: adafruit_button.sprite_button + :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 276f652..013559e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,8 +1,12 @@ -# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT +import datetime import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,54 +14,63 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinxcontrib.jquery", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # TODO: Please Read! # Uncomment the below if you use native CircuitPython modules such as # digitalio, micropython and busio. List the modules you use. Without it, the # autodoc module docs will fail to generate with a warning. -autodoc_mock_imports = ["displayio", "adafruit_display_text", "adafruit_display_shapes"] +autodoc_mock_imports = ["displayio", "bitmaptools", "terminalio", "fontio"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit Display_Button Library' -copyright = u'2019 Limor Fried' -author = u'Limor Fried' +project = "Adafruit Display_Button Library" +creation_year = "2019" +current_year = str(datetime.datetime.now().year) +year_duration = ( + current_year if current_year == creation_year else creation_year + " - " + current_year +) +copyright = year_duration + " Limor Fried" +author = "Limor Fried" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # 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. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -69,7 +82,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -84,59 +97,55 @@ # 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, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] + +# Include extra css to work around rtd theme glitches +html_css_files = ["custom.css"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitDisplay_buttonLibrarydoc' +htmlhelp_basename = "AdafruitDisplay_buttonLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitDisplay_ButtonLibrary.tex', u'AdafruitDisplay_Button Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitDisplay_ButtonLibrary.tex", + "AdafruitDisplay_Button Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -144,8 +153,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitDisplay_Buttonlibrary', u'Adafruit Display_Button Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitDisplay_Buttonlibrary", + "Adafruit Display_Button Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -154,7 +168,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitDisplay_ButtonLibrary', u'Adafruit Display_Button Library Documentation', - author, 'AdafruitDisplay_ButtonLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitDisplay_ButtonLibrary", + "Adafruit Display_Button Library Documentation", + author, + "AdafruitDisplay_ButtonLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/docs/examples.rst b/docs/examples.rst index f734fd0..30c5250 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -6,3 +6,39 @@ Ensure your device works with this simple test. .. literalinclude:: ../examples/display_button_simpletest.py :caption: examples/display_button_simpletest.py :linenos: + +Button Color Properties +----------------------- + +Demonstrate the different color possibilities present in the library + +.. literalinclude:: ../examples/display_button_color_properties.py + :caption: examples/display_button_color_properties.py + :linenos: + +Button Custom Font +------------------ + +Shows how to use different fonts with your button + +.. literalinclude:: ../examples/display_button_customfont.py + :caption: examples/display_button_customfont.py + :linenos: + +Soundboard +---------- + +A soundboard made with buttons + +.. literalinclude:: ../examples/display_button_soundboard.py + :caption: examples/display_button_soundboard.py + :linenos: + +Sprite Button +------------- + +Custom sprite button + +.. literalinclude:: ../examples/display_button_spritebutton_simpletest.py + :caption: examples/display_button_spritebutton_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 bf53505..d699318 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,8 +31,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/bmps/gradient_button_0.bmp b/examples/bmps/gradient_button_0.bmp new file mode 100644 index 0000000..bfa8cfa Binary files /dev/null and b/examples/bmps/gradient_button_0.bmp differ diff --git a/examples/bmps/gradient_button_0.bmp.license b/examples/bmps/gradient_button_0.bmp.license new file mode 100644 index 0000000..8f7990c --- /dev/null +++ b/examples/bmps/gradient_button_0.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/bmps/gradient_button_1.bmp b/examples/bmps/gradient_button_1.bmp new file mode 100644 index 0000000..ba6d75c Binary files /dev/null and b/examples/bmps/gradient_button_1.bmp differ diff --git a/examples/bmps/gradient_button_1.bmp.license b/examples/bmps/gradient_button_1.bmp.license new file mode 100644 index 0000000..8f7990c --- /dev/null +++ b/examples/bmps/gradient_button_1.bmp.license @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT diff --git a/examples/display_button_color_properties.py b/examples/display_button_color_properties.py new file mode 100644 index 0000000..9ad73a0 --- /dev/null +++ b/examples/display_button_color_properties.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: 2021 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +""" +Basic example that illustrates how to set the various color options on the button using +properties after the button has been initialized. +""" + +import adafruit_touchscreen +import board +import displayio +import terminalio + +from adafruit_button import Button + +# use built in display (MagTag, 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 + +# --| Button Config |------------------------------------------------- +BUTTON_X = 110 +BUTTON_Y = 95 +BUTTON_WIDTH = 100 +BUTTON_HEIGHT = 50 +BUTTON_STYLE = Button.ROUNDRECT +BUTTON_FILL_COLOR = 0xAA0000 +BUTTON_OUTLINE_COLOR = 0x0000FF +BUTTON_LABEL = "HELLO WORLD" +BUTTON_LABEL_COLOR = 0x000000 +# --| Button Config |------------------------------------------------- + +# Setup touchscreen (PyPortal) +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(display.width, display.height), +) + +# Make the display context +splash = displayio.Group() +display.root_group = splash + +# Make the button +button = Button( + x=BUTTON_X, + y=BUTTON_Y, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + style=BUTTON_STYLE, + fill_color=BUTTON_FILL_COLOR, + outline_color=BUTTON_OUTLINE_COLOR, + label="HELLO WORLD", + label_font=terminalio.FONT, + label_color=BUTTON_LABEL_COLOR, +) + +button.fill_color = 0x00FF00 +button.outline_color = 0xFF0000 + +button.selected_fill = (0, 0, 255) +button.selected_outline = (255, 0, 0) + +button.label_color = 0xFF0000 +button.selected_label = 0x00FF00 + +# Add button to the display context +splash.append(button) + +# Loop and look for touches +while True: + p = ts.touch_point + if p: + if button.contains(p): + print(p) + button.selected = True + else: + button.selected = False diff --git a/examples/display_button_customfont.py b/examples/display_button_customfont.py new file mode 100644 index 0000000..eb6a3ae --- /dev/null +++ b/examples/display_button_customfont.py @@ -0,0 +1,166 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +Button example with a custom font. +""" + +import os + +import adafruit_touchscreen +import board +import displayio +from adafruit_bitmap_font import bitmap_font + +from adafruit_button import Button + +# use built in display (MagTag, 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 + +# These pins are used as both analog and digital! XL, XR and YU must be analog +# and digital capable. YD just need to be digital +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(display.width, display.height), +) + +# the current working directory (where this file is) +cwd = ("/" + __file__).rsplit("/", 1)[0] +fonts = [ + file + for file in os.listdir(cwd + "/fonts/") + if (file.endswith(".bdf") and not file.startswith("._")) +] +for i, filename in enumerate(fonts): + fonts[i] = cwd + "/fonts/" + filename +print(fonts) +THE_FONT = "/fonts/Arial-12.bdf" +DISPLAY_STRING = "Button Text" + +# Make the display context +splash = displayio.Group() +display.root_group = splash +BUTTON_WIDTH = 80 +BUTTON_HEIGHT = 40 +BUTTON_MARGIN = 20 + +########################################################################## +# Make a background color fill + +color_bitmap = displayio.Bitmap(display.width, display.height, 1) +color_palette = displayio.Palette(1) +color_palette[0] = 0x404040 +bg_sprite = displayio.TileGrid(color_bitmap, pixel_shader=color_palette, x=0, y=0) +print(bg_sprite.x, bg_sprite.y) +splash.append(bg_sprite) + +########################################################################## + +# Load the font +font = bitmap_font.load_font(THE_FONT) + +buttons = [] +# Default button styling: +button_0 = Button( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button0", + label_font=font, +) +buttons.append(button_0) + +# a button with no indicators at all +button_1 = Button( + x=BUTTON_MARGIN * 2 + BUTTON_WIDTH, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + fill_color=None, + outline_color=None, +) +buttons.append(button_1) + +# various colorings +button_2 = Button( + x=BUTTON_MARGIN * 3 + 2 * BUTTON_WIDTH, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button2", + label_font=font, + label_color=0x0000FF, + fill_color=0x00FF00, + outline_color=0xFF0000, +) +buttons.append(button_2) + +# Transparent button with text +button_3 = Button( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN * 2 + BUTTON_HEIGHT, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button3", + label_font=font, + label_color=0x0, + fill_color=None, + outline_color=None, +) +buttons.append(button_3) + +# a roundrect +button_4 = Button( + x=BUTTON_MARGIN * 2 + BUTTON_WIDTH, + y=BUTTON_MARGIN * 2 + BUTTON_HEIGHT, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button4", + label_font=font, + style=Button.ROUNDRECT, +) +buttons.append(button_4) + +# a shadowrect +button_5 = Button( + x=BUTTON_MARGIN * 3 + BUTTON_WIDTH * 2, + y=BUTTON_MARGIN * 2 + BUTTON_HEIGHT, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button5", + label_font=font, + style=Button.SHADOWRECT, +) +buttons.append(button_5) + +# a shadowroundrect +button_6 = Button( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN * 3 + BUTTON_HEIGHT * 2, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button6", + label_font=font, + style=Button.SHADOWROUNDRECT, +) +buttons.append(button_6) + +for b in buttons: + splash.append(b) + +while True: + p = ts.touch_point + if p: + print(p) + for i, b in enumerate(buttons): + if b.contains(p): + print("Button %d pressed" % i) + b.selected = True + else: + b.selected = False diff --git a/examples/display_button_debounced.py b/examples/display_button_debounced.py new file mode 100644 index 0000000..8a0471b --- /dev/null +++ b/examples/display_button_debounced.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +Basic debounced button example. +""" + +import adafruit_touchscreen +import board +import displayio +import terminalio + +from adafruit_button import Button + +# use built in display (MagTag, 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 + +# --| Button Config |------------------------------------------------- +BUTTON_X = 110 +BUTTON_Y = 95 +BUTTON_WIDTH = 100 +BUTTON_HEIGHT = 50 +BUTTON_STYLE = Button.ROUNDRECT +BUTTON_FILL_COLOR = 0x00FFFF +BUTTON_OUTLINE_COLOR = 0xFF00FF +BUTTON_LABEL = "HELLO WORLD" +BUTTON_LABEL_COLOR = 0x000000 +# --| Button Config |------------------------------------------------- + +# Setup touchscreen (PyPortal) +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(display.width, display.height), +) + +# Make the display context +splash = displayio.Group() +display.root_group = splash + +# Make the button +button = Button( + x=BUTTON_X, + y=BUTTON_Y, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + style=BUTTON_STYLE, + fill_color=BUTTON_FILL_COLOR, + outline_color=BUTTON_OUTLINE_COLOR, + label=BUTTON_LABEL, + label_font=terminalio.FONT, + label_color=BUTTON_LABEL_COLOR, +) + +# Add button to the display context +splash.append(button) + +# Loop and look for touches +while True: + p = ts.touch_point + if p: + if button.contains(p): + if not button.selected: + button.selected = True + print("pressed") + else: + button.selected = False # if touch is dragged outside of button + else: + button.selected = False # if touch is released diff --git a/examples/display_button_simpletest.py b/examples/display_button_simpletest.py index 04fda4b..f8d8546 100644 --- a/examples/display_button_simpletest.py +++ b/examples/display_button_simpletest.py @@ -1,109 +1,71 @@ -import os +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +Simple button example. +""" + +import adafruit_touchscreen import board import displayio -from adafruit_bitmap_font import bitmap_font -from adafruit_button import Button -import adafruit_touchscreen +import terminalio -# These pins are used as both analog and digital! XL, XR and YU must be analog -# and digital capable. YD just need to be digital -ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, - board.TOUCH_YD, board.TOUCH_YU, - calibration=((5200, 59000), (5800, 57000)), - size=(320, 240)) +from adafruit_button import Button -# the current working directory (where this file is) -cwd = ("/"+__file__).rsplit('/', 1)[0] -fonts = [file for file in os.listdir(cwd+"/fonts/") - if (file.endswith(".bdf") and not file.startswith("._"))] -for i, filename in enumerate(fonts): - fonts[i] = cwd+"/fonts/"+filename -print(fonts) -THE_FONT = "/fonts/Chicago-12.bdf" -DISPLAY_STRING = "Button Text" +# use built in display (MagTag, 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 + +# --| Button Config |------------------------------------------------- +BUTTON_X = 110 +BUTTON_Y = 95 +BUTTON_WIDTH = 100 +BUTTON_HEIGHT = 50 +BUTTON_STYLE = Button.ROUNDRECT +BUTTON_FILL_COLOR = 0x00FFFF +BUTTON_OUTLINE_COLOR = 0xFF00FF +BUTTON_LABEL = "HELLO WORLD" +BUTTON_LABEL_COLOR = 0x000000 +# --| Button Config |------------------------------------------------- + +# Setup touchscreen (PyPortal) +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(display.width, display.height), +) # Make the display context -splash = displayio.Group(max_size=20) -board.DISPLAY.show(splash) -BUTTON_WIDTH = 80 -BUTTON_HEIGHT = 40 -BUTTON_MARGIN = 20 - -########################################################################## -# Make a background color fill - -color_bitmap = displayio.Bitmap(320, 240, 1) -color_palette = displayio.Palette(1) -color_palette[0] = 0x404040 -bg_sprite = displayio.TileGrid(color_bitmap, - pixel_shader=color_palette, - position=(0, 0)) -print(bg_sprite.position) -splash.append(bg_sprite) - -########################################################################## - -# Load the font -font = bitmap_font.load_font(THE_FONT) - -buttons = [] -# Default button styling: -button_0 = Button(x=BUTTON_MARGIN, y=BUTTON_MARGIN, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button0", label_font=font) -buttons.append(button_0) - -# a button with no indicators at all -button_1 = Button(x=BUTTON_MARGIN*2+BUTTON_WIDTH, y=BUTTON_MARGIN, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - fill_color=None, outline_color=None) -buttons.append(button_1) - -# various colorings -button_2 = Button(x=BUTTON_MARGIN*3+2*BUTTON_WIDTH, y=BUTTON_MARGIN, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button2", label_font=font, label_color=0x0000FF, - fill_color=0x00FF00, outline_color=0xFF0000) -buttons.append(button_2) - -# Transparent button with text -button_3 = Button(x=BUTTON_MARGIN, y=BUTTON_MARGIN*2+BUTTON_HEIGHT, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button3", label_font=font, label_color=0x0, - fill_color=None, outline_color=None) -buttons.append(button_3) - -# a roundrect -button_4 = Button(x=BUTTON_MARGIN, y=BUTTON_MARGIN*2+BUTTON_HEIGHT, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button4", label_font=font, style=Button.ROUNDRECT) -buttons.append(button_4) - -# a shadowrect -button_5 = Button(x=BUTTON_MARGIN*2+BUTTON_WIDTH, y=BUTTON_MARGIN*2+BUTTON_HEIGHT, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button5", label_font=font, style=Button.SHADOWRECT) -buttons.append(button_5) - -# a shadowroundrect -button_6 = Button(x=BUTTON_MARGIN*3+2*BUTTON_WIDTH, y=BUTTON_MARGIN*2+BUTTON_HEIGHT, - width=BUTTON_WIDTH, height=BUTTON_HEIGHT, - label="button5", label_font=font, style=Button.SHADOWROUNDRECT) -buttons.append(button_6) - - - -for b in buttons: - splash.append(b.group) - - +splash = displayio.Group() +display.root_group = splash + +# Make the button +button = Button( + x=BUTTON_X, + y=BUTTON_Y, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + style=BUTTON_STYLE, + fill_color=BUTTON_FILL_COLOR, + outline_color=BUTTON_OUTLINE_COLOR, + label=BUTTON_LABEL, + label_font=terminalio.FONT, + label_color=BUTTON_LABEL_COLOR, +) + +# Add button to the display context +splash.append(button) + +# Loop and look for touches while True: p = ts.touch_point if p: - print(p) - for i, b in enumerate(buttons): - if b.contains(p): - print("Button %d pressed" % i) - b.selected = True - else: - b.selected = False + if button.contains(p): + button.selected = True + else: + button.selected = False # if touch is dragged outside of button + else: + button.selected = False # if touch is released diff --git a/examples/display_button_soundboard.py b/examples/display_button_soundboard.py index 340b3ff..ef52c8a 100644 --- a/examples/display_button_soundboard.py +++ b/examples/display_button_soundboard.py @@ -1,27 +1,35 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +Soundboard example with buttons. +""" + import time + from adafruit_pyportal import PyPortal + from adafruit_button import Button SHOW_BUTTONS = False # the current working directory (where this file is) -cwd = ("/"+__file__).rsplit('/', 1)[0] +cwd = ("/" + __file__).rsplit("/", 1)[0] # No internet use version of pyportal -pyportal = PyPortal(default_bg=cwd+"/button_background.bmp") +pyportal = PyPortal(default_bg=cwd + "/button_background.bmp") spots = [] -spots.append({'label': "1", 'pos': (10, 10), 'size': (60, 60), 'file': "01.wav"}) -spots.append({'label': "2", 'pos': (90, 10), 'size': (60, 60), 'file': "02.wav"}) -spots.append({'label': "3", 'pos': (170, 10), 'size': (60, 60), 'file': "03.wav"}) -spots.append({'label': "4", 'pos': (250, 10), 'size': (60, 60), 'file': "04.wav"}) -spots.append({'label': "5", 'pos': (10, 90), 'size': (60, 60), 'file': "05.wav"}) -spots.append({'label': "6", 'pos': (90, 90), 'size': (60, 60), 'file': "06.wav"}) -spots.append({'label': "7", 'pos': (170, 90), 'size': (60, 60), 'file': "07.wav"}) -spots.append({'label': "8", 'pos': (250, 90), 'size': (60, 60), 'file': "08.wav"}) -spots.append({'label': "9", 'pos': (10, 170), 'size': (60, 60), 'file': "09.wav"}) -spots.append({'label': "10", 'pos': (90, 170), 'size': (60, 60), 'file': "10.wav"}) -spots.append({'label': "11", 'pos': (170, 170), 'size': (60, 60), 'file': "11.wav"}) -spots.append({'label': "12", 'pos': (250, 170), 'size': (60, 60), 'file': "12.wav"}) +spots.append({"label": "1", "pos": (10, 10), "size": (60, 60), "file": "01.wav"}) +spots.append({"label": "2", "pos": (90, 10), "size": (60, 60), "file": "02.wav"}) +spots.append({"label": "3", "pos": (170, 10), "size": (60, 60), "file": "03.wav"}) +spots.append({"label": "4", "pos": (250, 10), "size": (60, 60), "file": "04.wav"}) +spots.append({"label": "5", "pos": (10, 90), "size": (60, 60), "file": "05.wav"}) +spots.append({"label": "6", "pos": (90, 90), "size": (60, 60), "file": "06.wav"}) +spots.append({"label": "7", "pos": (170, 90), "size": (60, 60), "file": "07.wav"}) +spots.append({"label": "8", "pos": (250, 90), "size": (60, 60), "file": "08.wav"}) +spots.append({"label": "9", "pos": (10, 170), "size": (60, 60), "file": "09.wav"}) +spots.append({"label": "10", "pos": (90, 170), "size": (60, 60), "file": "10.wav"}) +spots.append({"label": "11", "pos": (170, 170), "size": (60, 60), "file": "11.wav"}) +spots.append({"label": "12", "pos": (250, 170), "size": (60, 60), "file": "12.wav"}) buttons = [] for spot in spots: @@ -29,12 +37,18 @@ if SHOW_BUTTONS: fill = None outline = 0x00FF00 - button = Button(x=spot['pos'][0], y=spot['pos'][1], - width=spot['size'][0], height=spot['size'][1], - fill_color=fill, outline_color=outline, - label=spot['label'], label_color=None, - name=spot['file']) - pyportal.splash.append(button.group) + button = Button( + x=spot["pos"][0], + y=spot["pos"][1], + width=spot["size"][0], + height=spot["size"][1], + fill_color=fill, + outline_color=outline, + label=spot["label"], + label_color=None, + name=spot["file"], + ) + pyportal.splash.append(button) buttons.append(button) last_pressed = None @@ -46,9 +60,8 @@ for b in buttons: if b.contains(p): print("Touched", b.name) - if currently_pressed != b: # don't restart if playing - pyportal.play_file(cwd + "/" + b.name, - wait_to_finish=False) + if currently_pressed != b: # don't restart if playing + pyportal.play_file(cwd + "/" + b.name, wait_to_finish=False) currently_pressed = b break else: diff --git a/examples/display_button_spritebutton_debounced.py b/examples/display_button_spritebutton_debounced.py new file mode 100644 index 0000000..6d6f65f --- /dev/null +++ b/examples/display_button_spritebutton_debounced.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT +import time + +import adafruit_touchscreen +import board +import displayio +import terminalio + +from adafruit_button.sprite_button import SpriteButton + +""" +Sprite button debounced example +""" + +# These pins are used as both analog and digital! XL, XR and YU must be analog +# and digital capable. YD just need to be digital +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(board.DISPLAY.width, board.DISPLAY.height), +) + +# Make the display context +main_group = displayio.Group() +board.DISPLAY.root_group = main_group + +BUTTON_WIDTH = 10 * 16 +BUTTON_HEIGHT = 3 * 16 +BUTTON_MARGIN = 20 + +font = terminalio.FONT + +buttons = [] + + +button_0 = SpriteButton( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button0", + label_font=font, + bmp_path="bmps/gradient_button_0.bmp", + selected_bmp_path="bmps/gradient_button_1.bmp", + transparent_index=0, +) + +buttons.append(button_0) + +for b in buttons: + main_group.append(b) +while True: + p = ts.touch_point + if p: + for i, b in enumerate(buttons): + if b.contains(p): + if not b.selected: + print("Button %d pressed" % i) + b.selected = True + b.label = "pressed" + else: + b.selected = False + b.label = f"button{i}" + + else: + for i, b in enumerate(buttons): + if b.selected: + b.selected = False + b.label = f"button{i}" + time.sleep(0.01) diff --git a/examples/display_button_spritebutton_simpletest.py b/examples/display_button_spritebutton_simpletest.py new file mode 100644 index 0000000..1836d67 --- /dev/null +++ b/examples/display_button_spritebutton_simpletest.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: 2022 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT +import time + +import adafruit_touchscreen +import board +import displayio +import terminalio + +from adafruit_button.sprite_button import SpriteButton + +# These pins are used as both analog and digital! XL, XR and YU must be analog +# and digital capable. YD just need to be digital +ts = adafruit_touchscreen.Touchscreen( + board.TOUCH_XL, + board.TOUCH_XR, + board.TOUCH_YD, + board.TOUCH_YU, + calibration=((5200, 59000), (5800, 57000)), + size=(board.DISPLAY.width, board.DISPLAY.height), +) + +# Make the display context +main_group = displayio.Group() +board.DISPLAY.root_group = main_group + +BUTTON_WIDTH = 10 * 16 +BUTTON_HEIGHT = 3 * 16 +BUTTON_MARGIN = 20 + +font = terminalio.FONT + +buttons = [] + + +button_0 = SpriteButton( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="button0", + label_font=font, + bmp_path="bmps/gradient_button_0.bmp", + selected_bmp_path="bmps/gradient_button_1.bmp", + transparent_index=0, +) + +buttons.append(button_0) + +for b in buttons: + main_group.append(b) +while True: + p = ts.touch_point + if p: + print(p) + for i, b in enumerate(buttons): + if b.contains(p): + print("Button %d pressed" % i) + b.selected = True + b.label = "pressed" + else: + b.selected = False + b.label = "button0" + + else: + for i, b in enumerate(buttons): + if b.selected: + b.selected = False + b.label = "button0" + time.sleep(0.01) diff --git a/examples/display_button_spritebutton_tft_featherwing_simpletest.py b/examples/display_button_spritebutton_tft_featherwing_simpletest.py new file mode 100644 index 0000000..3c6ffd9 --- /dev/null +++ b/examples/display_button_spritebutton_tft_featherwing_simpletest.py @@ -0,0 +1,76 @@ +# SPDX-FileCopyrightText: 2024 DJDevon3 +# SPDX-License-Identifier: MIT +import time + +import adafruit_stmpe610 # TFT Featherwing V1 touch driver +import board +import digitalio +import displayio +import fourwire +import terminalio +from adafruit_hx8357 import HX8357 # TFT Featherwing display driver + +from adafruit_button.sprite_button import SpriteButton + +# 3.5" TFT Featherwing is 480x320 +displayio.release_displays() +DISPLAY_WIDTH = 480 +DISPLAY_HEIGHT = 320 + +# Initialize TFT Display +spi = board.SPI() +tft_cs = board.D9 +tft_dc = board.D10 +display_bus = fourwire.FourWire(spi, command=tft_dc, chip_select=tft_cs) +display = HX8357(display_bus, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT) +display.rotation = 0 +_touch_flip = (False, True) + +# Initialize 3.5" TFT Featherwing Touchscreen +ts_cs_pin = digitalio.DigitalInOut(board.D6) +touchscreen = adafruit_stmpe610.Adafruit_STMPE610_SPI( + board.SPI(), + ts_cs_pin, + calibration=((231, 3703), (287, 3787)), + size=(display.width, display.height), + disp_rotation=display.rotation, + touch_flip=_touch_flip, +) + +TEXT_WHITE = 0xFFFFFF + +# --| Button Config |-- +BUTTON_WIDTH = 7 * 16 +BUTTON_HEIGHT = 2 * 16 +BUTTON_MARGIN = 5 + +# Defiine the button +button = SpriteButton( + x=BUTTON_MARGIN, + y=BUTTON_MARGIN, + width=BUTTON_WIDTH, + height=BUTTON_HEIGHT, + label="MENU", + label_font=terminalio.FONT, + label_color=TEXT_WHITE, + bmp_path="bmps/gradient_button_0.bmp", + selected_bmp_path="bmps/gradient_button_1.bmp", + transparent_index=0, +) + +main_group = displayio.Group() +main_group.append(button) +display.root_group = main_group + +while True: + p = touchscreen.touch_point + if p: + if button.contains(p): + if not button.selected: + button.selected = True + time.sleep(0.25) # Wait a bit so we can see the button color change + print("Button Pressed") + else: + button.selected = False # When touch moves outside of button + else: + button.selected = False # When button is released diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..9c5fce5 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +adafruit-circuitpython-ImageLoad diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..4b1b695 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-display_button" +description = "UI Buttons for 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_Display_Button"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "display_button", + "buttons", + "UI", +] +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_button"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index edf9394..964ebbf 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,9 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +Adafruit-Blinka-displayio Adafruit-Blinka +adafruit-circuitpython-bitmap-font +adafruit-circuitpython-display-text +adafruit-circuitpython-display-shapes diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..2cc8fc7 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,107 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +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 + "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 + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions + "PLR6301", # could-be-static no-self-use + "PLC0415", # import outside toplevel + "PLC2701", # private import +] + +[format] +line-ending = "lf" diff --git a/setup.py b/setup.py deleted file mode 100644 index 0fab7fc..0000000 --- a/setup.py +++ /dev/null @@ -1,63 +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-display_button', - - use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='UI Buttons for displayio', - long_description=long_description, - long_description_content_type='text/x-rst', - - # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_Display_Button', - - # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=[ - 'Adafruit-Blinka' - ], - - # 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 display_button buttons UI', - - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, - # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=['adafruit_display_button'], -)