From 55778c0d776adb410f61b303d47730d0ce665843 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 25 Apr 2025 12:15:56 -0500 Subject: [PATCH 1/2] new infrastructure files --- .../adafruit_circuitpython_pr.md | 13 + .github/workflows/build.yml | 73 +-- .github/workflows/release_gh.yml | 23 + .github/workflows/release_pypi.yml | 19 + .gitignore | 50 +- .pre-commit-config.yaml | 47 +- .pylintrc | 436 ------------------ .readthedocs.yaml | 22 + .readthedocs.yml | 7 - CODE_OF_CONDUCT.md | 94 ++-- README.rst | 50 +- README.rst.license | 2 +- displayio_cartesian.py | 268 +++-------- docs/api.rst | 5 +- docs/conf.py | 45 +- docs/examples.rst.license | 2 +- docs/index.rst | 5 +- docs/index.rst.license | 2 +- docs/requirements.txt | 7 + examples/displayio_cartesian_advanced_test.py | 1 + examples/displayio_cartesian_lineplot.py | 2 + examples/displayio_cartesian_simpletest.py | 50 +- examples/displayio_cartesion_fillarea.py | 4 +- optional_requirements.txt | 3 + pyproject.toml | 56 ++- requirements.txt | 2 +- ruff.toml | 102 ++++ setup.py | 64 --- 28 files changed, 504 insertions(+), 950 deletions(-) create mode 100644 .github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md create mode 100644 .github/workflows/release_gh.yml create mode 100644 .github/workflows/release_pypi.yml delete mode 100644 .pylintrc create mode 100644 .readthedocs.yaml delete mode 100644 .readthedocs.yml create mode 100644 docs/requirements.txt create mode 100644 optional_requirements.txt create mode 100644 ruff.toml delete mode 100644 setup.py diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md new file mode 100644 index 0000000..8de294e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +Thank you for contributing! Before you submit a pull request, please read the following. + +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html + +If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f7e7510..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,74 +10,5 @@ jobs: test: runs-on: ubuntu-latest steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install pylint, Sphinx, pre-commit - run: | - pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit - - name: Load graphviz - run: | - sudo apt install graphviz - - name: Library version - run: git describe --dirty --always --tags - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Check For docs folder - id: need-docs - run: | - echo ::set-output name=docs::$( find . -wholename './docs' ) - - name: Build docs - if: contains(steps.need-docs.outputs.docs, 'docs') - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..576410b --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +1,23 @@ +# 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 }} + # TODO: If you're creating a package (library is a folder), add this + # argument along with the prefix (or full name) of the package folder + # so the MPY bundles are built correctly:s + # package-prefix: displayio_cartesian 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 2c6ddfd..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,48 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT +# Do not include files and directories created by your personal work environment, such as the IDE +# you use, except for those already listed here. Pull requests including changes to this file will +# not be accepted. + +# This .gitignore file contains rules for files generated by working with CircuitPython libraries, +# including building Sphinx, testing with pip, and creating a virual environment, as well as the +# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. + +# If you find that there are files being generated on your machine that should not be included in +# your git commit, you should create a .gitignore_global file on your computer to include the +# files created by your personal setup. To do so, follow the two steps below. + +# First, create a file called .gitignore_global somewhere convenient for you, and add rules for +# the files you want to exclude from git commits. + +# Second, configure Git to use the exclude file for all Git repositories by running the +# following via commandline, replacing "path/to/your/" with the actual path to your newly created +# .gitignore_global file: +# git config --global core.excludesfile path/to/your/.gitignore_global + +# CircuitPython-specific files *.mpy -.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 -.python-version -build*/ -bundles +.venv + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea .vscode +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7e02117..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,40 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: -- repo: https://github.com/python/black - rev: 20.8b1 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace -- repo: https://github.com/pycqa/pylint - rev: pylint-2.7.1 - hooks: - - id: pylint - name: pylint (library code) - types: [python] - exclude: "^(docs/|examples/|tests/|setup.py$)" -- repo: local - hooks: - - id: pylint_examples - name: pylint (examples code) - description: Run pylint rules on "examples/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name $example; done)'] - language: system - - id: pylint_tests - name: pylint (tests code) - description: Run pylint rules on "tests/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "tests" ]] || for test in $(find . -path "./tests/*.py"); do pylint --disable=missing-docstring $test; done)'] - language: system + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 79bcfb7..0000000 --- a/.pylintrc +++ /dev/null @@ -1,436 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,pointless-string-statement - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[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..ee38fa0 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams 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 a1e2575..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: requirements.txt diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index d885b36..ddf57b0 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,10 +1,10 @@ -# Adafruit Community Code of Conduct +# CircuitPython Community Code of Conduct ## Our Pledge @@ -20,33 +20,52 @@ race, religion, or sexual identity and orientation. We are committed to providing a friendly, safe and welcoming environment for all. -Examples of behavior that contributes to creating a positive environment +Examples of behavior that contributes to creating and maintaining a positive environment include: * Be kind and courteous to others * Using welcoming and inclusive language +* Respecting the identity of every community member, including asking for their + pronouns if uncertain * Being respectful of differing viewpoints and experiences * Collaborating with other community members +* Providing desired assistance and knowledge to other community members +* Being open to new information and ideas * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members -Examples of unacceptable behavior by participants include: +Examples of unacceptable behavior by community members include: * The use of sexualized language or imagery and sexual attention or advances * The use of inappropriate images, including in a community member's avatar -* The use of inappropriate language, including in a community member's nickname +* The use of inappropriate language or profanity, including in a community member's nickname * Any spamming, flaming, baiting or other attention-stealing behavior * Excessive or unwelcome helping; answering outside the scope of the question asked -* Trolling, insulting/derogatory comments, and personal or political attacks +* Discussion or promotion of activities or projects that intend or pose a risk of + significant harm +* Trolling, insulting/derogatory comments, and attacks of any nature (including, + but not limited to, 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 +* Engaging in behavior that creates an unwelcoming or uninclusive environment * Other conduct which could reasonably be considered inappropriate +The CircuitPython Community welcomes everyone and strives to create a safe space for all. It is built +around sharing and contributing to technology. We encourage discussing your thoughts, experiences, +and feelings within the scope of the community. However, there are topics that can sometimes stray +from that scope, and can lead to hurting others and create an unwelcoming, uninclusive environment. + +Examples of discussion topics that have been known to stray outside the scope of the CircuitPython +Community include, but are not limited to: + +* Discussions regarding religion and related topics +* Discussions regarding politics and related topics + 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. @@ -70,51 +89,51 @@ inappropriate, threatening, offensive, or harmful. ## Moderation -Instances of behaviors that violate the Adafruit Community Code of Conduct +Instances of behaviors that violate the CircuitPython Community Code of Conduct may be reported by any member of the community. Community members are encouraged to report these situations, including situations they witness involving other community members. You may report in the following ways: -In any situation, you may send an email to . +In any situation, you may email the project maintainer. -On the Adafruit Discord, you may send an open message from any channel -to all Community Moderators by tagging @community moderators. You may -also send an open message from any channel, or a direct message to -@kattni#1507, @tannewt#4653, @danh#1614, @cater#2442, -@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. +The source of email and direct message reports will be kept confidential. -Email and direct message reports will be kept confidential. - -In situations on Discord where the issue is particularly egregious, possibly -illegal, requires immediate action, or violates the Discord terms of service, -you should also report the message directly to Discord. +In situations on GitHub where the issue is particularly offensive, possibly +illegal, requires immediate action, or violates the GitHub terms of service, +you should also report the message directly to GitHub via the comment, or via +[GitHub Support](https://support.github.com/contact/report-abuse?category=report-abuse&report=other&report_type=unspecified). These are the steps for upholding our community’s standards of conduct. 1. Any member of the community may report any situation that violates the -Adafruit Community Code of Conduct. All reports will be reviewed and -investigated. -2. If the behavior is an egregious violation, the community member who -committed the violation may be banned immediately, without warning. + CircuitPython Community Code of Conduct. All reports will be reviewed and + investigated. +2. If the behavior is a severe violation, the community member who + committed the violation may be banned immediately, without warning. 3. Otherwise, moderators will first respond to such behavior with a warning. 4. Moderators follow a soft "three strikes" policy - the community member may -be given another chance, if they are receptive to the warning and change their -behavior. + be given another chance, if they are receptive to the warning and change their + behavior. 5. If the community member is unreceptive or unreasonable when warned by a -moderator, or the warning goes unheeded, they may be banned for a first or -second offense. Repeated offenses will result in the community member being -banned. + moderator, or the warning goes unheeded, they may be banned for a first or + second offense. Repeated offenses will result in the community member being + banned. +6. Disciplinary actions (warnings, bans, etc) for Code of Conduct violations apply + to the platform where the violation occurred. However, depending on the severity + of the violation, the disciplinary action may be applied across CircuitPython's + other community platforms. For example, a severe violation in one Community forum + may result in a ban on not only the CircuitPython GitHub organisation, + but also on the CircuitPython Twitter, live stream text chats, etc. ## Scope This Code of Conduct and the enforcement policies listed above apply to all -Adafruit Community venues. This includes but is not limited to any community -spaces (both public and private), the entire Adafruit Discord server, and -Adafruit GitHub repositories. Examples of Adafruit Community spaces include -but are not limited to meet-ups, audio chats on the Adafruit Discord, or -interaction at a conference. +CircuitPython Community venues. This includes but is not limited to any community +spaces (both public and private), and CircuitPython GitHub repositories. Examples of +CircuitPython Community spaces include but are not limited to meet-ups, issue +threads on GitHub, text chats during a live stream, or interaction at a conference. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. As a community @@ -123,15 +142,14 @@ accordingly. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant], -version 1.4, available at -, +This Code of Conduct is adapted from the +[Adafruit Community Code of Conduct](https://github.com/adafruit/Adafruit_Community_Code_of_Conduct), +which is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), +version 1.4, available on [contributor-covenant.org](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html), and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). -For other projects adopting the Adafruit Community Code of +For other projects adopting the CircuitPython Community Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion. - -[Contributor Covenant]: https://www.contributor-covenant.org diff --git a/README.rst b/README.rst index d50299b..887deb2 100644 --- a/README.rst +++ b/README.rst @@ -2,8 +2,8 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/circuitpython-displayio_cartesian/badge/?version=latest - :target: https://circuitpython-displayio_cartesian.readthedocs.io/ +.. image:: https://readthedocs.org/projects/circuitpython-displayio-cartesian/badge/?version=latest + :target: https://circuitpython-displayio-cartesian.readthedocs.io/ :alt: Documentation Status @@ -17,11 +17,11 @@ Introduction :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. 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 -A cartesian plane widget for displaying graphical information. +A Cartesian plane widget for displaying graphical information. Dependencies @@ -40,7 +40,7 @@ Installing from PyPI ===================== On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from -PyPI `_. +PyPI `_. To install for current user: .. code-block:: shell @@ -58,26 +58,48 @@ To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env + python3 -m venv .venv source .env/bin/activate pip3 install circuitpython-displayio-cartesian +Installing to a Connected CircuitPython Device with Circup +========================================================== +Make sure that you have ``circup`` installed in your Python environment. +Install it with the following command if necessary: + +.. code-block:: shell + + pip3 install circup + +With ``circup`` installed and your CircuitPython device connected use the +following command to install: + +.. code-block:: shell + + circup install displayio_cartesian + +Or the following command to update an existing version: + +.. code-block:: shell + + circup update Usage Example ============= See scripts in the examples directory of this repository. +Documentation +============= +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out +`this guide `_. + Contributing ============ Contributions are welcome! Please read our `Code of Conduct `_ before contributing to help this project stay welcoming. - -Documentation -============= - -For information on building library documentation, please check out -`this guide `_. diff --git a/README.rst.license b/README.rst.license index 9b0f4cd..be02923 100644 --- a/README.rst.license +++ b/README.rst.license @@ -1,3 +1,3 @@ SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython +SPDX-FileCopyrightText: Copyright (c) 2025 Jose David M. for circuitpython SPDX-License-Identifier: MIT diff --git a/displayio_cartesian.py b/displayio_cartesian.py index 763ced9..ea23381 100644 --- a/displayio_cartesian.py +++ b/displayio_cartesian.py @@ -21,15 +21,12 @@ """ -# pylint: disable=too-many-lines, too-many-instance-attributes, too-many-arguments -# pylint: disable=too-many-locals, too-many-statements - import displayio import terminalio -from adafruit_display_text import bitmap_label import vectorio +from adafruit_display_text import bitmap_label + from adafruit_displayio_layout.widgets.widget import Widget -from adafruit_displayio_layout.widgets import rectangle_helper try: import bitmaptools @@ -37,7 +34,7 @@ pass try: - from typing import Tuple + from typing import Any, List, Optional, Tuple except ImportError: pass @@ -95,7 +92,7 @@ class Cartesian(Widget): .. code-block:: python - display.show(my_plane) # add the group to the display + display.root_group = my_plane # add the group to the display If you want to have multiple display elements, you can create a group and then append the plane and the other elements to the group. Then, you can add the full @@ -111,7 +108,7 @@ class Cartesian(Widget): # Append other display elements to the group # - display.show(my_group) # add the group to the display + display.root_group = my_group # add the group to the display **Summary: Cartesian Features and input variables** @@ -134,7 +131,7 @@ class Cartesian(Widget): - **range**: ``xrange`` and ``yrange`` This is the range in absolute units. For example, when using (20-90), the X axis will start at 20 finishing at 90. - However the height of the graph is given by the height parameter. The scale + However, the height of the graph is given by the height parameter. The scale is handled internal to provide a 1:1 experience when you update the graph. @@ -175,7 +172,7 @@ def __init__( tick_color: int = 0xFFFFFF, major_tick_stroke: int = 1, major_tick_length: int = 5, - tick_label_font=terminalio.FONT, + tick_label_font: terminalio.FONT = terminalio.FONT, font_color: int = 0xFFFFFF, pointer_radius: int = 1, pointer_color: int = 0xFFFFFF, @@ -183,10 +180,8 @@ def __init__( nudge_x: int = 0, nudge_y: int = 0, verbose: bool = False, - fill_area: bool = False, - **kwargs, + **kwargs: Any, ) -> None: - super().__init__(**kwargs) self._verbose = verbose @@ -228,28 +223,20 @@ def __init__( self._valuey = self.height / 100 self._factory = 100 / (self._yrange[1] - self._yrange[0]) - self._tick_bitmap = displayio.Bitmap( - self._tick_line_thickness, self._tick_line_height, 3 - ) + self._tick_bitmap = displayio.Bitmap(self._tick_line_thickness, self._tick_line_height, 3) self._tick_bitmap.fill(1) self._subticks = subticks axesx_height = ( - 2 - + self._axes_line_thickness - + self._font_height - + self._tick_line_height // 2 + 2 + self._axes_line_thickness + self._font_height + self._tick_line_height // 2 ) self._axesx_bitmap = displayio.Bitmap(self.width, axesx_height, 4) self._axesx_bitmap.fill(0) self._axesy_width = ( - 2 - + self._axes_line_thickness - + self._font_width - + self._tick_line_height // 2 + 2 + self._axes_line_thickness + self._font_width + self._tick_line_height // 2 ) self._axesy_bitmap = displayio.Bitmap(self._axesy_width, self.height, 4) @@ -266,14 +253,14 @@ def __init__( self._screen_palette[5] = self._background_color self._corner_bitmap = displayio.Bitmap(10, 10, 5) - rectangle_helper( + + bitmaptools.fill_region( + self._corner_bitmap, 0, 0, self._axes_line_thickness, self._axes_line_thickness, - self._corner_bitmap, 2, - self._screen_palette, ) self._corner_tilegrid = displayio.TileGrid( @@ -315,14 +302,12 @@ def __init__( self.append(self._screen_tilegrid) self.append(self._corner_tilegrid) - self._pointer = None - self._circle_palette = None - self.plot_line_point = None - - self._fill_area = fill_area + self._pointer: Optional[vectorio.Circle] = None + self._circle_palette: Optional[displayio.Palette] = None + self.plot_line_point: List[Tuple[int, int]] = [] @staticmethod - def _get_font_height(font, scale: int) -> Tuple[int, int]: + def _get_font_height(font: terminalio.FONT, scale: int) -> Tuple[int, int]: if hasattr(font, "get_bounding_box"): font_height = int(scale * font.get_bounding_box()[1]) font_width = int(scale * font.get_bounding_box()[0]) @@ -335,28 +320,22 @@ def _get_font_height(font, scale: int) -> Tuple[int, int]: return font_width, font_height def _draw_axes(self) -> None: - # Draw x axes line - rectangle_helper( + bitmaptools.fill_region( + self._axesx_bitmap, 0, 0, - self._axes_line_thickness, self.width, - self._axesx_bitmap, + self._axes_line_thickness, 2, - self._screen_palette, - True, ) - # Draw y axes line - rectangle_helper( + bitmaptools.fill_region( + self._axesy_bitmap, self._axesy_width - self._axes_line_thickness, 0, + self._axesy_width, self.height, - self._axes_line_thickness, - self._axesy_bitmap, 2, - self._screen_palette, - True, ) def _draw_ticks(self) -> None: @@ -381,30 +360,28 @@ def _draw_ticks(self) -> None: + 1, ) self.append(tick_text) - rectangle_helper( + + bitmaptools.fill_region( + self._axesx_bitmap, text_dist, self._axes_line_thickness, - self._tick_line_height, - self._tick_line_thickness, - self._axesx_bitmap, + text_dist + self._tick_line_thickness, + self._axes_line_thickness + self._tick_line_height, 1, - self._screen_palette, - True, ) if self._subticks: if i in subticks: # calc subtick_line_height; force min lineheigt to 1. subtick_line_height = max(1, self._tick_line_height // 2) - rectangle_helper( + + bitmaptools.fill_region( + self._axesx_bitmap, text_dist, self._axes_line_thickness, - subtick_line_height, - 1, - self._axesx_bitmap, + text_dist + 1, + self._axes_line_thickness + subtick_line_height, 1, - self._screen_palette, - True, ) # Y axes ticks @@ -417,46 +394,37 @@ def _draw_ticks(self) -> None: self._font, color=self._font_color, text=text_tick, - x=-shift_label_x - - self._axes_line_thickness - - self._tick_line_height - - 2, + x=-shift_label_x - self._axes_line_thickness - self._tick_line_height - 2, y=0 + self.height - text_dist, ) self.append(tick_text) - rectangle_helper( - self._axesy_width - - self._axes_line_thickness - - self._tick_line_height - - 1, - text_dist, - self._tick_line_thickness, - self._tick_line_height, + + bitmaptools.fill_region( self._axesy_bitmap, + self._axesy_width - self._axes_line_thickness - self._tick_line_height - 1, + text_dist, + self._axesy_width - self._axes_line_thickness - 1, + text_dist + self._tick_line_thickness, 1, - self._screen_palette, - True, ) if self._subticks: if i in subticks: - rectangle_helper( + bitmaptools.fill_region( + self._axesy_bitmap, self._axesy_width - self._axes_line_thickness - self._tick_line_height // 2 - 1, text_dist, + self._axesy_width - self._axes_line_thickness - 1, + text_dist + 1, 1, - self._tick_line_height // 2, - self._axesy_bitmap, - 1, - self._screen_palette, - True, ) def _draw_pointers(self, x: int, y: int) -> None: - self._circle_palette = displayio.Palette(1) + self._circle_palette[0] = self._pointer_color self._pointer = vectorio.Circle( radius=self._pointer_radius, x=x, y=y, pixel_shader=self._circle_palette @@ -465,9 +433,7 @@ def _draw_pointers(self, x: int, y: int) -> None: self.append(self._pointer) def _calc_local_xy(self, x: int, y: int) -> Tuple[int, int]: - local_x = ( - int((x - self._xrange[0]) * self._factorx * self._valuex) + self._nudge_x - ) + local_x = int((x - self._xrange[0]) * self._factorx * self._valuex) + self._nudge_x # details on `+ (self.height - 1)` : # the bitmap is set to self.width & self.height # but we are only allowed to draw to pixels 0..height-1 and 0..width-1 @@ -478,24 +444,22 @@ def _calc_local_xy(self, x: int, y: int) -> Tuple[int, int]: ) return (local_x, local_y) - def _check_local_x_in_range(self, local_x): + def _check_local_x_in_range(self, local_x: int) -> bool: return 0 <= local_x < self.width - def _check_local_y_in_range(self, local_y): + def _check_local_y_in_range(self, local_y: int) -> bool: return 0 <= local_y < self.height - def _check_local_xy_in_range(self, local_x, local_y): - return self._check_local_x_in_range(local_x) and self._check_local_y_in_range( - local_y - ) + def _check_local_xy_in_range(self, local_x: int, local_y: int) -> bool: + return self._check_local_x_in_range(local_x) and self._check_local_y_in_range(local_y) - def _check_x_in_range(self, x): + def _check_x_in_range(self, x: int) -> bool: return self._xrange[0] <= x <= self._xrange[1] - def _check_y_in_range(self, y): + def _check_y_in_range(self, y: int) -> bool: return self._yrange[0] <= y <= self._yrange[1] - def _check_xy_in_range(self, x, y): + def _check_xy_in_range(self, x: int, y: int) -> bool: return self._check_x_in_range(x) and self._check_y_in_range(y) def _add_point(self, x: int, y: int) -> None: @@ -504,36 +468,21 @@ def _add_point(self, x: int, y: int) -> None: :param int x: ``x`` coordinate in the local plane :param int y: ``y`` coordinate in the local plane :return: None + rtype: None """ - local_x, local_y = self._calc_local_xy(x, y) if self._verbose: print("") print( - "xy: ({: >4}, {: >4}) " - "_xrange: ({: >4}, {: >4}) " - "_yrange: ({: >4}, {: >4}) " - "".format( - x, - y, - self._xrange[0], - self._xrange[1], - self._yrange[0], - self._yrange[1], - ) + f"xy: ({x: >4}, {y: >4}) " + + f"_xrange: ({self._xrange[0]: >4}, {self._xrange[1]: >4}) " + + f"_yrange: ({self._yrange[0]: >4}, {self._yrange[1]: >4}) " + "" ) print( - "local_*: ({: >4}, {: >4}) " - " width: ({: >4}, {: >4}) " - " height: ({: >4}, {: >4}) " - "".format( - local_x, - local_y, - 0, - self.width, - 0, - self.height, - ) + f"local_*: ({local_x: >4}, {local_y: >4}) " + + f" width: ({0: >4}, {self.width: >4}) " + + f" height: ({0: >4}, {self.height: >4}) " ) if self._check_xy_in_range(x, y): if self._check_local_xy_in_range(local_x, local_y): @@ -548,45 +497,28 @@ def _add_point(self, x: int, y: int) -> None: if not self._check_local_x_in_range(local_x): raise ValueError( "local_x out of range: " - "local_x:{: >4}; _xrange({: >4}, {: >4})" - "".format( - local_x, - 0, - self.width, - ) + f"local_x:{local_x: >4}; _xrange({0: >4}, {self.width: >4})" + "" ) if not self._check_local_y_in_range(local_y): raise ValueError( "local_y out of range: " - "local_y:{: >4}; _yrange({: >4}, {: >4})" - "".format( - local_y, - 0, - self.height, - ) + f"local_y:{local_y: >4}; _yrange({0: >4}, {self.height: >4})" + "" ) - else: # for better error messages we check in detail what failed... if not self._check_x_in_range(x): raise ValueError( "x out of range: " - "x:{: >4}; xrange({: >4}, {: >4})" - "".format( - x, - self._xrange[0], - self._xrange[1], - ) + f"x:{x: >4}; xrange({self._xrange[0]: >4}, {self._xrange[1]: >4})" + "" ) if not self._check_y_in_range(y): raise ValueError( "y out of range: " - "y:{: >4}; yrange({: >4}, {: >4})" - "".format( - y, - self._yrange[0], - self._yrange[1], - ) + f"y:{y: >4}; yrange({self._yrange[0]: >4}, {self._yrange[1]: >4})" + "" ) def update_pointer(self, x: int, y: int) -> None: @@ -595,7 +527,9 @@ def update_pointer(self, x: int, y: int) -> None: :param int x: ``x`` coordinate in the local plane :param int y: ``y`` coordinate in the local plane :return: None + rtype: None """ + self._add_point(x, y) if not self._pointer: self._draw_pointers( @@ -606,15 +540,6 @@ def update_pointer(self, x: int, y: int) -> None: self._pointer.x = self.plot_line_point[-1][0] self._pointer.y = self.plot_line_point[-1][1] - @property - def fill_area(self) -> bool: - """Whether the area under the graph (integral) should be shaded""" - return self._fill_area - - @fill_area.setter - def fill_area(self, setting: bool) -> None: - self._fill_area = setting - def add_plot_line(self, x: int, y: int) -> None: """add_plot_line function. @@ -624,7 +549,10 @@ def add_plot_line(self, x: int, y: int) -> None: :param int x: ``x`` coordinate in the local plane :param int y: ``y`` coordinate in the local plane :return: None + + rtype: None """ + self._add_point(x, y) if len(self.plot_line_point) > 1: bitmaptools.draw_line( @@ -635,50 +563,6 @@ def add_plot_line(self, x: int, y: int) -> None: self.plot_line_point[-1][1], 1, ) - # Plot area under graph - if self._fill_area: - - delta_x = self.plot_line_point[-2][0] - self.plot_line_point[-1][0] - delta_y = self.plot_line_point[-2][1] - self.plot_line_point[-1][1] - delta_y_product = ( - self.plot_line_point[-1][1] * self.plot_line_point[-2][1] - ) - - if delta_x == 0: - return - - slope = delta_y / delta_x - - if delta_y_product < 0: - - intercept = self.plot_line_point[-1][1] - zero_point_x = (-1 * intercept) / slope - - self._draw_area_under(self.plot_line_point[-2], (zero_point_x, 0)) - self._draw_area_under((zero_point_x, 0), self.plot_line_point[-1]) - - else: - - self._draw_area_under( - self.plot_line_point[-2], self.plot_line_point[-1] - ) - - def _draw_area_under( - self, xy0: Tuple[float, float], xy1: Tuple[float, float] - ) -> None: - - _, plot_y_zero = self._calc_local_xy(0, 0) - - delta_x = self.plot_line_point[-2][0] - self.plot_line_point[-1][0] - delta_y = self.plot_line_point[-2][1] - self.plot_line_point[-1][1] - slope = delta_y / delta_x - - for pixel_x in range(xy0[0], xy1[0] + 1): - if pixel_x != xy1[0]: - pixel_y = round(slope * (pixel_x - xy1[0]) + xy1[1]) - bitmaptools.draw_line( - self._plot_bitmap, pixel_x, pixel_y, pixel_x, plot_y_zero, 1 - ) def clear_plot_lines(self, palette_index: int = 5) -> None: """clear_plot_lines function. @@ -689,5 +573,5 @@ def clear_plot_lines(self, palette_index: int = 5) -> None: :param int palette_index: color palett index. Defaults to 5 :return: None """ - self.plot_line_point = None + self.plot_line_point = [] self._plot_bitmap.fill(palette_index) diff --git a/docs/api.rst b/docs/api.rst index 214f853..0112141 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,9 +4,10 @@ .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" +API Reference +############# + .. automodule:: displayio_cartesian :members: :member-order: bysource :inherited-members: - -.. inheritance-diagram:: displayio_cartesian diff --git a/docs/conf.py b/docs/conf.py index 6d428fb..e83900d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,9 +1,8 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys @@ -16,10 +15,10 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", - "sphinx.ext.inheritance_diagram", ] # Uncomment the below if you use native CircuitPython modules such as @@ -27,10 +26,11 @@ # autodoc module docs will fail to generate with a warning. autodoc_mock_imports = ["vectorio", "bitmaptools"] +autodoc_preserve_defaults = True intersphinx_mapping = { - "python": ("https://docs.python.org/3.4", None), - "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), + "python": ("https://docs.python.org/3", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), } # Show the docstring from both the class and its __init__() method. @@ -45,8 +45,13 @@ master_doc = "index" # General information about the project. -project = " CircuitPython DisplayIO_Cartesian Library" -copyright = "2021 Jose David M." +project = "CircuitPython DisplayIO_Cartesian Library" +creation_year = "2025" +current_year = str(datetime.datetime.now().year) +year_duration = ( + current_year if current_year == creation_year else creation_year + " - " + current_year +) +copyright = year_duration + " Jose David M." author = "Jose David M." # The version info for the project you're documenting, acts as replacement for @@ -63,7 +68,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -101,19 +106,9 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -if not on_rtd: # only import and set the theme if we're building docs locally - try: - import sphinx_rtd_theme +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 = ["."] +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, @@ -127,7 +122,7 @@ html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = "CircuitPython_Displayio_cartesianLibrarydoc" +htmlhelp_basename = "CircuitPython_Displayio_cartesian_Librarydoc" # -- Options for LaTeX output --------------------------------------------- @@ -148,7 +143,7 @@ latex_documents = [ ( master_doc, - "CircuitPython_DisplayIO_CartesianLibrary.tex", + "CircuitPython_DisplayIO_Cartesian_Library.tex", "CircuitPython DisplayIO_Cartesian Library Documentation", author, "manual", @@ -162,7 +157,7 @@ man_pages = [ ( master_doc, - "CircuitPython_DisplayIO_CartesianLibrary", + "CircuitPython_DisplayIO_Cartesian_Library", "CircuitPython DisplayIO_Cartesian Library Documentation", [author], 1, @@ -177,10 +172,10 @@ texinfo_documents = [ ( master_doc, - "CircuitPython_DisplayIO_CartesianLibrary", + "CircuitPython_DisplayIO_Cartesian_Library", "CircuitPython DisplayIO_Cartesian Library Documentation", author, - "CircuitPython_DisplayIO_CartesianLibrary", + "CircuitPython_DisplayIO_Cartesian_Library", "One line description of project.", "Miscellaneous", ), diff --git a/docs/examples.rst.license b/docs/examples.rst.license index 74dc2f6..56bc02d 100644 --- a/docs/examples.rst.license +++ b/docs/examples.rst.license @@ -1,4 +1,4 @@ SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython +SPDX-FileCopyrightText: Copyright (c) 2025 Jose David M. for circuitpython SPDX-License-Identifier: MIT diff --git a/docs/index.rst b/docs/index.rst index 6c9da34..f5400ce 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -30,8 +30,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 index 74dc2f6..56bc02d 100644 --- a/docs/index.rst.license +++ b/docs/index.rst.license @@ -1,4 +1,4 @@ SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython +SPDX-FileCopyrightText: Copyright (c) 2025 Jose David M. for circuitpython 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/displayio_cartesian_advanced_test.py b/examples/displayio_cartesian_advanced_test.py index da89b58..40cc5ea 100644 --- a/examples/displayio_cartesian_advanced_test.py +++ b/examples/displayio_cartesian_advanced_test.py @@ -10,6 +10,7 @@ import board import displayio import terminalio + from displayio_cartesian import Cartesian # Fonts used for the Dial tick labels diff --git a/examples/displayio_cartesian_lineplot.py b/examples/displayio_cartesian_lineplot.py index 52b95bd..35d26c0 100644 --- a/examples/displayio_cartesian_lineplot.py +++ b/examples/displayio_cartesian_lineplot.py @@ -7,8 +7,10 @@ """ import time + import board import displayio + from displayio_cartesian import Cartesian # create the display on the PyPortal or Clue or PyBadge(for example) diff --git a/examples/displayio_cartesian_simpletest.py b/examples/displayio_cartesian_simpletest.py index 4e815fa..57ad79d 100644 --- a/examples/displayio_cartesian_simpletest.py +++ b/examples/displayio_cartesian_simpletest.py @@ -1,48 +1,4 @@ -# SPDX-FileCopyrightText: 2021 Jose David M. +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# SPDX-FileCopyrightText: Copyright (c) 2025 Jose David M. for circuitpython # -# SPDX-License-Identifier: MIT -############################# -""" -This is a basic demonstration of a Cartesian widget. -""" - -import time -import board -import displayio -import terminalio -from displayio_cartesian import Cartesian - -# Fonts used for the Dial tick labels -tick_font = terminalio.FONT - -display = board.DISPLAY # create the display on the PyPortal or Clue (for example) -# otherwise change this to setup the display -# for display chip driver and pinout you have (e.g. ILI9341) - - -# Create a Cartesian widget -my_plane = Cartesian( - x=150, # x position for the plane - y=100, # y plane position - width=100, # display width - height=100, # display height - axes_color=0xFFFFFF, # axes line color - axes_stroke=2, # axes lines width in pixels - tick_color=0xFFFFFF, # ticks color - major_tick_stroke=1, # ticks width in pixels - major_tick_length=5, # ticks length in pixels - tick_label_font=tick_font, # the font used for the tick labels - font_color=0xFFFFFF, # ticks line color -) - -my_group = displayio.Group() -my_group.append(my_plane) -display.show(my_group) # add high level Group to the display - -posx = 0 -posy = 0 - -while True: - for i in range(0, 90, 2): - my_plane.update_pointer(i, i) - time.sleep(0.5) +# SPDX-License-Identifier: Unlicense diff --git a/examples/displayio_cartesion_fillarea.py b/examples/displayio_cartesion_fillarea.py index 81eedf3..7ae41aa 100644 --- a/examples/displayio_cartesion_fillarea.py +++ b/examples/displayio_cartesion_fillarea.py @@ -6,10 +6,12 @@ This is a basic demonstration of a Cartesian widget for line-ploting """ +import random import time + import board import displayio -import random + from displayio_cartesian import Cartesian # create the display on the PyPortal or Clue or PyBadge(for example) diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..d4e27c4 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml index f3c35ae..cd450a4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,54 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2022 Alec Delaney, written for Adafruit Industries +# SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT -[tool.black] -target-version = ['py35'] +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "circuitpython-displayio-cartesian" +description = "A Cartesian plane widget for displaying graphical information." +version = "0.0.0+auto.0" +readme = "README.rst" +authors = [ + {name = "Jose David M."} +] +urls = {Homepage = "https://github.com/circuitpython/CircuitPython_DisplayIO_Cartesian"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "displayio_cartesian", + "displayio", + "widget", + "graphics", + "gui", + "graph", + "chart", + "graphic", +] +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] +# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, +# CHANGE `py_modules = ['...']` TO `packages = ['...']` +py-modules = ["displayio_cartesian"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index ec56ca7..092c985 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython +# SPDX-FileCopyrightText: Copyright (c) 2025 Jose David M. for circuitpython # # SPDX-License-Identifier: MIT diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..81b274c --- /dev/null +++ b/ruff.toml @@ -0,0 +1,102 @@ +# 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 + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too many arguments + "PLR0917", # too many positional arguments + "PLR0915", # too many statements +] + +[format] +line-ending = "lf" diff --git a/setup.py b/setup.py deleted file mode 100644 index f70026b..0000000 --- a/setup.py +++ /dev/null @@ -1,64 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython -# -# SPDX-License-Identifier: MIT - -"""A setuptools based setup module. - -See: -https://packaging.python.org/en/latest/distributing.html -https://github.com/pypa/sampleproject -""" - -from setuptools import setup, find_packages - -# To use a consistent encoding -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, "README.rst"), encoding="utf-8") as f: - long_description = f.read() - -setup( - # Community Bundle Information - name="circuitpython-displayio-cartesian", - use_scm_version=True, - setup_requires=["setuptools_scm"], - description="A cartesian plane widget for displaying graphical information.", - long_description=long_description, - long_description_content_type="text/x-rst", - # The project's main homepage. - url="https://github.com/circuitpython/CircuitPython_Org_DisplayIO_Cartesian.git", - # Author details - author="Jose David M.", - author_email="", - install_requires=[ - "Adafruit-Blinka", - "adafruit-circuitpython-display-text", - "adafruit-circuitpython-displayio-layout", - ], - # 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 displayio_cartesian displayio widget " - "graphics gui graph chart graphic", - # 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=["displayio_cartesian"], -) From ac80b86eb7d118973ad0071f87ff84741a7e6a69 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 25 Apr 2025 12:18:10 -0500 Subject: [PATCH 2/2] format --- displayio_cartesian.py | 1 - 1 file changed, 1 deletion(-) diff --git a/displayio_cartesian.py b/displayio_cartesian.py index ea23381..f611d70 100644 --- a/displayio_cartesian.py +++ b/displayio_cartesian.py @@ -25,7 +25,6 @@ import terminalio import vectorio from adafruit_display_text import bitmap_label - from adafruit_displayio_layout.widgets.widget import Widget try: