diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 47913f597..000000000 --- a/.gitattributes +++ /dev/null @@ -1,36 +0,0 @@ -*.py text diff=python -*.pyi text diff=python -*.c text diff=c -*.cpp text diff=cpp -*.hpp text diff=cpp -*.h text diff=c -*.m text diff=objc -*.mm text -*.bat text -*.md text -*.txt text -*.html text -*.sh text eol=lf -*.yml text -*.ttf binary -*.png binary -*.jpg binary -*.jpeg binary -*.gif binary -*.tif binary -*.tiff binary -*.ico binary - -.gitattributes export-ignore -.gitignore export-ignore - -# generated code -dearpygui/dearpygui.py linguist-generated -dearpygui/_dearpygui.pyi linguist-generated -dearpygui/_dearpygui_RTD.py linguist-generated - -# vendored code -thirdparty/* linguist-vendored - -# documentation -docs/* linguist-documentation \ No newline at end of file diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md deleted file mode 100644 index c1db814ef..000000000 --- a/.github/CHANGELOG.md +++ /dev/null @@ -1,27 +0,0 @@ -# 1.x.y CHANGELOG - -This document holds the user-facing changelog that we also use in release notes. -We generally fold multiple commits pertaining to the same topic as a single entry. - -* RELEASE NOTES: https://github.com/hoffstadt/DearPyGui/releases -* REPORT ISSUES, ASK QUESTIONS: https://github.com/hoffstadt/DearPyGui/issues -* COMMITS HISTORY: https://github.com/hoffstadt/DearPyGui/commits/master -* WIKI https://github.com/hoffstadt/DearPyGui/wiki - -### When to update? - -- Keeping your copy of Dear PyGui updated regularly is recommended. -- It is generally safe to sync to the latest commit in master - The library is fairly stable and regressions tends to be fixed fast when reported. - -### How to update? - -- pip or pip3 install dearpygui --upgrade -- Read the `Breaking Changes` section (here in the changelog). -- Please report any issue! - -## VERSION 1.0.1 - -### Fixes -* fixed `show_item_registry()` not rendering widgets -* fixed themes not binding to node attributes #1320 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index b23dae7d8..000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,23 +0,0 @@ - -# directories -/thirdparty/ @hoffstadt -/scripts/ @hoffstadt -/docs/* @hoffstadt - -# specific files -/src/distribution.cmake @hoffstadt -/src/embedded.cmake @hoffstadt -/src/CMakeLists.txt @hoffstadt -/src/.gitignore @hoffstadt -CMakeLists.txt @hoffstadt -CMakeSettings.json @hoffstadt -setup.py @hoffstadt -.gitattributes @hoffstadt -.gitignore @hoffstadt -.gitmodules @hoffstadt -.readthedocs.yaml @hoffstadt - -# no owners -README.md -/docs/source/ -/assets diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..6ee9f6669 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,58 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +1. PLEASE CAREFULLY READ: [FAQ](https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq) + +2. PLEASE CAREFULLY READ: [Documentation](https://github.com/hoffstadt/DearPyGui/wiki) + +3. FOR FIRST-TIME USERS ISSUES, please use the [Discord server](https://discord.gg/tyE7Gu4). + +4. PLEASE MAKE SURE that you have: read the FAQ; explored the examples; searched among Issues; and read the link provided in (1) (2). + +5. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. + +6. Delete points 1-6 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue or we will immediately close it. + +Thank you! + +---- + +## Version of Dear PyGui + +Version: XXX +Operating System: XXX (Windows 10, macOs xx, Ubuntu 20.04, etc.) + +## My Issue/Question + +A clear and concise description of what the issue/question is. Please provide as much context as possible. + +## To Reproduce + +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +## Expected behavior + +A clear and concise description of what you expected to happen. + +## Screenshots/Video + +XXX _(you can drag files here)_ + +## Standalone, minimal, complete and verifiable example + +```python +# Here's some code anyone can copy and paste to reproduce your issue +add_button("Example Bug") +more_code_to_explain_my_issue() +start_dearpygui() +``` diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 8325e2e5e..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Bug Report -description: File a report for unexpected or broken behavior. -labels: ["state: pending", "type: bug"] -body: - - type: markdown - attributes: - value: | - **Before opening a bug report, please:** - - Search [existing issues](https://github.com/hoffstadt/DearPyGui/issues?q=is%3Aissue) (including closed ones) — your bug may already be known. - - Check the [FAQ](https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq), [Wiki](https://github.com/hoffstadt/DearPyGui/wiki), and [online documentation](https://dearpygui.readthedocs.io/en/latest/index.html). - - **!!! FOR FIRST-TIME USERS' ISSUES, please use the [Discord server](https://discord.gg/tyE7Gu4) !!!** - - Remove all third-party libraries. - - Confirm that the problem still exists with the **latest released version** of DearPyGui. - - Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. - - - type: input - id: dpg_version - attributes: - label: "Dear PyGui version:" - description: > - Run `python -c "import dearpygui; print(dearpygui.__version__)"` or `pip show dearpygui` to obtain it. - placeholder: "e.g. 2.2.1" - validations: - required: true - - - type: input - id: python_version - attributes: - label: "Python version:" - description: > - Run `python --version` to obtain it. - Note: DearPyGui requires Python 3.8+. - placeholder: "e.g. 3.11.4" - validations: - required: true - - - type: input - id: operating_system - attributes: - label: "Operating system:" - placeholder: "e.g. Windows 11 22H2 or Ubuntu 22.04 LTS" - validations: - required: true - - - type: textarea - id: description - attributes: - label: "My issue/question:" - description: "A clear and concise description of what the issue/question is. Please provide as much context as possible!" - validations: - required: true - - - type: textarea - id: steps - attributes: - label: "Steps to reproduce:" - value: | - 1. Go to '...' - 2. Click on '....' - 3. Scroll down to '....' - 4. See error - validations: - required: true - - - type: textarea - id: expected - attributes: - label: "Expected behavior:" - description: "What did you expect to happen?" - validations: - required: true - - - type: textarea - id: screenshots - attributes: - label: "Screenshots:" - description: | - If applicable, attach screenshots or a screen recording (GIF/video) to help illustrate the problem. You can drag and drop files directly into this field. Please remove "N/A" text if you insert any screenshots. - # This is to prevent GitHub from inserting "No response" section - N/A reads better. - # As soon as GitHub starts entirely omitting empty inputs from issue description, - # we can remove the "value" and just let the Screenshots section disappear if the user - # doesn't provide any. - value: "N/A" - validations: - required: false - - - type: textarea - id: mcve - attributes: - label: "Standalone, minimal, complete and verifiable example:" - description: | - **Please provide the shortest self-contained Python script that recreates the issue.** - Strip your code down to only what is necessary to trigger the bug.

- **Anyone** should be able to **copy and paste** this code and recreate your issue.
- Issues without a reproducible example may be closed. - render: python - placeholder: | - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport(title="Bug Demo") - dpg.setup_dearpygui() - - with dpg.window(label="Bug Demo"): - # minimal code that triggers the bug - pass - - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - validations: - required: true - - - type: markdown - attributes: - value: | - **Last-chance checklist:** - - I have read DearPyGui documentation, - - I have checked FAQ and wiki articles for solution, - - I have searched for similar issues and found none, - - I have proof-read the description and it fully describes the problem. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 57dc07550..000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: Quick question? Discord! - url: https://discord.gg/tyE7Gu4 - about: Dear PyGui community is more active on Discord than here. If you're asking a question rather than reporting a bug, head over to Discord for a quick answer. - - name: Dear PyGui is in maintenance mode! - url: https://github.com/hoffstadt/DearPyGui/wiki/What's-going-on%3F - about: Read this wiki article if you're unaware of the maintenance-only status of this project. diff --git a/.github/ISSUE_TEMPLATE/doc_change.yml b/.github/ISSUE_TEMPLATE/doc_change.yml deleted file mode 100644 index 189af0b98..000000000 --- a/.github/ISSUE_TEMPLATE/doc_change.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Documentation Improvement -description: Suggest a doc change. -labels: ["state: pending", "type: docs"] -body: - - type: textarea - id: description - attributes: - label: Description - description: "A clear and concise description of what the improvement is. Please provide as much context as possible." - validations: - required: true - - - type: textarea - id: assets - attributes: - label: Necessary assets - description: "Any assets to use in the documentation. You can drag and drop files directly into this field." - value: | - - [ ] Pictures - - [ ] Code Sample - - [ ] GIFs - - validations: - required: false diff --git a/.github/ISSUE_TEMPLATE/documentation.md b/.github/ISSUE_TEMPLATE/documentation.md new file mode 100644 index 000000000..59f100f98 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.md @@ -0,0 +1,42 @@ +--- +name: Documentation Improvement +about: Not Documented, Not Done... Help us be done! +title: '' +labels: '' +assignees: '' + +--- + +--- +We'd love help and you are welcome to improve the the documentation with the exception of the api reference because +it is currently generated manually from the stub file. It needs to be integrated within our CI process soon. +If you'd like to change the API reference, update the stub file and we will generate the api docs during releases: + +https://github.com/hoffstadt/DearPyGui/blob/master/DearPyGui/stubs/dearpygui.pyi + + +What can be modified related to docs: +* Wiki +* https://github.com/hoffstadt/DearPyGui/tree/gh-pages except (api_docs.html) +* Readme +* https://github.com/hoffstadt/DearPyGui/blob/master/DearPyGui/include/mvMarvel.h (this shows up in _show_documentation()_) +* https://github.com/hoffstadt/DearPyGui/blob/master/DearPyGui/src/Core/StandardWindows/mvDocWindow.cpp (this shows up in _show_documentation()_) +* https://github.com/hoffstadt/DearPyGui/tree/master/Examples (adding examples) + +Currently the CSS formatting is inherited from the autogenerated AIP docs done using pdoc3 to keep uniformity. + +Delete the above comment between the lines and PLEASE FILL THE TEMPLATE BELOW before submitting your issue. + +Thank you! + +---- + +**My Improvement** + +A clear and concise description of what the improvement is. Please provide as much context as possible. + +**Necessary Assets** + +- [ ] Pictures +- [x] Code Sample +- [ ] GIFs diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..bbcbbe7d6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index dc2419b26..000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Feature Request -description: Suggest a new feature or improvement. -labels: ["state: pending", "type: improvement"] -body: - - type: markdown - attributes: - value: | - **Before opening a feature request, please:** - - Search [existing issues](https://github.com/hoffstadt/DearPyGui/issues?q=is%3Aissue) and [discussions](https://github.com/hoffstadt/DearPyGui/discussions) (including closed ones) for similar requests. - - Be mindful of [The XY Problem](https://en.wikipedia.org/wiki/XY_problem): describe **what you are trying to accomplish**, not only the specific solution you have in mind. There may be a better or already-available approach. - - - type: textarea - id: description - attributes: - label: Description - description: "A clear and concise description of what the problem is." - placeholder: "e.g. I'm trying to build X. There is currently no way to do Y, which means I have to work around it by..." - validations: - required: true - - - type: textarea - id: solution - attributes: - label: Proposed solution - description: "A clear and concise description of what you want to happen." - validations: - required: true - - - type: textarea - id: alternatives - attributes: - label: Alternatives considered - description: "Describe any alternative approaches, workarounds, or existing solutions you have already tried or considered." - value: "N/A" - validations: - required: false - - - type: textarea - id: additional - attributes: - label: Additional context - description: "Any other context, screenshots, links to related issues, or references that might help." - value: "N/A" - validations: - required: false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 47899303d..64042b0b4 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,16 +1,16 @@ - - +--- +name: Pull Request +about: Create a pull request to help us improve +title: '' +assignees: '' + +--- + + + **Description:** **Concerning Areas:** - -**A checklist on final steps:** - -I confirm that I have: -- [ ] listed all necessary tickets with the "closes" keyword, -- [ ] added reviewers, -- [ ] proof-read the description in the Preview tab, -- [ ] removed this checklist from PR description :) (yes, this checklist is for *you*, not for us - use it as a reminder). diff --git a/.github/TODO.md b/.github/TODO.md deleted file mode 100644 index 8141cf3d2..000000000 --- a/.github/TODO.md +++ /dev/null @@ -1,13 +0,0 @@ -## ISSUES & TODO LIST - -Issue numbers (#) refer to github issues listed at https://github.com/hoffstadt/DearPyGui/issues -The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point they usually exist on the github issue tracker). -It's mostly a bunch of personal notes, probably incomplete. Feel free to query if you have any questions. - -* window class: alot of work needs to happen here to clean this up. -* doc: work on the CONTRIBUTING.md file -* doc/wiki: work on the wiki https://github.com/hoffstadt/DearPyGui/wiki -* custom widgets: add a fully supported custom widget API to allow users to make their own widgets more easily -* mvPythonTranslator: make commands more consistent, more like ToPyPairII -* add_texture: fix alpha channel mess -* mac: handle retina display nonsense diff --git a/.github/workflows/Deployment.yml b/.github/workflows/Deployment.yml deleted file mode 100644 index 379745715..000000000 --- a/.github/workflows/Deployment.yml +++ /dev/null @@ -1,245 +0,0 @@ -name: Deployment - -on: - - workflow_dispatch: - - branches: - - master - - development - - development_* - - inputs: - - version: - description: 'Dear PyGui Version' - required: false - default: '2.1.2' - - deploy: - description: 'Deploy (true will deploy to pypi)' - required: false - default: 'false' - - deploytest: - description: 'Deploy (true will deploy to test pypi)' - required: false - default: 'false' - -jobs: - - build-windows-wheels: - - runs-on: windows-2022 - strategy: - matrix: - python-version: [ 3.8, 3.9, "3.10", "3.11", "3.12", "3.13", "3.14" ] - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Retrieve submodules - shell: cmd - run: | - git submodule update --init --recursive ./thirdparty/imgui - git submodule update --init --recursive ./thirdparty/implot - git submodule update --init --recursive ./thirdparty/freetype - - - name: Mark Versions - shell: cmd - run: | - cd %GITHUB_WORKSPACE% - echo ${{ github.event.inputs.version }} > version_number.txt - - - name: Build Wheel - shell: cmd - run: | - cd %GITHUB_WORKSPACE% - python -m pip install --upgrade pip twine wheel setuptools - python -m setup bdist_wheel --plat-name win_amd64 --dist-dir dist - - - name: Upload Windows ${{ matrix.python-version }} Wheel - uses: actions/upload-artifact@v4 - with: - name: windowsbuild${{ matrix.python-version }} - path: ${{ github.workspace }}/dist/*.whl - overwrite: true - - build-mac-silicon-wheels: - - runs-on: macos-latest-xlarge - strategy: - matrix: - python-version: [ "3.10", "3.11", "3.12", "3.13", "3.14" ] - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Retrieve submodules - run: | - git submodule update --init --recursive ./thirdparty/imgui - git submodule update --init --recursive ./thirdparty/implot - git submodule update --init --recursive ./thirdparty/glfw - - - name: Mark Versions - run: | - cd $GITHUB_WORKSPACE - echo ${{ github.event.inputs.version }} > version_number.txt - - - name: Build Wheel - run: | - cd $GITHUB_WORKSPACE - python -m pip install --upgrade pip twine wheel setuptools - python -m setup bdist_wheel --plat-name macosx-13.0-arm64 --dist-dir dist - - - name: Upload MacOS ${{ matrix.python-version }} Wheel - uses: actions/upload-artifact@v4 - with: - name: apple10sbuild${{ matrix.python-version }} - path: ${{ github.workspace }}/dist/*.whl - overwrite: true - - build-linux-x64-wheels: - - runs-on: ubuntu-22.04 - env: - CXX: g++-10 - strategy: - matrix: - python-version: [ 3.8, 3.9, "3.10", "3.11", "3.12", "3.13", "3.14" ] - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Retrieve submodules/Dependencies - run: | - git submodule update --init --recursive ./thirdparty/imgui - git submodule update --init --recursive ./thirdparty/implot - git submodule update --init --recursive ./thirdparty/glfw - sudo apt-get update - sudo apt-get install libglu1-mesa-dev libgl1-mesa-dev xorg-dev libxrandr-dev -y - - - name: Mark Versions - run: | - cd $GITHUB_WORKSPACE - echo ${{ github.event.inputs.version }} > version_number.txt - - - name: Build Wheel - run: | - cd $GITHUB_WORKSPACE - python -m pip install --upgrade pip twine wheel setuptools - python -m setup bdist_wheel --plat-name manylinux1_x86_64 --dist-dir dist - - - name: Upload Linux ${{ matrix.python-version }} Wheel - uses: actions/upload-artifact@v4 - with: - name: linuxbuild${{ matrix.python-version }} - path: ${{ github.workspace }}/dist/*.whl - overwrite: true - - build-linux-aarch64-wheels: - - runs-on: ubuntu-22.04-arm - env: - CXX: g++-10 - strategy: - matrix: - python-version: [ 3.8, 3.9, "3.10", "3.11", "3.12", "3.13", "3.14" ] - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Retrieve submodules/Dependencies - run: | - git submodule update --init --recursive ./thirdparty/imgui - git submodule update --init --recursive ./thirdparty/implot - git submodule update --init --recursive ./thirdparty/glfw - sudo apt-get update - sudo apt-get install libglu1-mesa-dev libgl1-mesa-dev xorg-dev libxrandr-dev -y - - - name: Mark Versions - run: | - cd $GITHUB_WORKSPACE - echo ${{ github.event.inputs.version }} > version_number.txt - - - name: Build Wheel - run: | - cd $GITHUB_WORKSPACE - python -m pip install --upgrade pip twine wheel setuptools - python -m setup bdist_wheel --plat-name manylinux2014_aarch64 --dist-dir dist - - - name: Upload Linux ${{ matrix.python-version }} Wheel - uses: actions/upload-artifact@v4 - with: - name: linuxaarchbuild${{ matrix.python-version }} - path: ${{ github.workspace }}/dist/*.whl - overwrite: true - - deploy-packages: - - needs: [build-windows-wheels, build-linux-x64-wheels, build-linux-aarch64-wheels, build-mac-silicon-wheels] - runs-on: windows-2022 - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Python 3.9 - uses: actions/setup-python@v5 - with: - python-version: 3.9 - - - name: Install Dependencies - run: | - python -m pip install --upgrade pip setuptools wheel twine - - - name: Download artifacts - uses: actions/download-artifact@v4 - - - name: PyPi Deployment - shell: cmd - if: ${{contains(github.event.inputs.deploy, 'true') && github.ref == 'refs/heads/master'}} - run: | - python -m twine upload windowsbuild*/* -u __token__ -p ${{ secrets.PYPI_PASSWORD }} --skip-existing - python -m twine upload apple10sbuild*/* -u __token__ -p ${{ secrets.PYPI_PASSWORD }} --skip-existing - python -m twine upload linuxbuild*/* -u __token__ -p ${{ secrets.PYPI_PASSWORD }} --skip-existing - python -m twine upload linuxaarchbuild*/* -u __token__ -p ${{ secrets.PYPI_PASSWORD }} --skip-existing - - - name: Test PyPi Deployment - shell: cmd - if: "contains(github.event.inputs.deploytest, 'true')" - run: | - dir - python -m twine upload --repository testpypi windowsbuild*/* -u __token__ -p ${{ secrets.TEST_PYPI_PASSWORD }} --skip-existing - python -m twine upload --repository testpypi apple10sbuild*/* -u __token__ -p ${{ secrets.TEST_PYPI_PASSWORD }} --skip-existing - python -m twine upload --repository testpypi linuxbuild*/* -u __token__ -p ${{ secrets.TEST_PYPI_PASSWORD }} --skip-existing - python -m twine upload --repository testpypi linuxaarchbuild*/* -u __token__ -p ${{ secrets.TEST_PYPI_PASSWORD }} --skip-existing diff --git a/.github/workflows/EmbeddedBuild.yml b/.github/workflows/EmbeddedBuild.yml index e21d690cc..ac70d6d86 100644 --- a/.github/workflows/EmbeddedBuild.yml +++ b/.github/workflows/EmbeddedBuild.yml @@ -1,37 +1,19 @@ name: Embedded Build on: - - schedule: - - cron: '0 1 * * 1' - - push: - - branches: - - master - - development - - development_* - - paths-ignore: - - 'docs/**' - - 'assets/**' - - 'scripts/**' - - pull_request: - - workflow_dispatch: + push: {} + pull_request: {} jobs: build-windows: - runs-on: windows-2022 - if: ${{! contains(github.event.head_commit.message, '[individual]') || contains(github.event.head_commit.message, '[windows]')}} + runs-on: windows-2019 + if: "! contains(github.event.head_commit.message, '[skip ci]')" steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v2 - name: Retrieve submodules shell: cmd @@ -40,139 +22,78 @@ jobs: - name: Build Python shell: cmd run: | - cd %GITHUB_WORKSPACE% - cd scripts + cd Scripts call BuildPythonForWindows.bat --ci + cd .. + mkdir cmake-build-release + cd cmake-build-release + cmake .. - name: Build DearPyGui shell: cmd run: | - cd %GITHUB_WORKSPACE% - mkdir cmake-build-release - cd cmake-build-release - cmake .. -DMV_TESTS_ONLY=True - cd .. cmake --build cmake-build-release --config Release -# temporarily removed until github runners are fixed (freetype is causing issues) -# - name: Run Tests -# shell: cmd -# run: | -# cd %GITHUB_WORKSPACE% -# cd cmake-build-release\DearSandbox -# DearSandbox.exe - build-MacOS: - + runs-on: MacOS-latest - if: ${{! contains(github.event.head_commit.message, '[individual]') || contains(github.event.head_commit.message, '[apple]')}} + if: "! contains(github.event.head_commit.message, '[skip ci]')" steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v2 - name: Retrieve submodules run: git submodule update --init --recursive - + - name: Build Python run: | - cd $GITHUB_WORKSPACE - cd thirdparty/cpython - mkdir -p build/debug - chmod +x configure - cd build/debug - ../../configure --with-pydebug --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) + cd Dependencies/cpython + mkdir debug + cd debug + ../configure --with-pydebug --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) make make install - name: Build DearPyGui run: | - cd $GITHUB_WORKSPACE - mkdir cmake-build-debug - cd cmake-build-debug - cmake .. -DMV_TESTS_ONLY=True - cd .. - cmake --build cmake-build-debug --config Debug - - build-x64-Linux: - - # Delete in the future - name: build-Ubuntu - runs-on: ubuntu-22.04 - env: - CXX: g++-10 - if: ${{! contains(github.event.head_commit.message, '[individual]') || contains(github.event.head_commit.message, '[linux]')}} - - steps: - - - name: Checkout - uses: actions/checkout@v4 - - - name: Retrieve submodules - run: git submodule update --init --recursive - - - name: Install Dependencies - run: | - cd $GITHUB_WORKSPACE - sudo apt-get update - sudo apt-get install libgl1-mesa-dev xorg-dev - - - name: Build Python - run: | - cd $GITHUB_WORKSPACE - cd thirdparty/cpython - mkdir -p build/debug - chmod +x configure - cd build/debug - ../../configure --with-pydebug --enable-shared - make - - - name: Build DearPyGui - run: | - cd $GITHUB_WORKSPACE mkdir cmake-build-debug cd cmake-build-debug - cmake .. -DMV_TESTS_ONLY=True + cmake .. cd .. cmake --build cmake-build-debug --config Debug - build-aarch64-Linux: - - runs-on: ubuntu-22.04-arm - env: - CXX: g++-10 - if: ${{! contains(github.event.head_commit.message, '[individual]') || contains(github.event.head_commit.message, '[linux]')}} + build-Ubuntu: + + runs-on: ubuntu-18.04 + if: "! contains(github.event.head_commit.message, '[skip ci]')" steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v2 - name: Retrieve submodules run: git submodule update --init --recursive - name: Install Dependencies run: | - cd $GITHUB_WORKSPACE sudo apt-get update - sudo apt-get install libgl1-mesa-dev xorg-dev - + sudo apt-get install libgl1-mesa-dev + sudo apt-get install xorg-dev + sudo apt-get install libfreetype6-dev + - name: Build Python run: | - cd $GITHUB_WORKSPACE - cd thirdparty/cpython - mkdir -p build/debug - chmod +x configure - cd build/debug - ../../configure --with-pydebug --enable-shared + cd Dependencies/cpython + mkdir debug + cd debug + ../configure --with-pydebug --enable-shared make - name: Build DearPyGui run: | - cd $GITHUB_WORKSPACE mkdir cmake-build-debug cd cmake-build-debug - cmake .. -DMV_TESTS_ONLY=True + cmake .. cd .. cmake --build cmake-build-debug --config Debug diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 12c507982..739759947 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -1,29 +1,16 @@ -name: Static Analysis +name: static-analysis on: - push: - - branches: - - master - - development - - development_* - - paths-ignore: - - 'docs/**' - - 'assets/**' - - 'scripts/**' - - pull_request: - workflow_dispatch: + push: {} + pull_request: {} jobs: PVS-Studio: - runs-on: ubuntu-22.04 - if: ${{! contains(github.event.head_commit.message, '[individual]') || contains(github.event.head_commit.message, '[static analysis]')}} + runs-on: ubuntu-18.04 steps: - - uses: actions/checkout@v4 - #with: - # fetch-depth: 1 + - uses: actions/checkout@v1 + with: + fetch-depth: 1 - name: Retrieve submodules run: git submodule update --init --recursive @@ -48,11 +35,11 @@ jobs: sudo apt-get update sudo apt-get install libgl1-mesa-dev sudo apt-get install xorg-dev - cd thirdparty/cpython - chmod +x configure - mkdir -p build/debug - cd build/debug - ../../configure --with-pydebug --enable-shared + sudo apt-get install libfreetype6-dev + cd Dependencies/cpython + mkdir debug + cd debug + ../configure --with-pydebug --enable-shared make - name: PVS-Studio static analysis @@ -69,12 +56,12 @@ jobs: cmake .. -DCMAKE_EXPORT_COMPILE_COMMANDS=On cd .. pvs-studio-analyzer trace -- cmake --build cmake-build-debug --config Debug - pvs-studio-analyzer analyze -e ./thirdparty -l pvs-studio.lic -o pvs-studio.log - plog-converter -a 'GA:1,2;OP:1' -t html -o pvs-studio.html -w pvs-studio.log + pvs-studio-analyzer analyze -e ./Dependencies -e ./DearPyGui/vendor -e ./DearPyGui/src/core/AppItems/custom/mvTextEditor.cpp -l pvs-studio.lic -o pvs-studio.log + plog-converter -a 'GA:1,2;OP:1' -t fullhtml -o pvs-studio.html -w pvs-studio.log - name: Archive code coverage results if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v2 with: name: pvs-results - path: /home/runner/work/DearPyGui/DearPyGui/pvs-studio.html \ No newline at end of file + path: /home/runner/work/DearPyGui/DearPyGui/pvs-studio.html diff --git a/.gitignore b/.gitignore index 45385971a..7611eadd8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,9 @@ .idea/ .vs/ -.vscode/ out/ cmake-build-debug/ cmake-build-release/ cmake-build-local/ -output/ +Output/ dist/ -.DS_Store -__pycache__/ -lib_location.txt -version_number.txt -dearpygui.egg-info/ -build/ -# Ignore only subdirectories -sandbox/*/ -src/CMakeFiles/ -thirdparty/CMakeFiles/ -thirdparty/Makefile -thirdparty/cmake_install.cmake +.DS_Store \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 22c3527e4..eed104296 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,19 +1,22 @@ -[submodule "thirdparty/imgui"] - path = thirdparty/imgui +[submodule "Dependencies/imgui"] + path = Dependencies/imgui url = https://github.com/ocornut/imgui - branch = docking -[submodule "thirdparty/implot"] - path = thirdparty/implot - url = https://github.com/epezent/implot branch = master -[submodule "thirdparty/cpython"] - path = thirdparty/cpython +[submodule "Dependencies/cpython"] + path = Dependencies/cpython url = https://github.com/python/cpython branch = master -[submodule "thirdparty/glfw"] - path = thirdparty/glfw +[submodule "Dependencies/glfw"] + path = Dependencies/glfw url = https://github.com/glfw/glfw branch = master -[submodule "thirdparty/freetype"] - path = thirdparty/freetype +[submodule "Dependencies/ImGuiFileDialog"] + path = Dependencies/ImGuiFileDialog + url = https://github.com/aiekick/ImGuiFileDialog + branch = master +[submodule "Dependencies/spdlog"] + path = Dependencies/spdlog + url = https://github.com/gabime/spdlog +[submodule "Dependencies/freetype"] + path = Dependencies/freetype url = https://gitlab.freedesktop.org/freetype/freetype diff --git a/.readthedocs.yaml b/.readthedocs.yaml deleted file mode 100644 index 2ff93384f..000000000 --- a/.readthedocs.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -build: - os: ubuntu-22.04 - tools: - python: "3.8" - -# Build documentation in the docs/ directory with Sphinx -sphinx: - configuration: docs/source/conf.py - -# Optionally build your docs in additional formats such as PDF and ePub -formats: all - -python: - install: - - requirements: docs/requirements.txt - - method: pip - path: . diff --git a/CMakeLists.txt b/CMakeLists.txt index 33a54057b..989737966 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,40 +1,18 @@ -cmake_minimum_required (VERSION 3.16) +cmake_minimum_required (VERSION 3.13) -if(APPLE) - # When using precompiled headers on macOS, we need to enable Objective-C - # as a distinct language. This won't work on other platforms (will fail to - # find the Obj-C compiler), hence the "if APPLE". - project ("DearPyGui" LANGUAGES C CXX OBJC OBJCXX) -else() - project ("DearPyGui") -endif() - -if(WIN32) - add_definitions(-DIMGUI_USER_CONFIG="mvImGuiConfig_win32.h") - add_definitions(-DMV_PLATFORM="windows") -elseif(APPLE) - add_definitions(-DIMGUI_USER_CONFIG="mvImGuiConfig_apple.h") - add_definitions(-DMV_PLATFORM="apple") -else() # Linux - add_definitions(-DIMGUI_USER_CONFIG="mvImGuiConfig_linux.h") - add_definitions(-DMV_PLATFORM="linux") -endif() - -if(WIN32) -else() # Linux - add_definitions(-DCUSTOM_IMGUIFILEDIALOG_CONFIG="ImGuiFileDialogConfigUnix.h") -endif() +project ("DearPyGui") # various settings -add_definitions( - -D_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR - -D_CRT_SECURE_NO_WARNINGS - -D_USE_MATH_DEFINES) - -set(MV_PY_VERSION ${MV_PY_VERSION}) -set(MVDPG_VERSION ${MVDPG_VERSION}) -add_definitions(-DMV_DPG_MAJOR_VERSION=1) -add_definitions(-DMV_DPG_MINOR_VERSION=0) +set(GLFW_BUILD_DOCS OFF) +add_definitions(-D_USE_MATH_DEFINES -DIMGUI_USER_CONFIG="mvImGuiConfig.h") + +# can be set to 36, 37, 38, 39, or 0 +# * 36 = Python 3.6 +# * 37 = Python 3.7 +# * 38 = Python 3.8 +# * 39 = Python 3.9 +# * 0 = Embedded Python +set(MVPY_VERSION ${MVPY_VERSION}) if(MVDPG_VERSION) add_definitions(-DMV_SANDBOX_VERSION="${MVDPG_VERSION}") else() @@ -44,35 +22,32 @@ endif() # when set to "ON", the embedded version # will be the only version build (no sandbox builds) set(MVDIST_ONLY ${MVDIST_ONLY}) + if(MVDIST_ONLY) add_definitions(-DMVDIST_ONLY) -else() - add_definitions(-DMV_LOG) endif() -# runs python tests -set(MV_TESTS_ONLY ${MV_TESTS_ONLY}) -if(MV_TESTS_ONLY) - add_definitions(-DMV_TESTS_ONLY) -endif() - -# Specifying MV_NO_USER_THREADS turns off some thread safety features (might give -# you some perf gain, yeah, those 0.01%) and must only be used when no user threads -# (threading.Thread) **ever** call DPG API. With MV_NO_USER_THREADS, it's only -# allowed to call DPG from the main thread and from handlers/callbacks. -# Also can be used to get back the behavior of old DPG versions that were thread -# unsafe (for testing/debugging). -set(MV_NO_USER_THREADS ${MV_NO_USER_THREADS}) -if(MV_NO_USER_THREADS) - add_definitions(-DMV_NO_USER_THREADS) +if(NOT MVDIST_ONLY) + add_subdirectory ("ImguiTesting") + add_definitions(-DMV_LOG) endif() -add_subdirectory("thirdparty") +# version number of Dear PyGui, usually set +# by AppVeyor +set(MVDPG_VERSION ${MVDPG_VERSION}) # if this is not a distribution build # build development environment if(NOT MVDIST_ONLY) - add_subdirectory ("sandbox") + add_subdirectory("Dependencies/spdlog") + add_subdirectory ("DearSandbox") +endif() + +if(WIN32) + # do nothing +else() # Apple and Linux + add_subdirectory ("Dependencies/glfw") endif() -add_subdirectory ("src") +add_subdirectory("Dependencies/freetype") +add_subdirectory ("DearPyGui") diff --git a/CMakeSettings.json b/CMakeSettings.json index fdf20f56f..1f2f0d758 100644 --- a/CMakeSettings.json +++ b/CMakeSettings.json @@ -2,14 +2,15 @@ "configurations": [ { "name": "x64-Debug", - "generator": "Ninja", + "generator": "Visual Studio 16 2019 Win64", "configurationType": "Debug", "inheritEnvironments": [ "msvc_x64_x64" ], "buildRoot": "${projectDir}\\cmake-build-debug", "installRoot": "${projectDir}\\out\\install\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "", - "ctestCommandArgs": "" + "ctestCommandArgs": "", + "variables": [] }, { "name": "x64-Release", @@ -20,7 +21,8 @@ "cmakeCommandArgs": "", "buildCommandArgs": "", "ctestCommandArgs": "", - "inheritEnvironments": [ "msvc_x64_x64" ] + "inheritEnvironments": [ "msvc_x64_x64" ], + "variables": [] } ] } \ No newline at end of file diff --git a/testing/.gitignore b/DearPyGui/.gitignore similarity index 100% rename from testing/.gitignore rename to DearPyGui/.gitignore diff --git a/DearPyGui/CMakeLists.txt b/DearPyGui/CMakeLists.txt new file mode 100644 index 000000000..04c766447 --- /dev/null +++ b/DearPyGui/CMakeLists.txt @@ -0,0 +1,29 @@ +cmake_minimum_required (VERSION 3.13) + +include("cmake/dpg_sources.cmake") + +# For distribution +if(MVDIST_ONLY) + + add_library(core SHARED) + + target_sources(core PRIVATE ${MARVEL_SOURCES}) + + target_compile_definitions(core + + PRIVATE + $<$:MV_RELEASE> + ) + + if(WIN32) + include("cmake/windows_runner.cmake") + elseif(APPLE) + include("cmake/mac_runner.cmake") + else() # Linux + include("cmake/linux_runner.cmake") + endif() + +# For development +else() + include("cmake/embedded.cmake") +endif() diff --git a/DearPyGui/cmake/dpg_sources.cmake b/DearPyGui/cmake/dpg_sources.cmake new file mode 100644 index 000000000..2befdfc8b --- /dev/null +++ b/DearPyGui/cmake/dpg_sources.cmake @@ -0,0 +1,198 @@ + +set(MARVEL_SOURCES + + "$<$:src/core/Modules/mvModule_Core.cpp>" + "$<$:src/core/Modules/mvModule_Core.cpp>" + "$<$:src/core/Modules/mvModule_Core.mm>" + + "src/core/AppItems/composite/mvDebugWindow.cpp" + "src/core/AppItems/composite/mvDocWindow.cpp" + + "src/core/PythonUtilities/mvPyObject.cpp" + "src/core/PythonUtilities/mvPythonTranslator.cpp" + "src/core/PythonUtilities/mvPythonParser.cpp" + "src/core/PythonUtilities/mvPythonExceptions.cpp" + "src/core/PythonUtilities/mvGlobalIntepreterLock.cpp" + + "$<$:src/platform/Windows/mvWindowsViewport.cpp>" + "$<$:src/platform/Windows/mvUtilities.cpp>" + + "$<$:src/platform/Apple/mvAppleViewport.mm>" + "$<$:src/platform/Apple/mvAppleUtilities.mm>" + + "$<$:src/platform/Linux/mvUtilities.cpp>" + "$<$:src/platform/Linux/mvLinuxViewport.cpp>" + + "src/core/mvEvents.cpp" + "src/core/mvApp.cpp" + "src/core/mvAppLog.cpp" + "src/core/mvInput.cpp" + "src/core/mvViewport.cpp" + "src/core/mvProfiler.cpp" + "src/core/mvLog.cpp" + + "src/core/Theming/mvThemeManager.cpp" + "src/core/Theming/mvFontScope.cpp" + "src/core/Theming/mvFontManager.cpp" + + "src/core/Registries/mvCallbackRegistry.cpp" + "src/core/Registries/mvTextureStorage.cpp" + + "src/core/AppItems/mvAppItemState.cpp" + "src/core/AppItems/mvAppItem.cpp" + "src/core/AppItems/mvTypeBases.cpp" + "src/core/AppItems/mvItemRegistry.cpp" + + "src/core/AppItems/basic/mvMenuItem.cpp" + "src/core/AppItems/basic/mvInputText.cpp" + "src/core/AppItems/basic/mvText.cpp" + "src/core/AppItems/basic/mvSliderSingle.cpp" + "src/core/AppItems/basic/mvSliderMulti.cpp" + "src/core/AppItems/basic/mvImage.cpp" + "src/core/AppItems/basic/mvImageButton.cpp" + "src/core/AppItems/basic/mvColorButton.cpp" + "src/core/AppItems/basic/mvColorEdit.cpp" + "src/core/AppItems/basic/mvColorPicker.cpp" + "src/core/AppItems/basic/mvRadioButton.cpp" + "src/core/AppItems/basic/mvListbox.cpp" + "src/core/AppItems/basic/mvCombo.cpp" + "src/core/AppItems/basic/mvCheckbox.cpp" + "src/core/AppItems/basic/mvButton.cpp" + "src/core/AppItems/basic/mvSelectable.cpp" + "src/core/AppItems/basic/mvTabButton.cpp" + "src/core/AppItems/basic/mvDragSingle.cpp" + "src/core/AppItems/basic/mvDragMulti.cpp" + "src/core/AppItems/basic/mvInputSingle.cpp" + "src/core/AppItems/basic/mvInputMulti.cpp" + + "src/core/AppItems/misc/mvProgressBar.cpp" + "src/core/AppItems/misc/mvIndent.cpp" + "src/core/AppItems/misc/mvUnindent.cpp" + "src/core/AppItems/misc/mvSameLine.cpp" + "src/core/AppItems/misc/mvSeparator.cpp" + "src/core/AppItems/misc/mvDummy.cpp" + "src/core/AppItems/misc/mvSpacing.cpp" + + "src/core/AppItems/containers/mvCollapsingHeader.cpp" + "src/core/AppItems/containers/mvGroup.cpp" + "src/core/AppItems/containers/mvChild.cpp" + "src/core/AppItems/containers/mvTooltip.cpp" + "src/core/AppItems/containers/mvTab.cpp" + "src/core/AppItems/containers/mvTabBar.cpp" + "src/core/AppItems/containers/mvMenu.cpp" + "src/core/AppItems/containers/mvMenuBar.cpp" + "src/core/AppItems/containers/mvTreeNode.cpp" + "src/core/AppItems/containers/mvWindowAppItem.cpp" + "src/core/AppItems/containers/mvPopup.cpp" + + "src/core/AppItems/tables/mvTable.cpp" + "src/core/AppItems/tables/mvTableColumn.cpp" + "src/core/AppItems/tables/mvTableNextColumn.cpp" + + "src/core/AppItems/custom/mvDatePicker.cpp" + "src/core/AppItems/custom/mvTimePicker.cpp" + "src/core/AppItems/custom/mvTextEditor.cpp" + "src/core/AppItems/custom/mvColorMapScale.cpp" + + "src/core/AppItems/drawing/mvDrawing.cpp" + "src/core/AppItems/drawing/mvDrawLine.cpp" + "src/core/AppItems/drawing/mvDrawArrow.cpp" + "src/core/AppItems/drawing/mvDrawTriangle.cpp" + "src/core/AppItems/drawing/mvDrawCircle.cpp" + "src/core/AppItems/drawing/mvDrawBezierCurve.cpp" + "src/core/AppItems/drawing/mvDrawQuad.cpp" + "src/core/AppItems/drawing/mvDrawRect.cpp" + "src/core/AppItems/drawing/mvDrawText.cpp" + "src/core/AppItems/drawing/mvDrawPolygon.cpp" + "src/core/AppItems/drawing/mvDrawPolyline.cpp" + "src/core/AppItems/drawing/mvDrawImage.cpp" + + "src/core/AppItems/composite/mvFileDialog.cpp" + "src/core/AppItems/composite/mvAboutWindow.cpp" + "src/core/AppItems/composite/mvDataGrid.cpp" + "src/core/AppItems/composite/mvLogger.cpp" + "src/core/AppItems/composite/mvStyleWindow.cpp" + "src/core/AppItems/composite/mvMetricsWindow.cpp" + "src/core/AppItems/composite/mvAboutWindow.cpp" + + "src/core/AppItems/nodes/mvNodeEditor.cpp" + "src/core/AppItems/nodes/mvNode.cpp" + "src/core/AppItems/nodes/mvNodeAttribute.cpp" + + "src/core/AppItems/plots/mvPlot.cpp" + "src/core/AppItems/plots/mvAreaSeries.cpp" + "src/core/AppItems/plots/mvDragPoint.cpp" + "src/core/AppItems/plots/mvDragLine.cpp" + "src/core/AppItems/plots/mvAnnotation.cpp" + "src/core/AppItems/plots/mvSimplePlot.cpp" + "src/core/AppItems/plots/mvLineSeries.cpp" + "src/core/AppItems/plots/mvScatterSeries.cpp" + "src/core/AppItems/plots/mvStemSeries.cpp" + "src/core/AppItems/plots/mvStairSeries.cpp" + "src/core/AppItems/plots/mvBarSeries.cpp" + "src/core/AppItems/plots/mvErrorSeries.cpp" + "src/core/AppItems/plots/mvInfiniteLineSeries.cpp" + "src/core/AppItems/plots/mvHeatSeries.cpp" + "src/core/AppItems/plots/mvImageSeries.cpp" + "src/core/AppItems/plots/mvPieSeries.cpp" + "src/core/AppItems/plots/mvShadeSeries.cpp" + "src/core/AppItems/plots/mvLabelSeries.cpp" + "src/core/AppItems/plots/mvCandleSeries.cpp" + + # imnodes + "vendor/imnodes/imnodes.cpp" + + # implot + "vendor/implot/implot.cpp" + "vendor/implot/implot_items.cpp" + "vendor/implot/implot_demo.cpp" + + # ImGuiFileDialog + "../Dependencies/ImGuiFileDialog/ImGuiFileDialog/ImGuiFileDialog.cpp" + + # imgui + "../Dependencies/imgui/misc/freetype/imgui_freetype.cpp" + "../Dependencies/imgui/misc/cpp/imgui_stdlib.cpp" + "../Dependencies/imgui/imgui.cpp" + "../Dependencies/imgui/imgui_demo.cpp" + "../Dependencies/imgui/imgui_draw.cpp" + "../Dependencies/imgui/imgui_widgets.cpp" + "../Dependencies/imgui/imgui_tables.cpp" + "$<$:../Dependencies/imgui/backends/imgui_impl_win32.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_dx11.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_metal.mm>" + "$<$:../Dependencies/imgui/backends/imgui_impl_glfw.cpp>" + "$<$:../Dependencies/imgui/examples/libs/gl3w/GL/gl3w.c>" + "$<$:../Dependencies/imgui/backends/imgui_impl_glfw.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_opengl3.cpp>" +) + +set(MARVEL_INCLUDE_DIR + + "vendor/implot" + "vendor/stb" + "vendor/imnodes" + "src/" + "src/core" + "src/core/Modules" + "src/core/AppItems" + "src/core/DrawCommands" + "src/core/CppUtilities" + "src/core/PythonUtilities" + "src/core/Registries" + "src/core/Theming" + "$<$:${CMAKE_SOURCE_DIR}/DearPyGui/vendor/dirent/>" + "../Dependencies/ImGuiFileDialog/ImGuiFileDialog/" + "../Dependencies/spdlog/include/" + "../Dependencies/glfw/include/" + "../Dependencies/glfw/deps/" + "../Dependencies/imgui/" + "../Dependencies/imgui/misc/freetype/" + "../Dependencies/imgui/backends/" + "../Dependencies/imgui/examples/libs/gl3w" + "../Dependencies/cpython/" + "../Dependencies/cpython/Include/" + "$<$:${CMAKE_SOURCE_DIR}/Dependencies/cpython/PC/>" + # may can delete this + "../Dependencies/cpython/debug/" +) diff --git a/src/embedded.cmake b/DearPyGui/cmake/embedded.cmake similarity index 59% rename from src/embedded.cmake rename to DearPyGui/cmake/embedded.cmake index 5614ecf91..ca00e1613 100644 --- a/src/embedded.cmake +++ b/DearPyGui/cmake/embedded.cmake @@ -1,14 +1,7 @@ -cmake_minimum_required (VERSION 3.16) +cmake_minimum_required (VERSION 3.13) add_library(coreemb STATIC) - -set_target_properties(coreemb - PROPERTIES - CXX_STANDARD 17 - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearPyGui/" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearPyGui/" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearPyGui/" - ) +set_target_properties(coreemb PROPERTIES CXX_STANDARD 17) target_include_directories(coreemb PRIVATE ${MARVEL_INCLUDE_DIR}) @@ -21,24 +14,19 @@ target_compile_definitions(coreemb # Add sources target_sources(coreemb PRIVATE ${MARVEL_SOURCES}) -if(WIN32) - target_precompile_headers(coreemb - PRIVATE mvPyUtils.h - ) -endif() - ############################################################################### # Windows Specifics ############################################################################### if(WIN32) add_definitions(-DWIN32) + add_definitions(-DMV_PROFILE) # tell cmake where to find the python3x dlls - target_link_directories(coreemb PRIVATE "../thirdparty/cpython/PCbuild/amd64/") + target_link_directories(coreemb PRIVATE "../Dependencies/cpython/PCbuild/amd64/") # Add libraries to link to - target_link_libraries(coreemb PUBLIC d3d11 dxgi freetype dwmapi $<$:python39_d> $<$:python39>) + target_link_libraries(coreemb PUBLIC d3d11 freetype $<$:python39_d> $<$:python39>) ############################################################################### # Apple Specifics @@ -46,17 +34,19 @@ if(WIN32) elseif(APPLE) add_definitions(-DAPPLE) + add_definitions(-DUNIX) # tell cmake where to find the python3x dlls - target_link_directories(coreemb PRIVATE "../thirdparty/cpython/build/debug") + target_link_directories(coreemb PRIVATE "../Dependencies/cpython/debug") - SET_PROPERTY(TARGET coreemb APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -arch x86_64") + SET_PROPERTY(TARGET coreemb APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc -Wunused-function -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64") target_link_libraries(coreemb PUBLIC glfw + freetype "-framework Metal" "-framework MetalKit" "-framework Cocoa" @@ -76,11 +66,11 @@ else() # Linux add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GL3W) # tell cmake where to find the python3x dlls - target_link_directories(coreemb PRIVATE "../thirdparty/cpython/build/debug") + target_link_directories(coreemb PRIVATE "../Dependencies/cpython/debug") - set_property(TARGET coreemb APPEND_STRING PROPERTY COMPILE_FLAGS "-fPIC -DNDEBUG -g -fwrapv -O3") + set_property(TARGET coreemb APPEND_STRING PROPERTY COMPILE_FLAGS "-fPIC -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall") # Add libraries to link to - target_link_libraries(coreemb PRIVATE "-lcrypt -lpthread -ldl -lutil -lm" GL glfw python3.9d) + target_link_libraries(coreemb PRIVATE "-lcrypt -lpthread -ldl -lutil -lm" GL glfw python3.9d freetype) endif() diff --git a/DearPyGui/cmake/linux_runner.cmake b/DearPyGui/cmake/linux_runner.cmake new file mode 100644 index 000000000..2cdb12429 --- /dev/null +++ b/DearPyGui/cmake/linux_runner.cmake @@ -0,0 +1,132 @@ + +add_definitions(-DLINUX) +add_definitions(-DUNIX) +set_target_properties(core PROPERTIES PREFIX "") +set_target_properties(core PROPERTIES CXX_STANDARD 17) + +set_property(TARGET core APPEND_STRING PROPERTY COMPILE_FLAGS "-fPIC -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall") + +add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GL3W) + +if(MVPY_VERSION EQUAL 36) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/home/appveyor/.localpython3.6.12" + "/home/appveyor/.localpython3.6.12/include/python3.6m" + ) + + target_link_directories(core + PRIVATE + "/usr/lib" + "/home/appveyor/.localpython3.6.12/lib" + ) + + target_link_libraries(core + PRIVATE + "-fPIC -lcrypt -lpthread -ldl -lutil -lm" + GL + freetype + glfw + python3.6m + ) + +elseif(MVPY_VERSION EQUAL 37) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/home/appveyor/.localpython3.7.9" + "/home/appveyor/.localpython3.7.9/include/python3.7m" + ) + + target_link_directories(core + PRIVATE + "/usr/lib" + "/home/appveyor/.localpython3.7.9/lib" + ) + + target_link_libraries(core + PRIVATE + "-fPIC -lcrypt -lpthread -ldl -lutil -lm" + GL + freetype + glfw + python3.7m + ) + +elseif(MVPY_VERSION EQUAL 38) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/home/appveyor/.localpython3.8.6" + "/home/appveyor/.localpython3.8.6/include/python3.8" + ) + + target_link_directories(core + PRIVATE + "/usr/lib" + "/home/appveyor/.localpython3.8.6/lib" + ) + + target_link_libraries(core + PRIVATE + "-fPIC -lcrypt -lpthread -ldl -lutil -lm" + GL + freetype + glfw + python3.8 + ) + +elseif(MVPY_VERSION EQUAL 39) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/home/appveyor/.localpython3.9.1" + "/home/appveyor/.localpython3.9.1/include/python3.9" + ) + + target_link_directories(core + PRIVATE + "/usr/lib" + "/home/appveyor/.localpython3.9.1/lib" + ) + + target_link_libraries(core + PRIVATE + "-fPIC -lcrypt -lpthread -ldl -lutil -lm" + GL + glfw + freetype + python3.9 + ) + +elseif(MVPY_VERSION EQUAL 0) + find_package (Python COMPONENTS Development) + if(NOT Python_Development_FOUND) + message(FATAL_ERROR "The python3 development library from your distribution repo need to be installed first!") + endif() + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + ${Python_INCLUDE_DIRS} + ) + + target_link_directories(core + PRIVATE + "/usr/lib" + ${Python_LIBRARY_DIRS} + ) + + target_link_libraries(core + PRIVATE + "-fPIC -lcrypt -lpthread -ldl -lutil -lm" + GL + glfw + freetype + ${Python_LIBRARIES} + ) +endif() \ No newline at end of file diff --git a/DearPyGui/cmake/mac_runner.cmake b/DearPyGui/cmake/mac_runner.cmake new file mode 100644 index 000000000..af21d7626 --- /dev/null +++ b/DearPyGui/cmake/mac_runner.cmake @@ -0,0 +1,88 @@ + +add_definitions(-DAPPLE) +add_definitions(-DUNIX) +set_target_properties(core PROPERTIES SUFFIX ".so") +set_target_properties(core PROPERTIES PREFIX "") +set_target_properties(core PROPERTIES CXX_STANDARD 17) + +SET_PROPERTY(TARGET core APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall") + +target_link_libraries(core + + PRIVATE + + glfw + freetype + "-undefined dynamic_lookup" + "-framework Metal" + "-framework MetalKit" + "-framework Cocoa" + "-framework CoreVideo" + "-framework IOKit" + "-framework QuartzCore" +) + +if(MVPY_VERSION EQUAL 36) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/Users/appveyor/.localpython3.6.12" + "/Users/appveyor/.localpython3.6.12/include/python3.6m" + ) + + target_link_directories(core + PRIVATE + "/Users/appveyor/.localpython3.6.12/lib" + ) + +elseif(MVPY_VERSION EQUAL 37) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/Users/appveyor/.localpython3.7.9" + "/Users/appveyor/.localpython3.7.9/include/python3.7m" + ) + + target_link_directories(core + PRIVATE + "/Users/appveyor/.localpython3.7.9/lib" + ) + +elseif(MVPY_VERSION EQUAL 38) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/Users/appveyor/.localpython3.8.6" + "/Users/appveyor/.localpython3.8.6/include/python3.8" + ) + + target_link_directories(core + PRIVATE + "/Users/appveyor/.localpython3.8.6/lib" + ) + +elseif(MVPY_VERSION EQUAL 39) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "/Users/appveyor/.localpython3.9.1" + "/Users/appveyor/.localpython3.9.1/include/python3.9" + ) + + target_link_directories(core + PRIVATE + "/Users/appveyor/.localpython3.9.1/lib" + ) + +elseif(MVPY_VERSION EQUAL 0) + target_link_directories(core PRIVATE ../Dependencies/cpython/debug) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + ) +endif() \ No newline at end of file diff --git a/DearPyGui/cmake/windows_runner.cmake b/DearPyGui/cmake/windows_runner.cmake new file mode 100644 index 000000000..b04f28c85 --- /dev/null +++ b/DearPyGui/cmake/windows_runner.cmake @@ -0,0 +1,85 @@ + +add_definitions(-DWIN32) +set_target_properties(core PROPERTIES SUFFIX ".pyd") +set_target_properties(core PROPERTIES CXX_STANDARD 17) + +if(MVPY_VERSION EQUAL 36) + + target_link_libraries(core PUBLIC d3d11 python36 freetype) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "C:/Python36-x64" + "C:/Python36-x64/include" + ) + + target_link_directories(core + PRIVATE + "C:/Python36-x64" + "C:/Python36-x64/libs" + "C:/Python36-x64/DLLs" + ) + +elseif(MVPY_VERSION EQUAL 37) + + target_link_libraries(core PUBLIC d3d11 python37 freetype) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "C:/Python37-x64" + "C:/Python37-x64/include" + ) + + target_link_directories(core + PRIVATE + "C:/Python37-x64" + "C:/Python37-x64/libs" + "C:/Python37-x64/DLLs" + ) + +elseif(MVPY_VERSION EQUAL 38) + target_link_libraries(core PUBLIC d3d11 python38 freetype) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "C:/Python38-x64" + "C:/Python38-x64/include" + ) + + target_link_directories(core + PRIVATE + "C:/Python38-x64" + "C:/Python38-x64/libs" + "C:/Python38-x64/DLLs" + ) + +elseif(MVPY_VERSION EQUAL 39) + target_link_libraries(core PUBLIC d3d11 python39 freetype) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + "C:/Python39-x64" + "C:/Python39-x64/include" + ) + + target_link_directories(core + PRIVATE + "C:/Python39-x64" + "C:/Python39-x64/libs" + "C:/Python39-x64/DLLs" + ) + +elseif(MVPY_VERSION EQUAL 0) + target_link_directories(core PRIVATE "../Dependencies/cpython/PCbuild/amd64/") + target_link_libraries(core PUBLIC d3d11 python39 freetype) + + target_include_directories(core + PRIVATE + ${MARVEL_INCLUDE_DIR} + ) + +endif() \ No newline at end of file diff --git a/DearPyGui/dearpygui/core.py b/DearPyGui/dearpygui/core.py new file mode 100644 index 000000000..5d202400f --- /dev/null +++ b/DearPyGui/dearpygui/core.py @@ -0,0 +1 @@ +from core import * \ No newline at end of file diff --git a/DearPyGui/dearpygui/core.pyi b/DearPyGui/dearpygui/core.pyi new file mode 100644 index 000000000..4dfc68170 --- /dev/null +++ b/DearPyGui/dearpygui/core.pyi @@ -0,0 +1,912 @@ +from typing import List, Any, Callable +from dearpygui.core import * + +########################################################## +# This file is generated automatically by mvPythonParser # +########################################################## + +# ~ Dear PyGui Version: master +def add_about_window(name: str = ..., *, width: int = -1, height: int = -1, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True) -> None: + """Creates an about window.""" + ... + +def add_area_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., fill: List[float] = (0, 0, 0, -1), label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_bar_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., weight: float = 1.0, horizontal: bool = False, label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_button(name: str = ..., *, small: bool = False, arrow: bool = False, direction: int = 0, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True, enabled: bool = True) -> None: + """Adds a button.""" + ... + +def add_candle_series(name: str = ..., *, dates: List[float] = ..., opens: List[float] = ..., closes: List[float] = ..., lows: List[float] = ..., highs: List[float] = ..., tooltip: bool = True, bull_color: List[float] = (0, 255, 113, 255), bear_color: List[float] = (218, 13, 79, 255), weight: float = 0.25, label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_checkbox(name: str = ..., *, default_value: int = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', label: str = '', show: bool = True, enabled: bool = True) -> None: + """Adds a checkbox widget.""" + ... + +def add_child(name: str = ..., *, show: bool = True, parent: str = '', before: str = '', width: int = 0, height: int = 0, border: bool = True, autosize_x: bool = False, autosize_y: bool = False, no_scrollbar: bool = False, horizontal_scrollbar: bool = False, menubar: bool = False) -> None: + """Adds an embedded child window. Will show scrollbars when items do not fit. Must be followed by a call to end.""" + ... + +def add_collapsing_header(name: str = ..., *, label: str = '', show: bool = True, parent: str = '', before: str = '', closable: bool = False, default_open: bool = False, open_on_double_click: bool = False, open_on_arrow: bool = False, leaf: bool = False, bullet: bool = False) -> None: + """Adds a collapsing header to add items to. Must be closed with the end command.""" + ... + +def add_color_button(name: str = ..., *, default_value: List[int] = (0, 0, 0, 255), callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', width: int = 0, height: int = 0, show: bool = True, no_alpha: bool = False, no_border: bool = False, no_drag_drop: bool = False, enabled: bool = True) -> None: + """Adds a color button.""" + ... + +def add_color_edit3(name: str = ..., *, default_value: List[int] = (0, 0, 0, 255), callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True, enabled: bool = True, no_alpha: bool = False, no_picker: bool = False, no_options: bool = False, no_small_preview: bool = False, no_inputs: bool = False, no_tooltip: bool = False, no_label: bool = False, no_drag_drop: bool = False, alpha_bar: bool = False, alpha_preview: bool = False, alpha_preview_half: bool = False, display_rgb: bool = False, display_hsv: bool = False, display_hex: bool = False, uint8: bool = False, floats: bool = False, input_rgb: bool = False, input_hsv: bool = False) -> None: + """Adds an rgb color editing widget. Click and draging the color square will copy the color to be applied on any other color widget.""" + ... + +def add_color_edit4(name: str = ..., *, default_value: List[int] = (0, 0, 0, 255), callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True, enabled: bool = True, no_alpha: bool = False, no_picker: bool = False, no_options: bool = False, no_small_preview: bool = False, no_inputs: bool = False, no_tooltip: bool = False, no_label: bool = False, no_drag_drop: bool = False, alpha_bar: bool = False, alpha_preview: bool = False, alpha_preview_half: bool = False, display_rgb: bool = False, display_hsv: bool = False, display_hex: bool = False, uint8: bool = False, floats: bool = False, input_rgb: bool = False, input_hsv: bool = False) -> None: + """Adds an rgba color editing widget. Click and draging the color square will copy the color to be applied on any other color widget.""" + ... + +def add_color_picker3(name: str = ..., *, default_value: List[int] = (0, 0, 0, 255), callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True, enabled: bool = True, no_alpha: bool = False, no_small_preview: bool = False, no_inputs: bool = False, no_tooltip: bool = False, no_label: bool = False, no_side_preview: bool = False, alpha_bar: bool = False, alpha_preview: bool = False, alpha_preview_half: bool = False, display_rgb: bool = False, display_hsv: bool = False, display_hex: bool = False, uint8: bool = False, floats: bool = False, picker_hue_bar: bool = False, picker_hue_wheel: bool = False, input_rgb: bool = False, input_hsv: bool = False) -> None: + """Adds an rgb color picking widget. Click and draging the color square will copy the color to be applied on any other color widget. Right Click allows the style of the color picker to be changed.""" + ... + +def add_color_picker4(name: str = ..., *, default_value: List[int] = (0, 0, 0, 255), callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True, enabled: bool = True, no_alpha: bool = False, no_small_preview: bool = False, no_inputs: bool = False, no_tooltip: bool = False, no_label: bool = False, no_side_preview: bool = False, alpha_bar: bool = False, alpha_preview: bool = False, alpha_preview_half: bool = False, display_rgb: bool = False, display_hsv: bool = False, display_hex: bool = False, uint8: bool = False, floats: bool = False, picker_hue_bar: bool = False, picker_hue_wheel: bool = False, input_rgb: bool = False, input_hsv: bool = False) -> None: + """Adds an rgba color picking widget. Click and draging the color square will copy the color to be applied on any other color widget. Right Click allows the style of the color picker to be changed""" + ... + +def add_colormap_scale(name: str = ..., *, default_value: int = 0, min_scale: float = 0.0, max_scale: float = 1.0, parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, label: str = '', show: bool = True) -> None: + """Adds drag for a single int value. CTRL+Click to directly modify the value.""" + ... + +def add_combo(name: str = ..., *, items: List[str] = (), default_value: str = '', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, label: str = '', show: bool = True, popup_align_left: bool = False, height_small: bool = False, height_regular: bool = False, height_large: bool = False, height_largest: bool = False, no_arrow_button: bool = False, no_preview: bool = False) -> None: + """Adds a combo.""" + ... + +def add_data_grid(name: str = ..., *, headers: List[str] = ..., callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', width: int = 0, height: int = 200, hide_headers: bool = False, show: bool = True) -> None: + """Adds data grid.""" + ... + +def add_date_picker(name: str = ..., *, default_value: dict = {'month_day': 14, 'year':20, 'month':5}, level: int = 0, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a data selector widget.""" + ... + +def add_debug_window(name: str = ..., *, width: int = 700, height: int = 500, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True) -> None: + """Creates a debug window.""" + ... + +def add_doc_window(name: str = ..., *, width: int = -1, height: int = -1, x_pos: int = 200, y_pos: int = 200, autosize: bool = True, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True) -> None: + """Creates a documentation window.""" + ... + +def add_drag_float(name: str = ..., *, default_value: float = 0.0, speed: float = 1.0, min_value: float = 0.0, max_value: float = 100.0, format: str = '%0.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds drag for a single float value. CTRL+Click to directly modify the value.""" + ... + +def add_drag_floatx(name: str = ..., *, default_value: List[float] = (0.0, 0.0, 0.0, 0.0), size: int = 4, speed: float = 1.0, min_value: float = 0.0, max_value: float = 100.0, format: str = '%0.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds drag for multiple float values. CTRL+Click to directly modify the value.""" + ... + +def add_drag_int(name: str = ..., *, default_value: int = 0, speed: float = 1.0, min_value: int = 0, max_value: int = 100, format: str = '%d', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds drag for a single int value. CTRL+Click to directly modify the value.""" + ... + +def add_drag_intx(name: str = ..., *, default_value: List[float] = (0, 0, 0, 0), size: int = 4, speed: float = 1.0, min_value: int = 0, max_value: int = 100, format: str = '%0.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds drag for multiple int values. CTRL+Click to directly modify the value.""" + ... + +def add_drag_line(name: str = ..., *, default_value: List[float] = (0.0, 0.0, 0.0, 0.0), label: str = '', source: str = '', color: List[float] = (0, 0, 0, -1), thickness: float = 1.0, show_label: bool = True, vertical: bool = True, callback: Callable = None, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_drag_point(name: str = ..., *, default_value: List[float] = (0.0, 0.0, 0.0, 0.0), label: str = '', source: str = '', color: List[float] = (0, 0, 0, -1), radius: float = 4.0, show_label: bool = True, callback: Callable = None, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_drawing(name: str = ..., *, parent: str = '', before: str = '', width: int = 0, height: int = 0, show: bool = True) -> None: + """Adds a drawing widget.""" + ... + +def add_dummy(name: str = 'dummy', *, width: int = 0, height: int = 0, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a spacer or 'dummy' object.""" + ... + +def add_error_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., negative: List[float] = ..., positive: List[float] = ..., horizontal: bool = False, label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_font(font: str, file: str, size: float = 13.0, glyph_ranges: str = '', *, custom_glyph_chars: List[int] = (), custom_glyph_ranges: Any = List[List[int]], char_remaps: Any = List[List[int]]) -> None: + """Adds additional font.""" + ... + +def add_grid_column(data_grid: str, name: str, column: List[str]) -> None: + """Adds a column to the end of a data grid.""" + ... + +def add_grid_row(data_grid: str, row: List[str]) -> None: + """Adds a row to the end of a data grid.""" + ... + +def add_group(name: str = ..., *, show: bool = True, parent: str = '', before: str = '', width: int = 0, horizontal: bool = False, horizontal_spacing: float = -1) -> None: + """Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. Must be closed with the end command.""" + ... + +def add_heat_series(name: str = ..., *, x: List[float] = ..., rows: int = 1, cols: int = 1, scale_min: float = 0.0, scale_max: float = 1.0, format: str = '%0.1f', bounds_min: List[float] = (0.0, 0.0), bounds_max: List[float] = (1.0, 1.0), label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_hline_series(name: str = ..., *, x: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_image(name: str = ..., *, value: str = ..., tint_color: List[float] = (255, 255, 255, 255), border_color: List[float] = (0, 0, 0, 0), parent: str = '', before: str = '', source: str = '', width: int = 0, height: int = 0, uv_min: List[float] = (0.0, 0.0), uv_max: List[float] = (1.0, 1.0), show: bool = True) -> None: + """Adds an image.uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown.Using(0,0)->(1,1) texture coordinates will generally display the entire texture""" + ... + +def add_image_button(name: str = ..., *, value: str = ..., callback: Callable = None, callback_data: Any = None, tint_color: List[float] = (255, 255, 255, 255), background_color: List[float] = (0, 0, 0, 0), parent: str = '', before: str = '', width: int = 0, height: int = 0, frame_padding: int = -1, uv_min: List[float] = (0.0, 0.0), uv_max: List[float] = (1.0, 1.0), show: bool = True, enabled: bool = True) -> None: + """Adds an image button.uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown.Using(0,0)->(1,1) texture coordinates will generally display the entire texture""" + ... + +def add_image_series(name: str = ..., *, value: str = ..., bounds_min: List[float] = ..., bounds_max: List[float] = ..., uv_min: List[float] = (0.0, 0.0), uv_max: List[float] = (1.0, 1.0), tint_color: List[int] = (255, 255, 255, 255), label: str = '', parent: str = '', before: str = '', show: bool = True, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_indent(name: str = 'indent', *, offset: float = 0.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds an indent to following items. Must be closed with the unindent command.""" + ... + +def add_input_float(name: str = ..., *, default_value: float = 0.0, min_value: float = 0, max_value: float = 100, min_clamped: bool = False, max_clamped: bool = False, format: str = '%.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, on_enter: bool = False, label: str = '', show: bool = True, step: float = 0.1, step_fast: float = 1.0, readonly: bool = False) -> None: + """Adds input for float values.""" + ... + +def add_input_floatx(name: str = ..., *, default_value: List[float] = (0.0, 0.0, 0.0, 0.0), size: int = 4, min_value: float = 0, max_value: float = 100, min_clamped: bool = False, max_clamped: bool = False, format: str = '%.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, on_enter: bool = False, label: str = '', show: bool = True, readonly: bool = False) -> None: + """Adds input for 4 float values.""" + ... + +def add_input_int(name: str = ..., *, default_value: int = 0, min_value: int = 0, max_value: int = 100, min_clamped: bool = False, max_clamped: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, on_enter: bool = False, label: str = '', show: bool = True, step: int = 1, step_fast: int = 100, readonly: bool = False) -> None: + """Adds input for integer values.""" + ... + +def add_input_intx(name: str = ..., *, default_value: List[int] = (0, 0, 0, 0), size: int = 4, min_value: int = 0, max_value: int = 100, min_clamped: bool = False, max_clamped: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, on_enter: bool = False, label: str = '', show: bool = True, readonly: bool = False) -> None: + """Adds input for 4 integer values.""" + ... + +def add_input_text(name: str = ..., *, default_value: str = '', hint: str = '', multiline: bool = False, no_spaces: bool = False, uppercase: bool = False, tab_input: bool = False, decimal: bool = False, hexadecimal: bool = False, readonly: bool = False, password: bool = False, scientific: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, height: int = 0, on_enter: bool = False, label: str = '', show: bool = True) -> None: + """Adds input for text values.""" + ... + +def add_label_text(name: str = ..., *, default_value: str = '', color: List[float] = (-1, 0, 0, 0), parent: str = '', before: str = '', source: str = '', label: str = '', show: bool = True) -> None: + """Adds text with a label. Useful for output values.""" + ... + +def add_line_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_listbox(name: str = ..., *, items: List[str] = (), default_value: int = 0, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, num_items: int = 3, label: str = '', show: bool = True) -> None: + """Adds a listbox.""" + ... + +def add_logger(name: str = ..., *, log_level: int = 1, auto_scroll: bool = True, auto_scroll_button: bool = True, clear_button: bool = True, copy_button: bool = True, filter: bool = True, width: int = 0, height: int = 0, parent: str = '', before: str = '', show: bool = True, autosize_x: bool = False, autosize_y: bool = False) -> None: + """Adds a logging widget.""" + ... + +def add_menu(name: str = ..., *, label: str = '', show: bool = True, parent: str = '', before: str = '', enabled: bool = True) -> None: + """Adds a menu to an existing menu bar. Must be followed by a call to end.""" + ... + +def add_menu_bar(name: str = ..., *, show: bool = True, parent: str = '', before: str = '') -> None: + """Adds a menu bar to a window. Must be followed by a call to end.""" + ... + +def add_menu_item(name: str = ..., *, default_value: int = False, shortcut: str = '', check: bool = False, callback: Callable = None, callback_data: Any = None, source: str = '', label: str = '', show: bool = True, enabled: bool = True, parent: str = '', before: str = '') -> None: + """Adds a menu item to an existing menu.""" + ... + +def add_metrics_window(name: str = ..., *, width: int = 700, height: int = 500, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True) -> None: + """Creates a metrics window.""" + ... + +def add_node(name: str = ..., *, show: bool = True, label: str = '', draggable: bool = True, parent: str = '', before: str = '', x_pos: int = 100, y_pos: int = 100) -> None: + """Adds a node to a node editor.""" + ... + +def add_node_attribute(name: str = ..., *, shape: int = 1, output: bool = False, static: bool = False, show: bool = True, parent: str = '', before: str = '') -> None: + """Adds a node attribute.""" + ... + +def add_node_editor(name: str = ..., *, show: bool = True, parent: str = '', before: str = '', link_callback: Callable = None, delink_callback: Callable = None) -> None: + """Adds a node editor.""" + ... + +def add_node_link(node_editor: str, node_1: str, node_2: str) -> None: + """Adds a node link between nodes.""" + ... + +def add_pie_series(name: str = ..., *, values: List[float] = ..., labels: List[str] = ..., x: float = ..., y: float = ..., radius: float = ..., normalize: bool = False, angle: float = 90.0, format: str = '%0.2f', label: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0) -> None: + """Adds a drag point to a plot.""" + ... + +def add_plot_annotation(name: str = ..., *, default_value: List[float] = (0.0, 0.0), offset: List[float] = (0.0, 0.0), label: str = '', source: str = '', color: List[float] = (0, 0, 0, -1), clamped: bool = True, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_plot_stack(name: str = ..., *, x_axis_name: str = '', y_axis_name: str = '', no_legend: bool = False, no_menus: bool = False, no_box_select: bool = False, no_mouse_pos: bool = False, no_highlight: bool = False, no_child: bool = False, query: bool = False, crosshairs: bool = False, anti_aliased: bool = False, equal_aspects: bool = False, yaxis2: bool = False, yaxis3: bool = False, xaxis_no_gridlines: bool = False, xaxis_no_tick_marks: bool = False, xaxis_no_tick_labels: bool = False, xaxis_log_scale: bool = False, xaxis_time: bool = False, xaxis_invert: bool = False, xaxis_lock_min: bool = False, xaxis_lock_max: bool = False, yaxis_no_gridlines: bool = False, yaxis_no_tick_marks: bool = False, yaxis_no_tick_labels: bool = False, yaxis_log_scale: bool = False, yaxis_invert: bool = False, yaxis_lock_min: bool = False, yaxis_lock_max: bool = False, y2axis_no_gridlines: bool = False, y2axis_no_tick_marks: bool = False, y2axis_no_tick_labels: bool = False, y2axis_log_scale: bool = False, y2axis_invert: bool = False, y2axis_lock_min: bool = False, y2axis_lock_max: bool = False, y3axis_no_gridlines: bool = False, y3axis_no_tick_marks: bool = False, y3axis_no_tick_labels: bool = False, y3axis_log_scale: bool = False, y3axis_invert: bool = False, y3axis_lock_min: bool = False, y3axis_lock_max: bool = False, parent: str = '', before: str = '', width: int = -1, height: int = -1, query_callback: Callable = None, label: str = '', show: bool = True) -> None: + """Adds a plot widget.""" + ... + +def add_popup(name: str = ..., *, mousebutton: int = 1, modal: bool = False, parent: str = '', before: str = '', width: int = 0, height: int = 0, show: bool = True) -> None: + """Adds a popup window for an item. This command must come immediately after the item the popup is for. Must be followed by a call to end.""" + ... + +def add_progress_bar(name: str = ..., *, default_value: float = 0.0, overlay: str = '', parent: str = '', before: str = '', source: str = '', label: str = '', width: int = 0, height: int = 0, show: bool = True) -> None: + """Adds a progress bar.""" + ... + +def add_radio_button(name: str = ..., *, items: List[str] = (), default_value: int = 0, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, horizontal: bool = False, show: bool = True) -> None: + """Adds a set of radio buttons. If items is empty, nothing will be shown.""" + ... + +def add_same_line(name: str = 'sameline', *, xoffset: float = 0.0, spacing: float = -1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Places a widget on the same line as the previous widget. Can also be used for horizontal spacing.""" + ... + +def add_scatter_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_selectable(name: str = ..., *, default_value: bool = False, callback: Callable = None, callback_data: Any = None, width: int = 0, height: int = 0, parent: str = '', before: str = '', source: str = '', enabled: bool = True, label: str = '', show: bool = True, span_columns: bool = False) -> None: + """Adds a selectable.""" + ... + +def add_separator(name: str = 'separator', *, parent: str = '', before: str = '') -> None: + """Adds a horizontal line.""" + ... + +def add_shade_series(name: str = ..., *, x: List[float] = ..., y1: List[float] = ..., y2: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_simple_plot(name: str = ..., *, value: List[float] = (), overlay: str = '', minscale: float = 0.0, maxscale: float = 0.0, histogram: bool = False, parent: str = '', before: str = '', width: int = 0, height: int = 0, source: str = '', label: str = '', show: bool = True) -> None: + """A simple plot for visualization of a set of values""" + ... + +def add_slider_float(name: str = ..., *, default_value: float = 0.0, min_value: float = 0.0, max_value: float = 100.0, format: str = '%.3f', vertical: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, height: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds slider for a single float value. CTRL+Click to directly modify the value.""" + ... + +def add_slider_floatx(name: str = ..., *, default_value: List[float] = (0.0, 0.0, 0.0, 0.0), size: int = 4, min_value: float = 0.0, max_value: float = 100.0, format: str = '%.3f', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds slider for a 4 float values. CTRL+Click to directly modify the value.""" + ... + +def add_slider_int(name: str = ..., *, default_value: int = 0, min_value: int = 0, max_value: int = 100, format: str = '%d', vertical: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, height: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds slider for a single int value. CTRL+Click to directly modify the value.""" + ... + +def add_slider_intx(name: str = ..., *, default_value: List[int] = (0, 0, 0, 0), size: int = 4, min_value: int = 0, max_value: int = 100, format: str = '%d', callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', source: str = '', enabled: bool = True, width: int = 0, no_input: bool = False, clamped: bool = False, label: str = '', show: bool = True) -> None: + """Adds slider for a 4 int values. CTRL+Click to directly modify the value.""" + ... + +def add_spacing(name: str = 'spacing', *, count: int = 1, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds vertical spacing.""" + ... + +def add_stair_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_stem_series(name: str = ..., *, x: List[float] = ..., y: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_style_window(name: str = ..., *, width: int = 700, height: int = 500, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True) -> None: + """Creates a style window.""" + ... + +def add_tab(name: str = ..., *, closable: bool = False, label: str = '', show: bool = True, no_reorder: bool = False, leading: bool = False, trailing: bool = False, no_tooltip: bool = False, parent: str = '', before: str = '') -> None: + """Adds a tab to a tab bar. Must be closed with the end command.""" + ... + +def add_tab_bar(name: str = ..., *, reorderable: bool = False, callback: Callable = None, callback_data: Any = None, show: bool = True, parent: str = '', before: str = '') -> None: + """Adds a tab bar.""" + ... + +def add_tab_button(name: str = ..., *, label: str = '', show: bool = True, no_reorder: bool = False, leading: bool = False, trailing: bool = False, no_tooltip: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '') -> None: + """Adds a tab button to a tab bar""" + ... + +def add_table(name: str = ..., *, header_row: bool = True, width: int = 0, height: int = 0, inner_width: int = 0, show: bool = True, parent: str = '', before: str = '', resizable: bool = False, reorderable: bool = False, hideable: bool = False, sortable: bool = False, context_menu_in_body: bool = False, row_background: bool = False, borders_innerH: bool = False, borders_outerH: bool = False, borders_innerV: bool = False, borders_outerV: bool = False, policy: int = 0, no_host_extendX: bool = False, no_host_extendY: bool = False, no_keep_columns_visible: bool = False, precise_widths: bool = False, no_clip: bool = False, pad_outerX: bool = False, no_pad_outerX: bool = False, no_pad_innerX: bool = False, scrollX: bool = False, scrollY: bool = False) -> None: + """Adds managed columns.""" + ... + +def add_table_column(name: str = ..., *, init_width_or_weight: float = 0.0, show: bool = True, parent: str = '', before: str = '', default_hide: bool = False, default_sort: bool = False, width_stretch: bool = False, width_fixed: bool = False, no_resize: bool = False, no_reorder: bool = False, no_hide: bool = False, no_clip: bool = False, no_sort: bool = False, no_sort_ascending: bool = False, no_sort_descending: bool = False, no_header_width: bool = False, prefer_sort_ascending: bool = False, prefer_sort_descending: bool = False, indent_enable: bool = False, indent_disable: bool = False) -> None: + """Changes to next column.""" + ... + +def add_table_next_column(name: str = 'next_column', *, show: bool = True, parent: str = '', before: str = '') -> None: + """Changes to next column.""" + ... + +def add_text(name: str = ..., *, wrap: int = -1, color: List[float] = (-1, 0, 0, 0), bullet: bool = False, parent: str = '', before: str = '', source: str = '', default_value: str = '', show: bool = True) -> None: + """Adds text""" + ... + +def add_text_point(name: str = ..., *, x: float = ..., y: float = ..., vertical: bool = False, x_offset: int = 0.0, y_offset: int = 0.0, label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_texture(name: str, data: List[int], width: int, height: int, *, format: int = 0) -> None: + """Adds a texture. Incorrect format may yield unexpected results.""" + ... + +def add_time_picker(name: str = ..., *, default_value: dict = {'hour': 14, 'min': 32, 'sec': 23}, hour24: bool = False, callback: Callable = None, callback_data: Any = None, parent: str = '', before: str = '', show: bool = True) -> None: + """Adds a time selector widget.""" + ... + +def add_tooltip(name: str = ..., *, parent: str = ..., before: str = '', show: bool = True) -> None: + """Adds an advanced tool tip for an item. This command must come immediately after the item the tip is for.""" + ... + +def add_tree_node(name: str = ..., *, label: str = '', show: bool = True, parent: str = '', before: str = '', default_open: bool = False, open_on_double_click: bool = False, open_on_arrow: bool = False, leaf: bool = False, bullet: bool = False) -> None: + """Adds a tree node to add items to. Must be closed with the end command.""" + ... + +def add_vline_series(name: str = ..., *, x: List[float] = ..., label: str = '', source: str = '', parent: str = '', before: str = '', show: bool = True, axis: int = 0, contribute_to_bounds: bool = True) -> None: + """Adds a drag point to a plot.""" + ... + +def add_window(name: str = ..., *, width: int = -1, height: int = -1, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, no_bring_to_front_on_focus: bool = False, menubar: bool = False, no_close: bool = False, no_background: bool = False, label: str = '', show: bool = True, collapsed: bool = False, on_close: Callable = None, min_size: List[int] = [32, 32], max_size: List[int] = [30000, 30000]) -> None: + """Creates a new window for following items to be added to.""" + ... + +def cleanup_dearpygui() -> None: + """Cleans up DearPyGui after calling setup_dearpygui.""" + ... + +def clear_data_grid(data_grid: str) -> None: + """Clears data in a data grid""" + ... + +def clear_log(*, logger: str = '') -> None: + """Clears the logger.""" + ... + +def clear_selected_links(node_editor: str) -> None: + """Clears selected links.""" + ... + +def clear_selected_nodes(node_editor: str) -> None: + """Clears selected nodes.""" + ... + +def close_popup(item: str) -> None: + """Closes a popup.""" + ... + +def configure_item(item: str, **Kwargs) -> None: + """Configures an item""" + ... + +def configure_viewport(**Kwargs) -> None: + """Shows viewport""" + ... + +def create_viewport(*, title: str = ..., width: int = ..., height: int = ..., x_pos: int = ..., y_pos: int = ..., resizable: bool = ..., vsync: bool = ..., always_on_top: bool = ..., maximized_box: bool = ..., minimized_box: bool = ..., border: bool = ..., caption: bool = ..., overlapped: bool = ..., min_width: int = ..., max_width: int = ..., min_height: int = ..., max_height: int = ...) -> None: + """Creates a viewport""" + ... + +def decrement_texture(name: str) -> None: + """Decrements a texture.""" + ... + +def delete_grid_column(data_grid: str, column: int) -> None: + """Delete a column in a data grid.""" + ... + +def delete_grid_row(data_grid: str, row: int) -> None: + """Delete a row in a data grid.""" + ... + +def delete_item(item: str, *, children_only: bool = False) -> None: + """Deletes an item if it exists.""" + ... + +def delete_node_link(node_editor: str, node_1: str, node_2: str) -> None: + """Deletes a node link if it exist.""" + ... + +def does_item_exist(item: str) -> bool: + """Checks if item exists.""" + ... + +def draw_arrow(name: str = '', *, p1: List[float] = ..., p2: List[float] = ..., color: List[int] = ..., thickness: int = ..., size: int = ..., parent: str = '', before: str = '', show: bool = True) -> None: + """Draws an arrow on a drawing.""" + ... + +def draw_bezier_curve(name: str = '', *, p1: List[float] = ..., p2: List[float] = ..., p3: List[float] = ..., p4: List[float] = ..., color: List[int] = ..., thickness: float = 1.0, segments: int = 0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a bezier curve on a drawing.""" + ... + +def draw_circle(name: str = '', *, center: List[float] = ..., radius: float = ..., color: List[int] = ..., segments: int = 0, thickness: float = 1.0, fill: List[float] = (0, 0, 0, -1), parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a circle on a drawing.""" + ... + +def draw_image(name: str = '', *, file: str = ..., pmin: List[float] = ..., pmax: List[float] = ..., uv_min: List[float] = (0.0, 0.0), uv_max: List[float] = (1.0, 1.0), color: List[int] = (255, 255, 255, 255), parent: str = '', before: str = '', show: bool = True) -> None: + """Draws an image on a drawing. p_min (bottom-left) and p_max (upper-right) represent corners of the rectangle the image will be drawn to.Setting the p_min equal to the p_max will sraw the image to with 1:1 scale.uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using (0,0)->(1,1) texturecoordinates will generally display the entire texture.""" + ... + +def draw_line(name: str = '', *, p1: List[float] = ..., p2: List[float] = ..., color: List[int] = ..., thickness: int = ..., parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a line on a drawing.""" + ... + +def draw_polygon(name: str = '', *, points: List[List[float]] = ..., color: List[int] = ..., fill: List[float] = (0, 0, 0, -1), thickness: float = 1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a polygon on a drawing.""" + ... + +def draw_polyline(name: str = '', *, points: List[List[float]] = ..., color: List[int] = ..., closed: bool = False, thickness: float = 1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws lines on a drawing.""" + ... + +def draw_quad(name: str = '', *, p1: List[float] = ..., p2: List[float] = ..., p3: List[float] = ..., p4: List[float] = ..., color: List[int] = ..., fill: List[float] = (0, 0, 0, -1), thickness: float = 1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a quad on a drawing.""" + ... + +def draw_rectangle(name: str = '', *, pmin: List[float] = ..., pmax: List[float] = ..., color: List[int] = ..., fill: List[float] = (0, 0, 0, -1), rounding: float = 0.0, thickness: float = 1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a line on a drawing.""" + ... + +def draw_text(name: str = '', *, pos: List[float] = ..., text: str = ..., color: List[int] = (0, 0, 0, -1), size: int = 10, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws text on a drawing.""" + ... + +def draw_triangle(name: str = '', *, p1: List[float] = ..., p2: List[float] = ..., p3: List[float] = ..., color: List[int] = ..., fill: List[float] = (0, 0, 0, -1), thickness: float = 1.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Draws a triangle on a drawing.""" + ... + +def enable_docking(*, shift_only: bool = True, dock_space: bool = False) -> None: + """Decrements a texture.""" + ... + +def end() -> None: + """Ends a container.""" + ... + +def get_active_window() -> str: + """Returns the active window name.""" + ... + +def get_all_items() -> List[str]: + """Returns a list of all items.""" + ... + +def get_dearpygui_version() -> str: + """Returns the current version of Dear PyGui.""" + ... + +def get_delta_time() -> float: + """Returns time since last frame.""" + ... + +def get_drawing_mouse_pos() -> (int, int): + """Returns the current mouse position in the currently hovered drawing.""" + ... + +def get_global_font_scale() -> float: + """Returns the global font scale.""" + ... + +def get_grid_data(data_grid: str) -> List[List[str]]: + """Gets data grid data.""" + ... + +def get_grid_item(data_grid: str, row: int, column: int) -> str: + """Gets a data grid's cell value.""" + ... + +def get_grid_selections(data_grid: str) -> List[List[int]]: + """Retrieves data from storage.""" + ... + +def get_item_callback(item: str) -> Callable: + """Returns an item' callback""" + ... + +def get_item_callback_data(item: str) -> Any: + """Returns an item' callback data""" + ... + +def get_item_children[1](item: str) -> List[str]: + """Returns a list of an item's children.""" + ... + +def get_item_configuration(item: str) -> dict: + """Returns an items configuration""" + ... + +def get_item_parent(item: str) -> str: + """Returns an item's parent.""" + ... + +def get_item_rect_max(item: str) -> [float, float]: + """Returns an item's maximum allowable size. [width, height]""" + ... + +def get_item_rect_min(item: str) -> [float, float]: + """Returns an item's minimum allowable size. [width, height]""" + ... + +def get_item_rect_size(item: str) -> [float, float]: + """Returns an item's current size. [width, height]""" + ... + +def get_item_type(item: str) -> str: + """Returns an item's type""" + ... + +def get_links(node_editor: str) -> List[List[str]]: + """Returns all links. """ + ... + +def get_log_level(*, logger: str = '') -> int: + """Returns the log level.""" + ... + +def get_mouse_drag_delta() -> (float, float): + """Returns the current mouse drag delta in pixels""" + ... + +def get_mouse_pos(*, local: bool = True) -> (int, int): + """Returns the current mouse position in relation to the active window (minus titlebar) unless local flag is unset.""" + ... + +def get_plot_mouse_pos() -> (int, int): + """Returns the current mouse position in the currently hovered plot.""" + ... + +def get_plot_query_area(plot: str) -> List[float]: + """Returns the bounding axis limits for the query area [x_min, x_max, y_min, y_max]""" + ... + +def get_plot_xlimits(plot: str) -> List[float]: + """Returns the plots x limits""" + ... + +def get_plot_ylimits(plot: str) -> List[float]: + """Returns the plots x limits""" + ... + +def get_selected_links(node_editor: str) -> List[List[str]]: + """Returns selected links.""" + ... + +def get_selected_nodes(node_editor: str) -> List[str]: + """Returns selected nodes.""" + ... + +def get_total_time() -> float: + """Returns total time since app started.""" + ... + +def get_value(name: str) -> Any: + """Returns an item's value or None if there is none.""" + ... + +def get_windows() -> List[str]: + """Returns a list of windows.""" + ... + +def insert_grid_column(data_grid: str, column_index: int, name: str, column: List[str]) -> None: + """Inserts a column into a data grid.""" + ... + +def insert_grid_row(data_grid: str, row_index: int, row: List[str]) -> None: + """Inserts a row into a data grid.""" + ... + +def is_dearpygui_running() -> bool: + """Checks if dearpygui is still running""" + ... + +def is_item_activated(item: str) -> bool: + """Checks if an item has been activated.""" + ... + +def is_item_active(item: str) -> bool: + """Checks if an item is active.""" + ... + +def is_item_clicked(item: str) -> bool: + """Checks if an item is clicked.""" + ... + +def is_item_container(item: str) -> bool: + """Checks if an item is container.""" + ... + +def is_item_deactivated(item: str) -> bool: + """Checks if an item has been deactivated.""" + ... + +def is_item_deactivated_after_edit(item: str) -> bool: + """Checks if an item has been deactivated after editing.""" + ... + +def is_item_edited(item: str) -> bool: + """Checks if an item has been edited.""" + ... + +def is_item_focused(item: str) -> bool: + """Checks if an item is focused.""" + ... + +def is_item_hovered(item: str) -> bool: + """Checks if an item is hovered.""" + ... + +def is_item_shown(item: str) -> bool: + """Checks if an item is shown.""" + ... + +def is_item_toggled_open(item: str) -> bool: + """Checks if an item is toggled.""" + ... + +def is_item_visible(item: str) -> bool: + """Checks if an item is visible on screen.""" + ... + +def is_key_down(key: int) -> bool: + """Checks if the key is down.""" + ... + +def is_key_pressed(key: int) -> bool: + """Checks if the key is pressed.""" + ... + +def is_key_released(key: int) -> bool: + """Checks if the key is released.""" + ... + +def is_mouse_button_clicked(button: int) -> bool: + """Checks if the mouse button is clicked.""" + ... + +def is_mouse_button_double_clicked(button: int) -> bool: + """Checks if the mouse button is double clicked.""" + ... + +def is_mouse_button_down(button: int) -> bool: + """Checks if the mouse button is pressed.""" + ... + +def is_mouse_button_dragging(button: int, threshold: float) -> bool: + """Checks if the mouse is dragging.""" + ... + +def is_mouse_button_released(button: int) -> bool: + """Checks if the mouse button is released.""" + ... + +def is_plot_queried(plot: str) -> bool: + """Returns true if plot was queried""" + ... + +def log(message: Any, *, level: str = 'TRACE', logger: str = '') -> None: + """Logs a trace level log.""" + ... + +def log_debug(message: Any, *, logger: str = '') -> None: + """Logs a debug level log.""" + ... + +def log_error(message: Any, *, logger: str = '') -> None: + """Logs a error level log.""" + ... + +def log_info(message: Any, *, logger: str = '') -> None: + """Logs a info level log.""" + ... + +def log_warning(message: Any, *, logger: str = '') -> None: + """Logs a warning level log.""" + ... + +def maximize_viewport() -> None: + """Maximizes viewport""" + ... + +def minimize_viewport() -> None: + """Minimizes viewport""" + ... + +def move_item(item: str, *, parent: str = '', before: str = '') -> None: + """Moves an existing item.""" + ... + +def move_item_down(item: str) -> None: + """Moves item down if possible and if it exists.""" + ... + +def move_item_up(item: str) -> None: + """Moves item up if possible and if it exists.""" + ... + +def open_file_dialog(callback: Callable = None, extensions: str = '') -> None: + """Opens an 'open file' dialog.""" + ... + +def render_dearpygui_frame() -> None: + """Renders a DearPyGui frame. Should be called within a user's event loop. Must first call setup_dearpygui outside of event loop.""" + ... + +def reset_xticks(plot: str) -> None: + """Sets plots x ticks and labels back to automatic""" + ... + +def reset_yticks(plot: str) -> None: + """Sets plots y ticks and labels back to automatic""" + ... + +def set_accelerator_callback(callback: Any) -> None: + """Callback similar to keypress but used for accelerator keys.""" + ... + +def set_exit_callback(callback: Any) -> None: + """Callback to run when exiting main window.""" + ... + +def set_font(font: str, size: int, *, item: str = '') -> None: + """Adds additional font.""" + ... + +def set_global_font_scale(scale: float) -> None: + """Changes the global font scale.""" + ... + +def set_grid_data(data_grid: str, data: List[List[str]]) -> None: + """Overwrites data grid data.""" + ... + +def set_grid_headers(data_grid: str, headers: List[str]) -> None: + """Sets a data grid's headers.""" + ... + +def set_grid_item(data_grid: str, row: int, column: int, value: str) -> None: + """Sets a data grid's cell value.""" + ... + +def set_grid_selection(data_grid: str, row: int, column: int, value: bool) -> None: + """Sets a data grid's cell selection value.""" + ... + +def set_item_callback(item: str, callback: Callable, *, callback_data: Any = None) -> None: + """Sets an item's callback if applicable.""" + ... + +def set_item_callback_data(item: str, callback_data: Any) -> None: + """Sets an item's callback data if applicable.""" + ... + +def set_key_down_callback(callback: Callable) -> None: + """Sets a callback for a key down event.""" + ... + +def set_key_press_callback(callback: Callable) -> None: + """Sets a callback for a key press event.""" + ... + +def set_key_release_callback(callback: Callable) -> None: + """Sets a callback for a key release event.""" + ... + +def set_log_level(level: int, *, logger: str = '') -> None: + """Sets the log level.""" + ... + +def set_logger_window_title(title: str) -> None: + """Sets the title of the logger window.""" + ... + +def set_mouse_click_callback(callback: Callable) -> None: + """Sets a callback for a mouse click event.""" + ... + +def set_mouse_double_click_callback(callback: Callable) -> None: + """Sets a callback for a mouse double click event.""" + ... + +def set_mouse_down_callback(callback: Callable) -> None: + """Sets a callback for a mouse down event.""" + ... + +def set_mouse_drag_callback(callback: Callable, threshold: float) -> None: + """Sets a callback for a mouse drag event.""" + ... + +def set_mouse_move_callback(callback: Callable) -> None: + """Sets a callback for a mouse move event. Data is the mouse position in local coordinates.""" + ... + +def set_mouse_release_callback(callback: Callable) -> None: + """Sets a callback for a mouse release event.""" + ... + +def set_mouse_wheel_callback(callback: Callable) -> None: + """Sets a callback for a mouse wheel event.""" + ... + +def set_plot_xlimits(plot: str, xmin: float, xmax: float) -> None: + """Sets x axis limits of a plot. (can be undone with set_plot_xlimits_auto()""" + ... + +def set_plot_xlimits_auto(plot: str) -> None: + """Sets plots x limits to be automatic.""" + ... + +def set_plot_ylimits(plot: str, ymin: float, ymax: float) -> None: + """Sets y axis limits of a plot. (can be undone with set_plot_ylimits_auto()""" + ... + +def set_plot_ylimits_auto(plot: str) -> None: + """Sets plots y limits to be automatic.""" + ... + +def set_primary_window(window: str, value: bool) -> None: + """Sets the primary window to fill the viewport.""" + ... + +def set_resize_callback(callback: Callable, *, handler: str = '') -> None: + """Sets a callback for a window resize event.""" + ... + +def set_start_callback(callback: Any) -> None: + """Callback to run when starting main window.""" + ... + +def set_theme_color(constant: int, color: List[float], item: str = '') -> None: + """Sets a color of a theme item for when the item is enabled.""" + ... + +def set_theme_color_disabled(constant: int, color: List[float], item: str = '') -> None: + """Sets a color of a theme item for when the item is disabled.""" + ... + +def set_theme_style(constant: int, style: float, item: str = '') -> None: + """Sets a style of a theme item.""" + ... + +def set_value(name: str, value: Any) -> bool: + """Sets an item's value if applicable.""" + ... + +def set_xticks(plot: str, label_pairs: Any) -> None: + """Sets plots x ticks and labels""" + ... + +def set_yticks(plot: str, label_pairs: Any) -> None: + """Sets plots y ticks and labels""" + ... + +def setup_dearpygui() -> None: + """Sets up DearPyGui for user controlled rendering. Only call once and you must call cleanup_deapygui when finished.""" + ... + +def show_logger() -> None: + """Shows the logging window. The Default log level is Trace""" + ... + +def show_viewport(*, minimized: bool = ..., maximized: bool = ...) -> None: + """Shows viewport""" + ... + +def stop_dearpygui() -> None: + """Stops DearPyGui.""" + ... + +def unindent(name: str = 'unindent', *, offset: float = 0.0, parent: str = '', before: str = '', show: bool = True) -> None: + """Unindents following items.""" + ... + diff --git a/DearPyGui/dearpygui/demo.py b/DearPyGui/dearpygui/demo.py new file mode 100644 index 000000000..1361b6bd9 --- /dev/null +++ b/DearPyGui/dearpygui/demo.py @@ -0,0 +1,966 @@ +from dearpygui.core import * +from dearpygui.simple import * +from math import sin, cos +import random + +######################################################################################################################## +# Helpers +######################################################################################################################## + +def demo_help(message): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + Creates a hoverable question marker on the same line as the last created item. The message will be displayed as a popup. + + Args: + message: text that will be displayed in the popup when the "(?)" is hovered. + + Returns: + None""" + add_same_line() + parent = add_text(color=[150, 150, 150], default_value="(?)") + add_tooltip(parent=parent) + add_text(default_value=message) + end() + +def demo_hsv_to_rgb(h: float, s: float, v: float) -> (float, float, float): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + converts hsv to rgb + + Args: + h: hue. + s: saturation + v: value + + Returns: + rgb as a tuple of floats + """ + if s == 0.0: return (v, v, v) + i = int(h*6.) # XXX assume int() truncates! + f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6 + if i == 0: return (255*v, 255*t, 255*p) + if i == 1: return (255*q, 255*v, 255*p) + if i == 2: return (255*p, 255*v, 255*t) + if i == 3: return (255*p, 255*q, 255*v) + if i == 4: return (255*t, 255*p, 255*v) + if i == 5: return (255*v, 255*p, 255*q) + +def demo_recursive_disable(sender, siblings, restart_index=0): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + This command will toggle enable/disable for any eligible children of the parent container recursively down the widget tree. + Args: + sender: is the widgets name that called the command. + siblings: children in the same container that this checkbox is in. + **restart_index: sets the position of the next item to check so the same item isnt checked multiple times. + + Returns: + None""" + for i in range(restart_index,len(siblings)-1, 1): + if is_item_container(siblings[i]): + siblings += get_item_children(siblings.pop(i)) + demo_recursive_disable(sender, siblings, i-1) + return + siblings.remove(sender) + for item in siblings: + for key,value in get_item_configuration(item).items(): + if key == 'enabled': + configure_item(item, enabled = not value) + +def demo_enable_disable(): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + Creates a checkbox that will toggle enable/disable for any eligible children of the parent container recursively down the widget tree. + Args: + None + + Returns: + None""" + add_checkbox(label="Enable/Disable", default_value=True, callback=lambda sender: demo_recursive_disable(sender, get_item_children(get_item_parent(sender)))) + demo_help('This will toggle the keyword "enable" for any sibling widgets that allow enabled & disabled') + +def demo_config(sender, data): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + Applies configuration of the data in callback_data. + + Args: + sender: is the widgets name that called the command. + data: data that is populated by callback_data. Item as string or items as list that the configuration will be applied to. + + Returns: + None + """ + widget_type = get_item_type(sender) + log_debug(widget_type) + items = data + value = get_value(sender) + + if widget_type == "mvAppItemType::mvCheckbox": + keyword = get_item_configuration(sender)["label"] + log_debug(keyword) + + elif widget_type == "mvAppItemType::mvRadioButton": + keyword = get_item_configuration(sender)["items"][value] + + + if isinstance(data, list): + for item in items: + configure_item(item, **{keyword: value}) + else: + configure_item(item, **{keyword: value}) + +def demo_log(sender): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + + Logs the name and value of the widget that called the command. + + Args: + sender: widgets name that called the command. + that will get configured. The second item in the tuple is the keyword that will be set. + + Returns: + None + """ + log_debug(f"{sender} ran a callback its value is {get_value(sender)}") + +def demo_main_callback(): + """[INTERNAL DPG DEMO COMMAND]: This is a helper function that is intended to make the demo easier to read. not suggested for external use. + If this command is appearing in your code consider importing demo as demo to prevent namespace polution. + """ + set_value("Mouse Position##demo", str(get_mouse_pos())) + set_value("Drawing Mouse Position##demo", str(get_drawing_mouse_pos())) + set_value("Plot Mouse Position##demo", str(get_plot_mouse_pos())) + + # keys + if is_key_down(mvKey_A): + set_value("A key Down##demo", "True") + else: + set_value("A key Down##demo", "False") + + if is_key_pressed(mvKey_W): + set_value("W key Pressed##demo", "True") + else: + set_value("W key Pressed##demo", "False") + + if is_key_released(mvKey_Q): + set_value("Q key Released##demo", "True") + else: + set_value("Q key Released##demo", "False") + + # mouse dragging + if is_mouse_button_dragging(mvMouseButton_Left, 1): + set_value("Left Mouse Dragging##demo", "True") + else: + set_value("Left Mouse Dragging##demo", "False") + + if is_mouse_button_dragging(mvMouseButton_Right, 1): + set_value("Right Mouse Dragging##demo", "True") + else: + set_value("Right Mouse Dragging##demo", "False") + + if is_mouse_button_dragging(mvMouseButton_Middle, 1): + set_value("Middle Mouse Dragging##demo", "True") + else: + set_value("Middle Mouse Dragging##demo", "False") + + # mouse down + if is_mouse_button_down(mvMouseButton_Left): + set_value("Left Mouse Down##demo", "True") + else: + set_value("Left Mouse Down##demo", "False") + + if is_mouse_button_down(mvMouseButton_Right): + set_value("Right Mouse Down##demo", "True") + else: + set_value("Right Mouse Down##demo", "False") + + if is_mouse_button_down(mvMouseButton_Middle): + set_value("Middle Mouse Down##demo", "True") + else: + set_value("Middle Mouse Down##demo", "False") + + # mouse clicked + if is_mouse_button_clicked(mvMouseButton_Left): + set_value("Left Mouse Clicked##demo", "True") + else: + set_value("Left Mouse Clicked##demo", "False") + + if is_mouse_button_clicked(mvMouseButton_Right): + set_value("Right Mouse Clicked##demo", "True") + else: + set_value("Right Mouse Clicked##demo", "False") + + if is_mouse_button_clicked(mvMouseButton_Middle): + set_value("Middle Mouse Clicked##demo", "True") + else: + set_value("Middle Mouse Clicked##demo", "False") + + # mouse double clicked + if is_mouse_button_double_clicked(mvMouseButton_Left): + set_value("Left Mouse Double Clicked##demo", "True") + else: + set_value("Left Mouse Double Clicked##demo", "False") + + if is_mouse_button_double_clicked(mvMouseButton_Right): + set_value("Right Mouse Double Clicked##demo", "True") + else: + set_value("Right Mouse Double Clicked##demo", "False") + + if is_mouse_button_double_clicked(mvMouseButton_Middle): + set_value("Middle Mouse Double Clicked##demo", "True") + else: + set_value("Middle Mouse Double Clicked##demo", "False") + + # mouse released + if is_mouse_button_released(mvMouseButton_Left): + set_value("Left Mouse Released##demo", "True") + else: + set_value("Left Mouse Released##demo", "False") + + if is_mouse_button_released(mvMouseButton_Right): + set_value("Right Mouse Released##demo", "True") + else: + set_value("Right Mouse Released##demo", "False") + + if is_mouse_button_released(mvMouseButton_Middle): + set_value("Middle Mouse Released##demo", "True") + else: + set_value("Middle Mouse Released##demo", "False") + +def demo_accelerator_callback(sender, data): + + mapping = { + "P": mvKey_P, + "Y": mvKey_Y, + "T": mvKey_T, + "SHIFT": mvKey_Shift, + "CTRL": mvKey_Control, + } + + def are_all_true(shortcut): + keys = shortcut.split("+") + for item in keys: + if not is_key_down(mapping[item.upper()]): + return False + return True + + items = get_all_items() + for item in items: + # print(get_item_type(item)) + if get_item_type(item) == "mvAppItemType::MenuItem": + shortcut = get_item_configuration(item)["shortcut"] + if shortcut != None and shortcut != "": + if are_all_true(shortcut): + get_item_callback(item)(item, None) + +def on_demo_close(sender, data): + + delete_item("Dear PyGui Demo") + if does_item_exist("Logging Widget On Window##demo"): + delete_item("Logging Widget On Window##demo") + set_mouse_down_callback(None) + set_mouse_drag_callback(None, 10) + set_mouse_move_callback(None) + set_mouse_double_click_callback(None) + set_mouse_click_callback(None) + set_mouse_release_callback(None) + set_mouse_wheel_callback(None) + set_key_down_callback(None) + set_key_press_callback(None) + set_key_release_callback(None) + set_accelerator_callback(None) + +def show_demo(): + + #set_accelerator_callback(demo_accelerator_callback) + + with window("Dear PyGui Demo", x_pos=100, y_pos=100, width=800, height=800, on_close=on_demo_close): + + with menu_bar(): + + with menu(label="Menu"): + add_menu_item(label="New") + add_menu_item(label="Open") + + with menu(label="Open Recent"): + add_menu_item(label="harrell.c") + add_menu_item(label="patty.h") + add_menu_item(label="nick.py") + add_menu_item(label="Save") + add_menu_item(label="Save As..") + add_separator() + + with menu(label="Settings"): + demo_enable_disable() + add_menu_item(label="Option 1", callback=demo_log) + add_menu_item(label="Option 2", check=True, callback=demo_log) + add_menu_item(label="Option 3", check=True, callback=demo_log, default_value=True) + with child(height=60, autosize_x=True): + for i in range(0, 10): + add_text(default_value=f"Scrolling Text {i}") + add_slider_float(label="Slider Float") + add_input_float(label="Input Int") + add_combo(label="Combo", items=["Yes", "No", "Maybe"]) + + with menu(label="Tools"): + add_menu_item(label="Show Logger", callback=show_logger) + add_menu_item(label="Show About", callback=show_about) + add_menu_item(label="Show Metrics", callback=show_metrics) + add_menu_item(label="Show Documentation", callback=show_documentation) + add_menu_item(label="Show Debug", callback=show_debug) + add_menu_item(label="Show Style Editor", callback=show_style_editor) + + add_text(default_value=f'Dear PyGui says hello. ({get_dearpygui_version()})') + add_text(default_value="This code for this demo can be found here: ") + add_text(default_value="https://github.com/hoffstadt/DearPyGui/blob/master/DearPyGui/dearpygui/demo.py") + + with collapsing_header(label="Window options"): + with table(header_row=False): + add_table_column() + add_table_column() + add_table_column() + + # TODO: when autogenerated names are done and labels are set the label is correctly displayed however when the label is retrieved out of the config dict + # the label is the autogenerated name + add_checkbox(label="no_title_bar", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="no_scrollbar", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="menubar", callback=demo_config, callback_data="Dear PyGui Demo", default_value=True) + + add_table_next_column() + add_checkbox(label="no_move", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="no_resize", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="no_collapse", callback=demo_config, callback_data="Dear PyGui Demo") + + add_table_next_column() + add_checkbox(label="no_close", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="no_background", callback=demo_config, callback_data="Dear PyGui Demo") + add_checkbox(label="no_bring_to_front_on_focus", callback=demo_config, callback_data="Dear PyGui Demo") + + with collapsing_header(label="Widgets"): + + with tree_node(label="Basic"): + + demo_enable_disable() + + with group(horizontal=True): + add_button(label="Button", callback=demo_log) + add_button(label="Button", callback=demo_log, small=True) + add_button(label="Button", callback=demo_log, arrow=True) + add_button(label="Button", callback=demo_log, arrow=True, direction=4010) + add_button(label="Button", callback=demo_log, arrow=True, direction=4020) + add_button(label="Button", callback=demo_log, arrow=True, direction=4030) + + add_checkbox(label="checkbox", callback=demo_log) + add_radio_button(items=["radio a", "radio b", "radio c"], callback=demo_log, horizontal=True) + add_selectable(label="selectable", callback=demo_log) + + # TODO: when items whose colors are set then disabled the disable color is not found so its clear + # probably because if you dont set disable at the item level when the searcher finds color it grabs an empty disable member + + # demonstrate the ability to programmatically create buttons and store their id to do something. + # In this case we are adding to the list of items that will be disabled + log_items = [] + for i in range(0, 7): + if i > 0: + add_same_line() + button_widget = add_button(label="Click", callback=lambda: log_debug(log_items)) + set_theme_style(mvThemeStyle_Button_Rounding, i*5, item=button_widget) + set_theme_style(mvThemeStyle_Button_PaddingX, i*3, item=button_widget) + set_theme_style(mvThemeStyle_Button_PaddingY, i*3, item=button_widget) + set_theme_color(mvThemeCol_Button_Bg, demo_hsv_to_rgb(i/7.0, 0.6, 0.6), item=button_widget) + set_theme_color(mvThemeCol_Button_Active, demo_hsv_to_rgb(i/7.0, 0.8, 0.8), item=button_widget) + set_theme_color(mvThemeCol_Button_Hovered, demo_hsv_to_rgb(i/7.0, 0.7, 0.7), item=button_widget) + log_items.append(button_widget) + + with group(horizontal=True): + add_text(default_value="Press a button: ") + add_button(arrow=True, direction=mvDir_Left, callback=lambda: set_value(widget, int(get_value(widget))-1)) + add_button(arrow=True, direction=mvDir_Right, callback=lambda: set_value(widget, int(get_value(widget))+1)) + widget = add_text(default_value="0") + + with group(horizontal=True): + parent = add_text(default_value="hover me") + with tooltip(parent=parent): + add_text(default_value="I'm a tooltip") + add_dummy(width=10) + parent = add_text(default_value="or me") + with tooltip(parent=parent): + add_text(default_value="I'm a fancy tooltip") + add_simple_plot(label="Curve",value=[0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2]) + + add_separator() + + add_label_text(label="Label", default_value="Value") + add_combo(label="combo", items=["AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK"], default_value="AAAA", callback=demo_log) + add_input_text(label="input text", default_value="Hello, world!", callback=demo_log) + demo_help( + "USER:\n" + "Hold SHIFT or use mouse to select text.\n" + "CTRL+Left/Right to word jump.\n" + "CTRL+A or double-click to select all.\n" + "CTRL+X,CTRL+C,CTRL+V clipboard.\n" + "CTRL+Z,CTRL+Y undo/redo.\n" + "ESCAPE to revert.\n\n") + add_input_text(label="input text (w/ hint)", hint="enter text here", callback=demo_log) + add_input_int(label="input int", callback=demo_log) + add_input_float(label="input float", callback=demo_log) + add_input_float(label="input scientific", format="%e", callback=demo_log) + add_input_floatx(label="input floatx", callback=demo_log) + add_drag_int(label="drag int", callback=demo_log) + demo_help( + "Click and drag to edit value.\n" + "Hold SHIFT/ALT for faster/slower edit.\n" + "Double-click or CTRL+click to input value.") + add_drag_int(label="drag int 0..100", format="%d%%", callback=demo_log) + add_drag_float(label="drag float", callback=demo_log) + add_drag_float(label="drag small float", default_value=0.0067, format="%.06f ns", callback=demo_log) + add_slider_int(label="slider int", max_value=3, callback=demo_log) + demo_help("CTRL+click to enter value.") + add_slider_float(label="slider float", max_value=1.0, format="ratio = %.3f", callback=demo_log) + add_slider_int(label="slider angle", min_value=-360, max_value=360, format="%d deg", callback=demo_log) + add_color_edit3(label="color edit 3", default_value=[255, 0, 51], callback=demo_log) + demo_help( + "Click on the colored square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-click on the colored square to show options.\n" + "CTRL+click on individual component to input value.\n") + add_color_edit4(label="color edit 4", default_value=[102, 179, 0, 128], callback=demo_log) + add_listbox(label="listbox", items=["Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon"], num_items=4, callback=demo_log) + + with tree_node(label="Trees"): + with tree_node(label="Basic Trees"): + with tree_node(label="Child 0", default_open=True): + add_text(default_value="blah blah") + add_same_line() + add_button(label="button") + with tree_node(label="Child 1"): + add_text(default_value="blah blah") + add_same_line() + add_button(label="button") + with tree_node(label="Child 2"): + add_text(default_value="blah blah") + add_same_line() + add_button(label="button") + with tree_node(label="Child 3"): + add_text(default_value="blah blah") + add_same_line() + add_button(label="button") + with tree_node(label="Child 4"): + add_text(default_value="blah blah") + add_same_line() + add_button(label="button") + with tree_node(label="Advanced, with selectable nodes"): + demo_help("This is a more typical looking tree with selectable nodes.\n" + "Click to select, CTRL+Click to toggle, click on arrows or double-click to open.") + + with tree_node(label="Bullets"): + add_text(default_value="Bullet point 1", bullet=True) + add_text(default_value="Bullet point 2\nbullet text can be\nOn multiple lines", bullet=True) + with tree_node(label="Tree node"): + add_text(default_value="Another bullet point", bullet=True) + # TODO: discuss the below behavior. intended was to set the label to an empty string but + # because label is checking if empty or not to use name we get the auto name showing + add_text(default_value="1", bullet=True) + add_same_line() + add_button(label="Button", small=True) + + with tree_node(label="Text"): + + with tree_node(label="Colored Text"): + add_text(default_value="Pink", color=[255, 0, 255]) + add_text(default_value="Yellow", color=[255, 255, 0]) + + with tree_node(label="Images"): + add_text(default_value="Below we are displaying the font texture (which is the only texture we have access to in this demo).") + add_image("INTERNAL_DPG_FONT_ATLAS") + add_text(default_value="Here is an image button using a portion of the font atlas") + demo_enable_disable() + add_image_button(value="INTERNAL_DPG_FONT_ATLAS",uv_max=[0.1, 0.1], callback=demo_log) + add_same_line() + textdata = [] + for i in range(0, 10000): + textdata.append(255) + textdata.append(0) + textdata.append(255) + textdata.append(255) + # TODO: texture requires a name when it would be nice that it didnt + add_texture("#cooltexture", textdata, 100, 100, format=mvTEX_RGBA_INT) + add_image_button(value="#cooltexture", callback=demo_log) + + with tree_node(label="Text Input"): + demo_enable_disable() + add_checkbox(label="readonly", callback=demo_config, callback_data="Multi-line Text Input") + add_checkbox(label="on_enter", callback=demo_config, callback_data="Multi-line Text Input") + with tree_node("Multi-line Text Input"): + add_input_text(multiline=True, default_value="/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n", height=300, callback=demo_log, tab_input=True) + + with tree_node(label="Filtered Text Input"): + add_input_text(callback=demo_log, label="default") + add_input_text(callback=demo_log, label="decimal", decimal=True) + add_input_text(callback=demo_log, label="no blank", no_spaces=True) + add_input_text(callback=demo_log, label="uppercase", uppercase=True) + add_input_text(callback=demo_log, label="scientific", scientific=True) + add_input_text(callback=demo_log, label="hexdecimal", hexadecimal=True) + + with tree_node(label="Password Input"): + password = add_input_text(label="password", password=True, callback=demo_log) + add_input_text(label="password (w/ hint)", password=True, hint="", source=password, callback=demo_log) + add_input_text(label="password (clear)", source=password, callback=demo_log) + + with tree_node(label="Simple Plot Widgets"): + add_simple_plot(label="Frame Times", value=[0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2]) + add_simple_plot(label="Histogram", value=(0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2), height=80, histogram=True, minscale=0.0) + + data1 = [] + for i in range(0, 70): + data1.append(cos(3.14*6*i/180)) + add_simple_plot(label="Lines", value=data1, height=80) + add_simple_plot(label="Histogram", value=data1, height=80, histogram=True) + add_progress_bar(label="Progress Bar", default_value=0.78, overlay="78%") + add_same_line() + add_text(default_value="Progress Bar") + bar = add_progress_bar(default_value=0.78, overlay="1367/1753") + set_theme_color(mvThemeCol_ProgressBar_Bar, [255,0,0, 255], item=bar ) + + with tree_node(label="Multi-component Widgets"): + demo_enable_disable() + input_float_2 = add_input_floatx(label="input float 2", min_value=0.0, max_value=100.0) + add_drag_floatx(label="drag float 2", source=input_float_2) + add_slider_floatx(label="slider float 2", source=input_float_2) + input_int_2 = add_input_intx(label="input int 2", min_value=0, max_value=100) + add_drag_intx(label="drag int 2", source=input_int_2) + add_slider_intx(label="slider int 2", source=input_int_2) + add_spacing() + input_float_3 = add_input_floatx(label="input float 3", min_value=0.0, max_value=100.0) + add_drag_floatx(label="drag float 3", source=input_float_3) + add_slider_floatx(label="slider float 3", source=input_float_3) + input_int_3 = add_input_intx(label="input intx", min_value=0, max_value=100) + add_drag_intx(label="drag int 3", source=input_int_3) + add_slider_intx(label="slider int 3", source=input_int_3) + add_spacing() + input_float_4 = add_input_floatx(label="input float 4", min_value=0.0, max_value=100.0) + add_drag_floatx(label="drag float 4", source=input_float_4) + add_slider_floatx(label="slider float 4", source=input_float_4) + input_int_4 = add_input_intx(label="input int 4", min_value=0, max_value=100) + add_drag_intx(label="drag int 4", source=input_int_4) + add_slider_intx(label="slider intx", source=input_int_4) + + with tree_node(label="Vertical Sliders"): + demo_enable_disable() + add_slider_int(label="", default_value=1, vertical=True, max_value=5, height=160) + add_same_line() + + with group(): + values = [ 0.0, 0.60, 0.35, 0.9, 0.70, 0.20, 0.0 ] + for i in range(0, 7): + if i > 0: + add_same_line() + widget = add_slider_float(label="", default_value=values[i], vertical=True, max_value=1.0, height=160) + set_theme_color(mvThemeCol_SliderFloat_Bg, demo_hsv_to_rgb(i/7.0, 0.5, 0.5), item=widget) + set_theme_color(mvThemeCol_SliderFloat_Grab, demo_hsv_to_rgb(i/7.0, 0.9, 0.9), item=widget) + set_theme_color(mvThemeCol_SliderFloat_BgActive, demo_hsv_to_rgb(i/7.0, 0.7, 0.5), item=widget) + set_theme_color(mvThemeCol_SliderFloat_BgHovered, demo_hsv_to_rgb(i/7.0, 0.6, 0.5), item=widget) + + # TODO: Find out why the final slider is throwing a error for duplicate name when the name should be autogenerated + add_same_line() + with group(): + for i in range(0, 3): + with group(): + values = [ 0.20, 0.80, 0.40, 0.25 ] + for j in range(0, 4): + add_slider_float(label="", default_value=values[j], vertical=True, max_value=1.0, height=50) + if i != 3: + add_same_line() + # TODO: Should the label default just be an empty string when the item isnt given a name or a label, having to evter label="" is annoying, when you dont want a label to show + add_same_line() + with group(horizontal=True): + add_slider_float(label="", vertical=True, max_value=1.0, height=160, width=40) + add_slider_float(label="", vertical=True, max_value=1.0, height=160, width=40) + add_slider_float(label="", vertical=True, max_value=1.0, height=160, width=40) + add_slider_float(label="", vertical=True, max_value=1.0, height=160, width=40) + + with collapsing_header("Layout & Scolling##demo"): + + with tree_node("Child windows##demo"): + + with child(border=False, width=400): + for i in range(0, 100): + add_text(f"{i}: scrollable region") + + add_same_line() + with child(autosize_x=True): + with menu_bar(): + with menu("Menu##child##demo"): + pass + with group(width=-20): + for i in range(0, 100): + add_button(f"{i}##childbutton##demo") + + with tree_node("Child Window Flags##demo"): + + with table(header_row=False): + add_table_column() + add_table_column() + add_table_column() + + add_checkbox("autosize_x##demo", callback=lambda sender, data: configure_item("testchild##demo", autosize_x=get_value(sender))) + add_checkbox("autosize_y##demo", callback=lambda sender, data: configure_item("testchild##demo", autosize_y=get_value(sender))) + + add_table_next_column() + add_checkbox("menubar##childdemo", default_value=True, callback=lambda sender, data: configure_item("testchild##demo", menubar=get_value(sender))) + add_checkbox("no_scrollbar##childdemo", callback=lambda sender, data: configure_item("testchild##demo", no_scrollbar=get_value(sender))) + + add_table_next_column() + add_checkbox("horizontal_scrollbar##childdemo", callback=lambda sender, data: configure_item("testchild##demo", horizontal_scrollbar=get_value(sender))) + add_checkbox("border##childdemo", default_value=True, callback=lambda sender, data: configure_item("testchild##demo", border=get_value(sender))) + + with child(width=500, height=500): + with menu_bar(): + with menu("Menu##testchild##demo"): + pass + for i in range(0, 100): + add_text(default_value="A pretty long sentence if you really think about it. It's also pointless.") + + with tree_node("Widgets Width##demo"): + + add_text("Width=100") + add_drag_float("float##demowidths1", width=100) + + add_text("Width=-100") + add_drag_float("float##demowidths2", width=-100) + + add_text("Width=-1") + add_drag_float("float##demowidths3", width=-1) + + add_text("group with width=75") + with group(width=75): + add_drag_float("float##demowidths4") + add_drag_float("float##demowidths5") + add_drag_float("float##demowidths6") + + with tree_node("Basic Horizontal Layout##demo"): + add_text("(Use add_same_line(), to keep adding items to the right of the preceding item)") + add_text("Normal buttons") + add_same_line() + add_button("Banana##demo") + add_same_line() + add_button("Apple##demo") + add_same_line() + add_button("Corniflower##demo") + + add_text("Small buttons") + add_same_line() + add_button("Like this one##demo", small=True) + add_same_line() + add_text("can fit within a text block") + + add_text("Aligned") + add_same_line(xoffset=150) + add_text("x=150") + add_same_line(xoffset=300) + add_text("x=300") + + add_text(default_value="Aligned") + add_same_line(xoffset=150) + add_button("x=150##demo1", small=True) + add_same_line(xoffset=300) + add_button("x=300##demo1", small=True) + + add_checkbox("My##demo") + add_same_line() + add_checkbox("Tailor##demo") + add_same_line() + add_checkbox("is##demo") + add_same_line() + add_checkbox("rich##demo") + + add_text("Lists:") + add_listbox("##demolistbox1", items=["AAAA", "BBBB", "CCCC", "DDDD"], default_value=0, width=100) + add_same_line() + add_listbox("##demolistbox2", items=["AAAA", "BBBB", "CCCC", "DDDD"], default_value=1, width=100) + add_same_line() + add_listbox("##demolistbox3", items=["AAAA", "BBBB", "CCCC", "DDDD"], default_value=2, width=100) + add_same_line() + add_listbox("##demolistbox4", items=["AAAA", "BBBB", "CCCC", "DDDD"], default_value=3, width=100) + + + add_text("Spacing(100):") + add_button("A##demospacing", width=50, height=50) + add_same_line(spacing=100) + add_button("B##demospacing", width=50, height=50) + + with tree_node("Tabs##demo"): + with tree_node("Basic##tabs##demo"): + with tab_bar(): + with tab("Avocado##demo"): + add_text("This is the avocado tab!") + with tab("Broccoli##demo"): + add_text("This is the broccoli tab!") + with tab("Cucumber##demo"): + add_text("This is the cucumber tab!") + with tree_node("Advanced##tabs##demo"): + add_checkbox("tab bar reorderable##demo", callback=lambda sender, data: configure_item("Basic Tabbar1##demo", reorderable=get_value(sender))) + add_checkbox("tab 2 no_reorder##demo", callback=lambda sender, data: configure_item("tab 2##demo", no_reorder=get_value(sender))) + add_checkbox("tab 2 leading##demo", callback=lambda sender, data: configure_item("tab 2##demo", leading=get_value(sender))) + add_checkbox("tab 2 trailing##demo", callback=lambda sender, data: configure_item("tab 2##demo", trailing=get_value(sender))) + add_checkbox("tab button trailing##demo", callback=lambda sender, data: configure_item("+##demo", trailing=get_value(sender))) + add_checkbox("tab button leading##demo", callback=lambda sender, data: configure_item("+##demo", leading=get_value(sender))) + with tab_bar("Basic Tabbar1##demo"): + with tab("tab 1##demo"): + add_text("This is the tab 1!") + with tab("tab 2##demo"): + add_text("This is the tab 2!") + with tab("tab 3##demo"): + add_text("This is the tab 3!") + with tab("tab 4##demo"): + add_text("This is the tab 4!") + add_tab_button("+##demo", callback=lambda sender, data: log_debug("Pressed tab button")) + add_tab_button("?##demo", callback=lambda sender, data: log_debug("Pressed tab button")) + + with tree_node("Groups##demo123"): + add_text("Groups can be used to bundle widths together so that you can use functions such as is_item_hovered or add_same_line on the whole group.") + with group("group##demotabexamples"): + add_button("AAA##demogroup") + add_button("BBB##demogroup") + add_button("CCC##demogroup") + with tooltip(parent="group##demotabexamples"): + add_text("The group is hovered", wrap=200) + + add_text("Horizontal group:") + with group(horizontal=True): + add_button("AAA##demogroup1") + add_button("BBB##demogroup1") + add_button("CCC##demogroup1") + + with collapsing_header("Tooltips##demo"): + add_text("Hover me for a fancy tooltip") + with tooltip("tool_tip##tooltips", parent="Hover me for a fancy tooltip"): + add_simple_plot("Simpleplot##tooltips##demo", value=(0.3, 0.9, 2.5, 8.9), height = 80) + + with collapsing_header("Popups, Modal windows, & Dialogs##demo"): + + with tree_node("Popups##demo"): + add_text("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it.") + add_button("Select..##popups##demo") + add_same_line() + add_text("") + demo_help("right click for popup, it is set to right mouse button, this can be changed") + with popup("popup1", parent="Select..##popups##demo", ): + add_text("Aquariam") + add_separator() + add_selectable("Bream##demo", callback=lambda sender, data: set_value("", sender)) + add_selectable("Haddock##demo", callback=lambda sender, data: set_value("", sender)) + add_selectable("Mackerel##demo", callback=lambda sender, data: set_value("", sender)) + add_selectable("Pollock##demo", callback=lambda sender, data: set_value("", sender)) + add_selectable("Tilefish##demo", callback=lambda sender, data: set_value("", sender)) + + with tree_node("Modals##demo"): + add_text("Modal windows are like popups but the user cannot close them by clicking outside.") + add_button("Delete..##modals##demo") + demo_help("right click for popup, it is set to right mouse button, this can be changed ") + with popup("Delete?", parent="Delete..##modals##demo", modal=True): + add_text("All those beautiful files will be deleted.\nThis operation cannot be undone!") + add_separator() + add_checkbox("Don't ask me next time##demo") + add_button("OK##modal##demo", width=75, callback=lambda sender, data: close_popup("Delete?")) + add_same_line() + add_button("Cancel##modal##demo", width=75, callback=lambda sender, data: close_popup("Delete?")) + + with tree_node("File Selector##demo"): + def file_selected(sender, data): + log_info(data) + add_button("Select Python File##demo", callback = lambda sender, data: open_file_dialog(file_selected, ".*,.py")) + add_button("Select C++ File##demo", callback = lambda sender, data: open_file_dialog(file_selected, ".*,.cpp")) + + with tree_node("Directory Selector##demo"): + def directory_selected(sender, data): + log_info(data) + add_button("Select Directory##demo", callback = lambda sender, data: select_directory_dialog(directory_selected)) + + with tree_node("Menus inside a regular window##demo"): + add_text("Below we are testing adding menu items to a regular window. It's rather unusual but should work") + add_separator() + add_menu_item("Menu item##demotestingmenus", shortcut="CTRL+M") + with menu("Menu inside a regular window##demo"): + add_menu_item("Disabled item##demotestingmenus", enabled=False) + add_menu_item("New##demotestingmenus") + + with collapsing_header("Tables##demo"): + + with tree_node("Basic##tables##demo"): + + # basic usage of the table api + with table(header_row=False): + + # use add_table_column to add columns to the table + add_table_column() + add_table_column() + add_table_column() + + # add_table_next_column will jump to the next row + # once it reaches the end of the columns + for i in range(0, 4): + for j in range(0, 3): + add_text(f"Row{i} Column{j}") + if not (i == 3 and j == 2): + add_table_next_column() + + with tree_node("Borders, background##tables##demo"): + + add_checkbox("row_background##tables2##demo", default_value=True, callback=lambda sender:configure_item("table2##demo", row_background=get_value(sender))) + add_checkbox("borders_innerH##tables2##demo", default_value=True, callback=lambda sender:configure_item("table2##demo", borders_innerH=get_value(sender))) + add_checkbox("borders_innerV##tables2##demo", default_value=True, callback=lambda sender:configure_item("table2##demo", borders_innerV=get_value(sender))) + add_checkbox("borders_outerH##tables2##demo", default_value=True, callback=lambda sender:configure_item("table2##demo", borders_outerH=get_value(sender))) + add_checkbox("borders_outerV##tables2##demo", default_value=True, callback=lambda sender:configure_item("table2##demo", borders_outerV=get_value(sender))) + add_checkbox("header_row##tables2##demo", default_value=False, callback=lambda sender:configure_item("table2##demo", header_row=get_value(sender))) + + with table("table2##demo", header_row=False, row_background=True, + borders_innerH=True, borders_outerH=True, borders_innerV=True, + borders_outerV=True): + add_table_column("Header 1##democolumns2") + add_table_column("Header 2##democolumns2") + add_table_column("Header 3##democolumns2") + + for i in range(0, 5): + for j in range(0, 3): + add_text(default_value=f"Row{i} Column{j}") + if not (i == 4 and j == 2): + add_table_next_column() + + with tree_node("Resizable, stretch##tables##demo"): + + add_checkbox("borders_innerV##tables3##demo", default_value=True, callback=lambda sender:configure_item("table3##demo", borders_innerV=get_value(sender))) + add_checkbox("borders_outerV##tables3##demo", default_value=True, callback=lambda sender:configure_item("table3##demo", borders_outerV=get_value(sender))) + add_checkbox("resizable##tables3##demo", default_value=True, callback=lambda sender:configure_item("table3##demo", resizable=get_value(sender))) + + with table("table3##demo", header_row=False, resizable=True, + borders_outerH=True, borders_innerV=True, borders_outerV=True): + add_table_column("Header 1##democolumns3") + add_table_column("Header 2##democolumns3") + add_table_column("Header 3##democolumns3") + + for i in range(0, 5): + for j in range(0, 3): + add_text(default_value=f"Row{i} Column{j}") + if not (i == 4 and j == 2): + add_table_next_column() + + with tree_node("Resizable, fixed##tables##demo"): + + add_checkbox("no_host_extendX##tables3##demo", callback=lambda sender:configure_item("table4##demo", no_host_extendX=get_value(sender))) + + with table("table4##demo", header_row=False, policy=8192, resizable=True, no_host_extendX=False, + borders_innerV=True, borders_outerV=True,borders_outerH=True): + add_table_column("Header 1##democolumns4") + add_table_column("Header 2##democolumns4") + add_table_column("Header 3##democolumns4") + + for i in range(0, 5): + for j in range(0, 3): + add_text(default_value=f"Row{i} Column{j}") + if not (i == 4 and j == 2): + add_table_next_column() + + with tree_node("Resizable, mixed##tables##demo"): + + with table("table5##demo", header_row=True, policy=mvTable_SizingFixedFit, row_background=True, reorderable=True, + resizable=True, no_host_extendX=False, hideable=True, + borders_innerV=True, borders_outerV=True, borders_innerH=True, borders_outerH=True): + add_table_column("AAA##democolumns5", width_fixed=True) + add_table_column("BBB##democolumns5", width_fixed=True) + add_table_column("CCC##democolumns5", width_stretch=True, init_width_or_weight=0.0) + + for i in range(0, 5): + for j in range(0, 3): + if j == 2: + add_text(f"Stretch {i}, {j}") + else: + add_text(f"Fixed {i}, {j}") + if not (i == 4 and j == 2): + add_table_next_column() + + with table("table6##demo", header_row=True, policy=mvTable_SizingFixedFit, row_background=True, reorderable=True, + resizable=True, no_host_extendX=False, hideable=True, + borders_innerV=True, borders_outerV=True, borders_innerH=True, borders_outerH=True): + add_table_column("AAA##democolumns6", width_fixed=True) + add_table_column("BBB##democolumns6", width_fixed=True) + add_table_column("CCC##democolumns6", width_stretch=True, init_width_or_weight=0.0) + add_table_column("DDD##democolumns6", width_stretch=True, init_width_or_weight=0.0) + + for i in range(0, 5): + for j in range(0, 4): + if j == 2 or j == 3: + add_text(default_value=f"Stretch {i},{j}") + else: + add_text(default_value=f"Fixed {i}, {j}") + if not (i == 4 and j == 3): + add_table_next_column() + + with tree_node("Reorderable, hideable, with headers##tables##demo"): + + add_checkbox("hideable##tables7##demo", default_value=True, callback=lambda sender:configure_item("table7##demo", hideable=get_value(sender))) + add_checkbox("reorderable##tables7##demo", default_value=True, callback=lambda sender:configure_item("table7##demo", reorderable=get_value(sender))) + add_checkbox("resizable##tables7##demo", default_value=True, callback=lambda sender:configure_item("table7##demo", resizable=get_value(sender))) + + with table("table7##demo", header_row=True, resizable=True, + hideable=True, reorderable=True): + add_table_column("One##democolumns7") + add_table_column("Two##democolumns7") + add_table_column("three##democolumns7") + + for i in range(0, 5): + for j in range(0, 3): + add_text(f"Hello {i}, {j}") + if not (i == 4 and j == 2): + add_table_next_column() + + with tree_node("Outer Size##tables##demo"): + + add_checkbox("no_host_extendX##tables8##demo", default_value=True, callback=lambda sender:configure_item("table8##demo", no_host_extendX=get_value(sender))) + add_checkbox("no_host_extendY##tables8##demo", default_value=False, callback=lambda sender:configure_item("table8##demo", no_host_extendY=get_value(sender))) + + with table("table8##demo", header_row=False, no_host_extendX=True, + borders_innerH=True, borders_outerH=True, borders_innerV=True, + borders_outerV=True, context_menu_in_body=True, row_background=True, + policy=mvTable_SizingFixedFit, height=150): + add_table_column("One##democolumns8") + add_table_column("Two##democolumns8") + add_table_column("three##democolumns8") + + for i in range(0, 10): + for j in range(0, 3): + add_text(f"Cell {i}, {j}") + if not (i == 9 and j == 2): + add_table_next_column() + + add_text("Using explicit size:") + with table("table9##demo", header_row=False, no_host_extendX=True, + borders_innerH=True, borders_outerH=True, borders_innerV=True, + borders_outerV=True, context_menu_in_body=True, row_background=True, + policy=mvTable_SizingFixedFit, height=0, width=300): + add_table_column("One##democolumns9") + add_table_column("Two##democolumns9") + add_table_column("three##democolumns9") + + for i in range(0, 6): + for j in range(0, 3): + add_text(default_value=f"Cell {i}, {j}") + if not (i == 9 and j == 2): + add_table_next_column() diff --git a/DearPyGui/dearpygui/simple.py b/DearPyGui/dearpygui/simple.py new file mode 100644 index 000000000..66a356ebe --- /dev/null +++ b/DearPyGui/dearpygui/simple.py @@ -0,0 +1,706 @@ +"""DearPyGui's simple contains wrappings of the core API. +""" +from contextlib import contextmanager +from typing import List, Any, Callable, Union +import dearpygui.core as internal_dpg + +######################################################################################################################## +# context manager container wrappers +######################################################################################################################## + +@contextmanager +def table(*args, header_row: bool = True, width: int = 0, height: int = 0, inner_width: int = 0, show: bool = True, parent: str = "", + before: str = "", resizable: bool = False, reorderable: bool = False, hideable: bool = False, sortable: bool = False, + context_menu_in_body: bool = False, row_background: bool = False, borders_innerH: bool = False, borders_outerH: bool = False, + borders_innerV: bool = False, borders_outerV: bool = False, policy: int = 0, no_host_extendX: bool = False, + no_host_extendY: bool = False, no_keep_columns_visible: bool = False, precise_widths: bool = False, no_clip: bool = False, + pad_outerX: bool = False, no_pad_outerX: bool = False, no_pad_innerX: bool = False, scrollX: bool = False, scrollY: bool = False): + """Wraps add_table() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **header_row: show headers at the top of the columns + **width: + **height: + **inner_width: + **show: Attempt to render + **parent: Parent this item will be added to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **resizable: Enable resizing columns + **reorderable: Enable reordering columns in header row + **hideable: Enable hiding/disabling columns in context menu. + **sortable: Enable sorting. + **context_menu_in_body: Right-click on columns body/contents will display table context menu. + **row_background: Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + **borders_innerH: Draw horizontal borders between rows. + **borders_outerH: Draw horizontal borders at the top and bottom. + **borders_innerV: Draw vertical borders between columns. + **borders_outerV: Draw vertical borders on the left and right sides. + **policy: sizing policy + **no_host_extendX: Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + **no_host_extendY: Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + **no_keep_columns_visible: Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + **precise_widths: Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + **no_clip: Disable clipping rectangle for every individual columns. + **pad_outerX: Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. + **no_pad_outerX: Default if BordersOuterV is off. Disable outer-most padding. + **no_pad_innerX: Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + **scollX: Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + **scollY: Enable horizontal vertical. + + Returns: + None + """ + try: + yield internal_dpg.add_table(*args, header_row=header_row, width = width, height = height, inner_width = inner_width, + show = show, parent = parent, before = before, resizable = resizable, reorderable = reorderable, hideable = hideable, + sortable = sortable, context_menu_in_body = context_menu_in_body, row_background = row_background, + borders_innerH = borders_innerH, borders_outerH = borders_outerH, borders_innerV = borders_innerV, + borders_outerV = borders_outerV, policy = policy, no_host_extendX = no_host_extendX, + no_host_extendY = no_host_extendY, no_keep_columns_visible = no_keep_columns_visible, precise_widths = precise_widths, + no_clip = no_clip, pad_outerX = pad_outerX, no_pad_outerX = no_pad_outerX, no_pad_innerX = no_pad_innerX, + scrollX = scrollX, scrollY = scrollY) + finally: + internal_dpg.end() + +@contextmanager +def window(*args, width: int = 200, height: int = 200, x_pos: int = 200, y_pos: int = 200, autosize: bool = False, + no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False, + no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False, + no_bring_to_front_on_focus: bool = False, menubar: bool = False, no_close: bool = False, + no_background: bool = False, label: str = "__DearPyGuiDefault", show: bool = True, collapsed: bool = False, + on_close: Callable = None, min_size: List[int]=[32, 32], max_size: List[int] = [30000, 30000]): + """Wraps add_window() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **width: Width of the item. + **height: Height of the item. + **x_pos: x position the window will start at + **y_pos: y position the window will start at + **autosize: Autosized the window to fit it's items. + **no_resize: Allows for the window size to be changed or fixed + **no_title_bar: Title name for the title bar of the window + **no_move: Allows for the window's position to be changed or fixed + **no_scrollbar: Disable scrollbars (window can still scroll with mouse or programmatically) + **no_collapse: Disable user collapsing window by double-clicking on it + **horizontal_scrollbar: Allow horizontal scrollbar to appear (off by default). + **no_focus_on_appearing: Disable taking focus when transitioning from hidden to visible state + **no_bring_to_front_on_focus: Disable bringing window to front when taking focus (e.g. clicking on it or + programmatically giving it focus) + **menubar: Decides if the menubar is shown or not. + **no_close: Decides if the window can be closed. + **no_background: + **label: Displayed name of the item. + **show: sets if the item is shown or not window. + **on_close: Callback ran when window is closed + **min_size: Minimum window size + **max_size: Maximum window size + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_window(*args, width=width, height=height, x_pos=x_pos, y_pos=y_pos, autosize=autosize, + no_resize=no_resize, no_title_bar=no_title_bar, no_move=no_move, + no_scrollbar=no_scrollbar, no_collapse=no_collapse, + horizontal_scrollbar=horizontal_scrollbar, + no_focus_on_appearing=no_focus_on_appearing, + no_bring_to_front_on_focus=no_bring_to_front_on_focus, + menubar=menubar, no_close=no_close, no_background=no_background, + show=show, collapsed=collapsed, on_close=on_close, + min_size=min_size, max_size=max_size) + else: + yield internal_dpg.add_window(*args, width=width, height=height, x_pos=x_pos, y_pos=y_pos, autosize=autosize, + no_resize=no_resize, no_title_bar=no_title_bar, no_move=no_move, + no_scrollbar=no_scrollbar, no_collapse=no_collapse, + horizontal_scrollbar=horizontal_scrollbar, + no_focus_on_appearing=no_focus_on_appearing, + no_bring_to_front_on_focus=no_bring_to_front_on_focus, + menubar=menubar, no_close=no_close, + no_background=no_background, label=label, show=show, + collapsed=collapsed, on_close=on_close, + min_size=min_size, max_size=max_size) + finally: + internal_dpg.end() + + +@contextmanager +def menu_bar(*args, show: bool = True, parent: str = "", before: str = ""): + """Wraps add_menu_bar() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **show: Decides if the item is shown of not. + **parent: Parent this item will be added to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + + Returns: + None + """ + try: + yield internal_dpg.add_menu_bar(*args, show=show, parent=parent, before=before) + finally: + internal_dpg.end() + + +@contextmanager +def menu(*args, label: str = "__DearPyGuiDefault", show: bool = True, parent: str = "", + before: str = "", enabled: bool = True): + """Wraps add_menu() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **label: Displayed name of the item. + **show: Decides if the item is shown of not. + **parent: Parent this item will be added to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **enabled: Will enable or disable the menu. + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_menu(*args, show=show, parent=parent, before=before, enabled=enabled) + else: + yield internal_dpg.add_menu(*args, label=label, show=show, parent=parent, + before=before, enabled=enabled) + finally: + internal_dpg.end() + + +@contextmanager +def child(*args, show: bool = True, parent: str = "", before: str = "", width: int = 0, + height: int = 0, border: bool = True, autosize_x: bool = False, autosize_y: bool = False, + no_scrollbar: bool = False, horizontal_scrollbar: bool = False, menubar: bool = False): + """Wraps add_child() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + show: Decides if the item is shown of not. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **width: Width of the item. + **height: Height of the item. + **border: Shows/Hides the border around the sides + **autosize_x: Autosize the window to fit its items in the x. + **autosize_y: Autosize the window to fit its items in the y. + **no_scrollbar: Disable scrollbars (window can still scroll with mouse or programmatically) + **horizontal_scrollbar: Allow horizontal scrollbar to appear (off by default) + **menubar: adds a bar to add menus + + Returns: + None + """ + try: + yield internal_dpg.add_child(*args, show=show, parent=parent, before=before, width=width, + height=height, border=border, autosize_x=autosize_x, autosize_y=autosize_y, + no_scrollbar=no_scrollbar, horizontal_scrollbar=horizontal_scrollbar, + menubar=menubar) + finally: + internal_dpg.end() + + +@contextmanager +def collapsing_header(*args, label: str = "__DearPyGuiDefault", show: bool = True, + parent: str = "", before: str = "",closable: bool = False, + default_open: bool = False, open_on_double_click: bool = False, open_on_arrow: bool = False, + leaf: bool = False, bullet: bool = False): + """Wraps add_collapsing_header() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **label: Displayed name of the item. + **show: Decides if the item is shown of not. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **closable: Decides if the header can be collapsed. + **default_open: Decides if item is open by default. + **open_on_double_click: Need double-click to open node. + **open_on_arrow: Only open when clicking on the arrow part. + **leaf: No collapsing, no arrow (use as a convenience for leaf nodes). + **bullet: Display a bullet instead of arrow. + + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_collapsing_header(*args, show=show, parent=parent, before=before, + closable=closable, default_open=default_open, + open_on_double_click=open_on_double_click, + open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet) + else: + yield internal_dpg.add_collapsing_header(*args, show=show, label=label, parent=parent, before=before, + closable=closable, default_open=default_open, + open_on_double_click=open_on_double_click, + open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet) + finally: + internal_dpg.end() + + +@contextmanager +def group(*args, show: bool = True, parent: str = "", before: str = "", width: int = 0, + horizontal: bool = False, horizontal_spacing: float = -1.0): + """Wraps add_group() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **show: Decides if the item is shown of not. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **width: Width of the item. + **horizontal: Adds the items on the same row by default. + **horizontal_spacing: Decides the spacing for the items. + + Returns: + None + """ + try: + yield internal_dpg.add_group(*args, show=show, parent=parent, before=before, width=width, + horizontal=horizontal, horizontal_spacing=horizontal_spacing) + finally: + internal_dpg.end() + +@contextmanager +def node(*args, label: str = "__DearPyGuiDefault", show: bool = True, draggable: bool = True, + parent: str = "", before: str = "", x_pos: int = 100, y_pos: int = 100): + """Wraps add_node() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **label: Displayed name of the item. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **show: sets if the item is shown or not window. + **draggable: Allow node to be draggable. + **x_pos: x position the node will start at + **y_pos: y position the node will start at + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_node(*args, show=show, parent=parent, before=before, + draggable=draggable, x_pos=x_pos, y_pos=y_pos) + else: + yield internal_dpg.add_node(*args, label=label, show=show, parent=parent, before=before, + draggable=draggable, x_pos=x_pos, y_pos=y_pos) + finally: + internal_dpg.end() + +@contextmanager +def node_attribute(*args, show: bool = True, output: bool = False, + static: bool = False, parent: str = "", before: str = "", shape: int = 1): + """Wraps add_node_attribute() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **show: sets if the item is shown or not window. + **output: Set as output attribute + **static: Set as static attribute + + Returns: + None + """ + try: + yield internal_dpg.add_node_attribute(*args, show=show, parent=parent, before=before, + output=output, static=static, shape=shape) + + finally: + internal_dpg.end() + +@contextmanager +def node_editor(*args, show: bool = True, parent: str = "", before: str = "", link_callback: Callable = None, delink_callback: Callable = None): + """Wraps add_node_editor() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **show: sets if the item is shown or not window. + **link_callback: Callback ran when a new link is created + **delink_callback: Callback ran when a link is detached + + Returns: + None + """ + try: + yield internal_dpg.add_node_editor(*args, show=show, parent=parent, before=before, link_callback=link_callback, delink_callback=delink_callback) + finally: + internal_dpg.end() + + +@contextmanager +def tab_bar(*args, reorderable: bool = False, callback: Callable = None, callback_data: Any = None, show: bool = True, + parent: str = "", before: str = ""): + """Wraps add_tab_bar() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **reorderable: Allows for moveable tabs. + **callback: Registers a callback. + **callback_data: Callback data. + **show: Decides if the item is shown of not. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + + Returns: + None + """ + try: + yield internal_dpg.add_tab_bar(*args, reorderable=reorderable, callback=callback, callback_data=callback_data, + show=show, parent=parent, before=before) + finally: + internal_dpg.end() + + +@contextmanager +def tab(*args, closable: bool = False, label: str = "__DearPyGuiDefault", show: bool = True, + no_reorder: bool = False, leading: bool = False, trailing: bool = False, no_tooltip: bool = False, + parent: str = "", before: str = ""): + """Wraps add_tab() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **closable: creates a button on the tab that can hide the tab. + **label: Displayed name of the item. + **show: Decides if the item is shown of not. + **no_reorder: Disable reordering this tab or having another tab cross over this tab + **leading: Enforce the tab position to the left of the tab bar (after the tab list popup button) + **trailing: Enforce the tab position to the right of the tab bar (before the scrolling buttons) + **no_tooltip: Disable tooltip for the given tab + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_tab(*args, closable=closable, show=show, parent=parent, before=before, + no_reorder=no_reorder, leading=leading, trailing=trailing, no_tooltip=no_tooltip) + else: + yield internal_dpg.add_tab(*args, closable=closable, label=label, show=show, parent=parent, + before=before, no_reorder=no_reorder, leading=leading, trailing=trailing, no_tooltip=no_tooltip) + finally: + internal_dpg.end() + + +@contextmanager +def tree_node(*args, label: str = "__DearPyGuiDefault", show: bool = True, parent: str = "", + before: str = "", default_open: bool = False, open_on_double_click: bool = False, + open_on_arrow: bool = False, leaf: bool = False, bullet: bool = False): + """Wraps add_tree_node() and automates calling end(). + + Args: + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **label: Displayed name of the item. + **show: Decides if the item is shown of not. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **default_open: Decides if item is open by default. + **open_on_double_click: Need double-click to open node. + **open_on_arrow: Only open when clicking on the arrow part. + **leaf: No collapsing, no arrow (use as a convenience for leaf nodes). + **bullet: Display a bullet instead of arrow. + + Returns: + None + """ + try: + if label == "__DearPyGuiDefault": + yield internal_dpg.add_tree_node(*args, show=show, parent=parent, + before=before, default_open=default_open, + open_on_double_click=open_on_double_click, + open_on_arrow=open_on_arrow, + leaf=leaf, bullet=bullet) + else: + yield internal_dpg.add_tree_node(*args, show=show, parent=parent, + before=before, default_open=default_open, + open_on_double_click=open_on_double_click, + open_on_arrow=open_on_arrow, + leaf=leaf, bullet=bullet, label=label) + finally: + internal_dpg.end() + + +@contextmanager +def tooltip(*args, parent: str = "", before: str = "", show: bool = True): + """Wraps add_tooltip() and automates calling end(). + + Args: + tipparent: Sets the item's tool tip to be the same as the named item's tool tip. + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **show: Decides if the item is shown of not. + + Returns: + None + """ + try: + yield internal_dpg.add_tooltip(*args, parent=parent, before=before, show=show) + finally: + internal_dpg.end() + + +@contextmanager +def popup(*args, mousebutton: int = 1, modal: bool = False, parent: str = "", + before: str = "", width: int = 0, height: int = 0, show: bool = True): + """Wraps add_popup() and automates calling end(). + + Args: + popupparent: Parent that the popup will be assigned to. + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + **mousebutton: The mouse code that will trigger the popup. Default is 1 or mvMouseButton_Right. + (mvMouseButton_Left, mvMouseButton_Right, mvMouseButton_Middle, mvMouseButton_X1, mvMouseButton_X2) + **modal: Makes the popup modal. + **parent: Parent to add this item to. (runtime adding) + **before: This item will be displayed before the specified item in the parent. (runtime adding) + **width: Width of the item. + **height: Height of the item. + **show: Decides if the item is shown of not. + + Returns: + None + """ + try: + yield internal_dpg.add_popup(*args, mousebutton=mousebutton, modal=modal, parent=parent, + before=before, width=width, height=height, show=show) + finally: + internal_dpg.end() + +######################################################################################################################## +# Old Commands +######################################################################################################################## + + +# window configure +def set_window_pos(window: str, x: int, y: int): + """Sets the top left corner of the window to the specified position. + + Args: + window: window to position + x: The x position. + y: The y position. + + Returns: + None + """ + internal_dpg.configure_item(window, x_pos=x, y_pos=y) + + +def get_window_pos(window: str) -> Union[List[int], None]: + """Gets the top left corner of the window to the specified position. + + Args: + window: window to retrieve position + x: The x position. + y: The y position. + + Returns: + list as [x,y] or None + """ + config = internal_dpg.get_item_configuration(window) + return [config["x_pos"], config["y_pos"]] + + +def show_item(item: str): + """Shows the item. + + Args: + item: Item to show. + + Returns: + None + """ + internal_dpg.configure_item(item, show=True) + + +def hide_item(item: str, *, children_only: bool = False): + """Hides the item. + + Args: + **item: Item to hide. + + Returns: + None + """ + if children_only: + children = internal_dpg.get_item_children(item) + for child in children: + internal_dpg.configure_item(child, show=False) + else: + internal_dpg.configure_item(item, show=False) + + +# item configure commands +def set_item_name(item: str, name: str): + """Sets the item's name, anything after the characters "##" in the name will not be shown. + + If no label is specified then by default this will be the displayed label. + + Args: + item: Item name will be applied to. + name: Unique name used to programmatically refer to the item. If label is unused this will be the label, + anything after "##" that occurs in the name will not be shown on screen. + + Returns: + None + """ + internal_dpg.configure_item(item, name=name) + + +def set_item_label(item: str, label: str): + """Sets the item's displayed label, anything after the characters "##" in the name will not be shown. + + Args: + item: Item label will be applied to. + label: Displayed name of the item. + + Returns: + None + """ + internal_dpg.configure_item(item, label=label) + + +def set_item_width(item: str, width: int): + """Sets the item's width. + + Args: + item: Item the Width will be applied to. + width: Width of the item. width to be applied. + + Returns: + None + """ + internal_dpg.configure_item(item, width=width) + + +def set_item_height(item: str, height: int): + """Sets the item's height. + + Args: + item: Item the Height will be applied to. + height: Height of the item. height to be applied. + + Returns: + None + """ + internal_dpg.configure_item(item, height=height) + + +def get_item_label(item: str) -> Union[str, None]: + """Gets the item's label. + + Returns: + label as a string or None + """ + return internal_dpg.get_item_configuration(item)["label"] + + +def get_item_width(item: str) -> Union[int, None]: + """Gets the item's width. + + Returns: + width as a int or None + """ + return internal_dpg.get_item_configuration(item)["width"] + + +def get_item_height(item: str) -> Union[int, None]: + """Gets the item's height. + + Returns: + height as a int or None + """ + return internal_dpg.get_item_configuration(item)["height"] + + +def set_drawing_size(drawing: str, width: int, height: int): + """Sets the drawing's size, width and height. + + Args: + drawing: Drawing that will be set. + width: x axis width to set + height: y axis height to set + + Returns: + None + """ + internal_dpg.configure_item(drawing, width=width, height=height) + + +def get_drawing_size(drawing: str) -> Union[List[int], None]: + """Gets the drawing's scale. + + Args: + drawing: Drawing that will be set. + + Returns: + list as [width, height] or None + """ + config = internal_dpg.get_item_configuration(drawing) + return [config["width"], config["height"]] + +def show_style_editor(sender: str="", data: Any=None) -> None: + """Shows the standard style editor window + + Returns: + None + """ + internal_dpg.configure_item("style##standard", show=True) + +def show_metrics(sender: str="", data: Any=None) -> None: + """Shows the standard metrics window + + Returns: + None + """ + internal_dpg.configure_item("metrics##standard", show=True) + +def show_about(sender: str="", data: Any=None) -> None: + """Shows the standard about window + + Returns: + None + """ + internal_dpg.configure_item("about##standard", show=True) + +def show_debug(sender: str="", data: Any=None) -> None: + """Shows the standard debug window + + Returns: + None + """ + internal_dpg.configure_item("debug##standard", show=True) + +def show_documentation(sender: str="", data: Any=None) -> None: + """Shows the standard documentation window + + Returns: + None + """ + internal_dpg.configure_item("documentation##standard", show=True) diff --git a/DearPyGui/src/core/AppItems/basic/mvButton.cpp b/DearPyGui/src/core/AppItems/basic/mvButton.cpp new file mode 100644 index 000000000..489febfe8 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvButton.cpp @@ -0,0 +1,90 @@ +#include +#include "mvButton.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvButton::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "small", "Small button, useful for embedding in text.", "False"}, + {mvPythonDataType::Bool, "arrow", "Arrow button, must use with direction", "False"}, + {mvPythonDataType::Integer, "direction", "A cardinal direction", "0"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + }, "Adds a button.", "None", "Adding Widgets") }); + } + + mvButton::mvButton(const std::string& name) + : + mvAppItem(name) + { + } + + void mvButton::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_small_button) + { + if (ImGui::SmallButton(m_label.c_str())) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + return; + } + + if (m_arrow) + { + if (ImGui::ArrowButton(m_label.c_str(), m_direction)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + return; + } + + if (ImGui::Button(m_label.c_str(), ImVec2((float)m_width, (float)m_height))) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + void mvButton::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "small")) m_small_button = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "arrow")) m_arrow = ToBool(item); + + if (PyObject* item = PyDict_GetItemString(dict, "direction")) + { + m_direction = ToInt(item); + DecodelibID(m_direction, &m_direction); + } + + } + + void mvButton::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "small", ToPyBool(m_small_button)); + PyDict_SetItemString(dict, "arrow", ToPyBool(m_arrow)); + PyDict_SetItemString(dict, "direction", ToPyInt(MV_ENCODE_CONSTANT(m_direction, 0))); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvButton.h b/DearPyGui/src/core/AppItems/basic/mvButton.h new file mode 100644 index 000000000..74bb0a166 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvButton.h @@ -0,0 +1,82 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvButton, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvButton : public mvAppItem + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvButton, add_button) + + MV_CREATE_CONSTANT(mvDir_None , -1L, 0L); + MV_CREATE_CONSTANT(mvDir_Left , 0L, 0L); + MV_CREATE_CONSTANT(mvDir_Right , 1L, 0L); + MV_CREATE_CONSTANT(mvDir_Up , 2L, 0L); + MV_CREATE_CONSTANT(mvDir_Down , 3L, 0L); + + MV_CREATE_CONSTANT(mvThemeCol_Button_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Button_Bg , ImGuiCol_Button , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Button_Hovered , ImGuiCol_ButtonHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Button_Active , ImGuiCol_ButtonActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Button_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Button_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Button_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Button_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Button_TextAlignX , ImGuiStyleVar_ButtonTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Button_TextAlignY , ImGuiStyleVar_ButtonTextAlign , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Button_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Button_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_ADD_GENERAL_CONSTANT(mvDir_None), + MV_ADD_GENERAL_CONSTANT(mvDir_Left), + MV_ADD_GENERAL_CONSTANT(mvDir_Right), + MV_ADD_GENERAL_CONSTANT(mvDir_Up), + MV_ADD_GENERAL_CONSTANT(mvDir_Down), + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Button_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Button_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Button_Hovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Button_Active, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Button_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Button_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Button_Rounding , 0 ,12), + MV_ADD_CONSTANT(mvThemeStyle_Button_BorderSize , 0 , 1), + MV_ADD_CONSTANT(mvThemeStyle_Button_TextAlignX , 0.5f , 1), + MV_ADD_CONSTANT(mvThemeStyle_Button_TextAlignY , 0.5f , 1), + MV_ADD_CONSTANT(mvThemeStyle_Button_PaddingX , 4 ,20), + MV_ADD_CONSTANT(mvThemeStyle_Button_PaddingY , 3 ,20), + MV_END_STYLE_CONSTANTS + + public: + + mvButton(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiDir m_direction = ImGuiDir_Up; + bool m_small_button = false; + bool m_arrow = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvCheckbox.cpp b/DearPyGui/src/core/AppItems/basic/mvCheckbox.cpp new file mode 100644 index 000000000..53d638070 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvCheckbox.cpp @@ -0,0 +1,47 @@ +#include +#include "mvCheckbox.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvCheckbox::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "Overrides 'name' as value storage key", "''"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"} + }, "Adds a checkbox widget.", "None", "Adding Widgets") }); + } + + mvCheckbox::mvCheckbox(const std::string& name) + : + mvBoolPtrBase(name) + { + } + + void mvCheckbox::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (ImGui::Checkbox(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvCheckbox.h b/DearPyGui/src/core/AppItems/basic/mvCheckbox.h new file mode 100644 index 000000000..4b308c89b --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvCheckbox.h @@ -0,0 +1,68 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvCheckbox, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Bool, 1); + class mvCheckbox : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvCheckbox, add_checkbox) + + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_BgActive , ImGuiCol_CheckMark , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CheckBox_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_InnerItemSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Checkbox_InnerItemSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_CheckBox_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_CheckBox_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_CheckBox_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_CheckBox_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_CheckBox_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_CheckBox_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_InnerItemSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Checkbox_InnerItemSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvCheckbox(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + private: + + bool m_default_value = false; + std::string m_source = ""; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvColorButton.cpp b/DearPyGui/src/core/AppItems/basic/mvColorButton.cpp new file mode 100644 index 000000000..94f9005a4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorButton.cpp @@ -0,0 +1,82 @@ +#include "mvColorButton.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvColorButton::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 255)"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::Bool, "show", "Attemp to render", "True"}, + {mvPythonDataType::Bool, "no_alpha", "ignore Alpha component", "False"}, + {mvPythonDataType::Bool, "no_border", "disable border (which is enforced by default)", "False"}, + {mvPythonDataType::Bool, "no_drag_drop", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + }, "Adds a color button.", "None", "Adding Widgets") }); + } + + mvColorButton::mvColorButton(const std::string& name) + : + mvColorPtrBase(name) + { + } + + void mvColorButton::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImVec4 col = { (*m_value)[0], (*m_value)[1], (*m_value)[2], (*m_value)[3] }; + + if (ImGui::ColorButton(m_label.c_str(), col, m_flags, ImVec2((float)m_width, (float)m_height))) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + void mvColorButton::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + flagop("no_border", ImGuiColorEditFlags_NoBorder, m_flags); + flagop("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + } + + void mvColorButton::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + checkbitset("no_border", ImGuiColorEditFlags_NoBorder, m_flags); + checkbitset("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvColorButton.h b/DearPyGui/src/core/AppItems/basic/mvColorButton.h new file mode 100644 index 000000000..abfe3b773 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorButton.h @@ -0,0 +1,73 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvColorButton, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvColorButton : public mvColorPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorButton, add_color_button) + + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_Separator , ImGuiCol_Separator , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_PopupBg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_DragDrop , ImGuiCol_DragDropTarget , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorButton_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_PopupRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_PopupBorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_PopupPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorButton_PopupPaddingY , ImGuiStyleVar_WindowPadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ColorButton_Text , mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorButton_Separator , mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorButton_PopupBg , mvColor( 20, 20, 20, 240), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorButton_DragDrop , mvColor(255, 255, 0, 230), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorButton_Border , mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorButton_BorderShadow , mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_PopupRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_PopupBorderSize, 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_PopupPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorButton_PopupPaddingY , 8, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvColorButton(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiColorEditFlags m_flags = ImGuiColorEditFlags_None; + bool m_no_alpha = false; + bool m_no_border = false; + bool m_no_drag_drop = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvColorEdit.cpp b/DearPyGui/src/core/AppItems/basic/mvColorEdit.cpp new file mode 100644 index 000000000..397bb4a88 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorEdit.cpp @@ -0,0 +1,303 @@ +#include "mvColorEdit.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvColorEdit3::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 255)"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + {mvPythonDataType::Bool, "no_alpha", "ignore Alpha component", "False"}, + {mvPythonDataType::Bool, "no_picker", "disable picker when clicking on colored square.", "False"}, + {mvPythonDataType::Bool, "no_options", " disable toggling options menu when right-clicking on inputs/small preview.", "False"}, + {mvPythonDataType::Bool, "no_small_preview", "disable colored square preview next to the inputs. For color pickers this only shows if the side preview is not shown.", "False"}, + {mvPythonDataType::Bool, "no_inputs", "disable inputs sliders/text widgets (e.g. to show only the small preview colored square)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "disable tooltip when hovering the preview.", "False"}, + {mvPythonDataType::Bool, "no_label", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "no_drag_drop", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "alpha_bar", "show vertical alpha bar/gradient in picker.", "False"}, + {mvPythonDataType::Bool, "alpha_preview", "display preview as a transparent color over a checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "alpha_preview_half", "display half opaque / half checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "display_rgb", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hsv", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hex", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "uint8", "display values formatted as 0..255", "False"}, + {mvPythonDataType::Bool, "floats", "display values formatted as 0.0f..1.0f floats instead of 0..255 integers.", "False"}, + {mvPythonDataType::Bool, "input_rgb", "input and output data in RGB format.", "False"}, + {mvPythonDataType::Bool, "input_hsv", "input and output data in HSV format.", "False"}, + + }, "Adds an rgb color editing widget. Click and draging the color square will copy the color to be applied on any other color widget.", "None", "Adding Widgets") }); + } + + void mvColorEdit4::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 255)"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + {mvPythonDataType::Bool, "no_alpha", "ignore Alpha component", "False"}, + {mvPythonDataType::Bool, "no_picker", "disable picker when clicking on colored square.", "False"}, + {mvPythonDataType::Bool, "no_options", " disable toggling options menu when right-clicking on inputs/small preview.", "False"}, + {mvPythonDataType::Bool, "no_small_preview", "disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown.", "False"}, + {mvPythonDataType::Bool, "no_inputs", "disable inputs sliders/text widgets (e.g. to show only the small preview colored square)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "disable tooltip when hovering the preview.", "False"}, + {mvPythonDataType::Bool, "no_label", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "no_drag_drop", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "alpha_bar", "show vertical alpha bar/gradient in picker.", "False"}, + {mvPythonDataType::Bool, "alpha_preview", "display preview as a transparent color over a checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "alpha_preview_half", "display half opaque / half checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "display_rgb", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hsv", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hex", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "uint8", "display values formatted as 0..255", "False"}, + {mvPythonDataType::Bool, "floats", "display values formatted as 0.0f..1.0f floats instead of 0..255 integers.", "False"}, + {mvPythonDataType::Bool, "input_rgb", "input and output data in RGB format.", "False"}, + {mvPythonDataType::Bool, "input_hsv", "input and output data in HSV format.", "False"}, + + }, "Adds an rgba color editing widget. Click and draging the color square will copy the color to be applied on any other color widget.", "None", "Adding Widgets") }); + } + + mvColorEdit3::mvColorEdit3(const std::string& name) + : + mvColorPtrBase(name) + { + } + + void mvColorEdit3::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 3, m_disabled_value); + + if (ImGui::ColorEdit3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + } + + mvColorEdit4::mvColorEdit4(const std::string& name) + : + mvColorPtrBase(name) + { + } + + void mvColorEdit4::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 4, m_disabled_value); + + if (ImGui::ColorEdit4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + void mvColorEdit3::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + auto conflictingflagop = [dict](const std::vector& keywords, std::vector flags, int& mflags) + { + + for (size_t i = 0; i < keywords.size(); i++) + { + if (PyObject* item = PyDict_GetItemString(dict, keywords[i].c_str())) + { + //turning all conflicting flags false + for (const auto& flag : flags) mflags &= ~flag; + //writing only the first conflicting flag + ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i]; + break; + } + } + + }; + + flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + flagop("no_picker", ImGuiColorEditFlags_NoPicker, m_flags); + flagop("no_options", ImGuiColorEditFlags_NoOptions, m_flags); + flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + flagop("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + flagop("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + flagop("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + + static std::vector AlphaPreviewKeywords{ "alpha_preview", "alpha_preview_half" }; + static std::vector AlphaPreviewFlags{ ImGuiColorEditFlags_AlphaPreview, ImGuiColorEditFlags_AlphaPreviewHalf }; + + static std::vector DisplayValueTypeKeywords{ "uint8", "floats" }; + static std::vector DisplayValueTypeFlags{ ImGuiColorEditFlags_Uint8, ImGuiColorEditFlags_Float }; + + std::vector DisplayTypeKeywords{ "display_rgb", "display_hsv", "display_hex" }; + std::vector DisplayTypeFlags{ ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_DisplayHex }; + + static std::vector IOTypeKeywords{ "input_rgb", "input_hsv" }; + static std::vector IOTypeFlags{ ImGuiColorEditFlags_InputRGB, ImGuiColorEditFlags_InputHSV }; + + conflictingflagop(AlphaPreviewKeywords, AlphaPreviewFlags, m_flags); + conflictingflagop(DisplayValueTypeKeywords, DisplayValueTypeFlags, m_flags); + conflictingflagop(DisplayTypeKeywords, DisplayTypeFlags, m_flags); + conflictingflagop(IOTypeKeywords, IOTypeFlags, m_flags); + + } + + void mvColorEdit3::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + checkbitset("no_picker", ImGuiColorEditFlags_NoPicker, m_flags); + checkbitset("no_options", ImGuiColorEditFlags_NoOptions, m_flags); + checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + checkbitset("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + checkbitset("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + checkbitset("alpha_preview", ImGuiColorEditFlags_AlphaPreview, m_flags); + checkbitset("alpha_preview_half", ImGuiColorEditFlags_AlphaPreviewHalf, m_flags); + checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + checkbitset("unit8", ImGuiColorEditFlags_Uint8, m_flags); + checkbitset("floats", ImGuiColorEditFlags_Float, m_flags); + checkbitset("input_rgb", ImGuiColorEditFlags_InputRGB, m_flags); + checkbitset("input_hsv", ImGuiColorEditFlags_InputHSV, m_flags); + } + + void mvColorEdit4::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + auto conflictingflagop = [dict](const std::vector& keywords, std::vector flags, int& mflags) + { + + for (size_t i = 0; i < keywords.size(); i++) + { + if (PyObject* item = PyDict_GetItemString(dict, keywords[i].c_str())) + { + //turning all conflicting flags false + for (const auto& flag : flags) mflags &= ~flag; + //writing only the first conflicting flag + ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i]; + break; + } + } + + }; + + flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + flagop("no_picker", ImGuiColorEditFlags_NoPicker, m_flags); + flagop("no_options", ImGuiColorEditFlags_NoOptions, m_flags); + flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + flagop("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + flagop("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags); + flagop("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + + static std::vector AlphaPreviewKeywords{ "alpha_preview", "alpha_preview_half" }; + static std::vector AlphaPreviewFlags{ ImGuiColorEditFlags_AlphaPreview, ImGuiColorEditFlags_AlphaPreviewHalf }; + + static std::vector DisplayValueTypeKeywords{ "uint8", "floats" }; + static std::vector DisplayValueTypeFlags{ ImGuiColorEditFlags_Uint8, ImGuiColorEditFlags_Float }; + + std::vector DisplayTypeKeywords{ "display_rgb", "display_hsv", "display_hex" }; + std::vector DisplayTypeFlags{ ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_DisplayHex }; + + static std::vector IOTypeKeywords{ "input_rgb", "input_hsv" }; + static std::vector IOTypeFlags{ ImGuiColorEditFlags_InputRGB, ImGuiColorEditFlags_InputHSV }; + + conflictingflagop(AlphaPreviewKeywords, AlphaPreviewFlags, m_flags); + conflictingflagop(DisplayValueTypeKeywords, DisplayValueTypeFlags, m_flags); + conflictingflagop(DisplayTypeKeywords, DisplayTypeFlags, m_flags); + conflictingflagop(IOTypeKeywords, IOTypeFlags, m_flags); + + } + + void mvColorEdit4::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + checkbitset("no_picker", ImGuiColorEditFlags_NoPicker, m_flags); + checkbitset("no_options", ImGuiColorEditFlags_NoOptions, m_flags); + checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + checkbitset("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + checkbitset("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, m_flags); + checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + checkbitset("alpha_preview", ImGuiColorEditFlags_AlphaPreview, m_flags); + checkbitset("alpha_preview_half", ImGuiColorEditFlags_AlphaPreviewHalf, m_flags); + checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + checkbitset("unit8", ImGuiColorEditFlags_Uint8, m_flags); + checkbitset("floats", ImGuiColorEditFlags_Float, m_flags); + checkbitset("input_rgb", ImGuiColorEditFlags_InputRGB, m_flags); + checkbitset("input_hsv", ImGuiColorEditFlags_InputHSV, m_flags); + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvColorEdit.h b/DearPyGui/src/core/AppItems/basic/mvColorEdit.h new file mode 100644 index 000000000..ac5e9dee0 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorEdit.h @@ -0,0 +1,215 @@ +#pragma once + +#include "mvTypeBases.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvColorEdit3 +// * mvColorEdit4 +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvColorEdit3 + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvColorEdit3, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Color, 1); + class mvColorEdit3 : public mvColorPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorEdit3, add_color_edit3) + + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_TextHighlight , ImGuiCol_TextSelectedBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_DragDrop , ImGuiCol_DragDropTarget , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_PopupBg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit3_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PopupRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PopupBorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PopupPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PopupPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit3_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_DragDrop, mvColor(255, 255, 0, 230), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_PopupBg, mvColor( 20, 20, 20, 240), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit3_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PopupRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PopupBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PopupPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PopupPaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit3_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvColorEdit3(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiColorEditFlags m_flags = ImGuiColorEditFlags_None; + + std::array m_default_value = { 0.0f, 0.0f, 0.0f, 1.0f }; + bool m_no_alpha = false; + bool m_no_picker = false; + bool m_no_options = false; + bool m_no_small_preview = false; + bool m_no_inputs = false; + bool m_no_tooltip = false; + bool m_no_label = false; + bool m_no_drag_drop = false; + bool m_alpha_bar = false; + bool m_alpha_preview = false; + bool m_alpha_preview_half = false; + bool m_display_rgb = false; + bool m_display_hsv = false; + bool m_display_hex = false; + bool m_uint8 = false; + bool m_floats = false; + bool m_input_rgb = false; + bool m_input_hsv = false; + }; + + //----------------------------------------------------------------------------- + // mvColorEdit4 + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvColorEdit4, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Color, 1); + class mvColorEdit4 : public mvColorPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorEdit4, add_color_edit4) + + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_TextHighlight , ImGuiCol_TextSelectedBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_DragDrop , ImGuiCol_DragDropTarget , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_PopupBg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorEdit4_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PopupRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PopupBorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PopupPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PopupPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorEdit4_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_DragDrop, mvColor(255, 255, 0, 230), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_PopupBg, mvColor( 20, 20, 20, 240), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorEdit4_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PopupRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PopupBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PopupPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PopupPaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorEdit4_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvColorEdit4(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiColorEditFlags m_flags = ImGuiColorEditFlags_None; + + + std::array m_default_value = { 0.0f, 0.0f, 0.0f, 1.0f }; + bool m_no_alpha = false; + bool m_no_picker = false; + bool m_no_options = false; + bool m_no_small_preview = false; + bool m_no_inputs = false; + bool m_no_tooltip = false; + bool m_no_label = false; + bool m_no_drag_drop = false; + bool m_alpha_bar = false; + bool m_alpha_preview = false; + bool m_alpha_preview_half = false; + bool m_display_rgb = false; + bool m_display_hsv = false; + bool m_display_hex = false; + bool m_uint8 = false; + bool m_floats = false; + bool m_input_rgb = false; + bool m_input_hsv = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp b/DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp new file mode 100644 index 000000000..dcf7b5d56 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp @@ -0,0 +1,304 @@ +#include "mvColorPicker.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvColorPicker3::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 255)"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + {mvPythonDataType::Bool, "no_alpha", "ignore Alpha component", "False"}, + {mvPythonDataType::Bool, "no_small_preview", "disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown.", "False"}, + {mvPythonDataType::Bool, "no_inputs", "disable inputs sliders/text widgets (e.g. to show only the small preview colored square)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "disable tooltip when hovering the preview.", "False"}, + {mvPythonDataType::Bool, "no_label", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "no_side_preview", "disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden", "False"}, + {mvPythonDataType::Bool, "alpha_bar", "show vertical alpha bar/gradient in picker.", "False"}, + {mvPythonDataType::Bool, "alpha_preview", "display preview as a transparent color over a checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "alpha_preview_half", "display half opaque / half checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "display_rgb", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hsv", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hex", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "uint8", "display values formatted as 0..255", "False"}, + {mvPythonDataType::Bool, "floats", "display values formatted as 0.0f..1.0f floats instead of 0..255 integers.", "False"}, + {mvPythonDataType::Bool, "picker_hue_bar", "bar for Hue, rectangle for Sat/Value.", "False"}, + {mvPythonDataType::Bool, "picker_hue_wheel", "wheel for Hue, triangle for Sat/Value.", "False"}, + {mvPythonDataType::Bool, "input_rgb", "input and output data in RGB format.", "False"}, + {mvPythonDataType::Bool, "input_hsv", "input and output data in HSV format.", "False"}, + }, "Adds an rgb color picking widget. Click and draging the color square will copy the color to be applied on any other color widget. Right Click allows the style of the color picker to be changed.", "None", "Adding Widgets") }); + } + + void mvColorPicker4::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 255)"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Integer, "width", "", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + {mvPythonDataType::Bool, "no_alpha", "ignore Alpha component", "False"}, + {mvPythonDataType::Bool, "no_small_preview", "disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown.", "False"}, + {mvPythonDataType::Bool, "no_inputs", "disable inputs sliders/text widgets (e.g. to show only the small preview colored square)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "disable tooltip when hovering the preview.", "False"}, + {mvPythonDataType::Bool, "no_label", "disable display of inline text label", "False"}, + {mvPythonDataType::Bool, "no_side_preview", "disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden", "False"}, + {mvPythonDataType::Bool, "alpha_bar", "show vertical alpha bar/gradient in picker.", "False"}, + {mvPythonDataType::Bool, "alpha_preview", "display preview as a transparent color over a checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "alpha_preview_half", "display half opaque / half checkerboard, instead of opaque.", "False"}, + {mvPythonDataType::Bool, "display_rgb", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hsv", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "display_hex", "override _display_ type among RGB/HSV/Hex.", "False"}, + {mvPythonDataType::Bool, "uint8", "display values formatted as 0..255", "False"}, + {mvPythonDataType::Bool, "floats", "display values formatted as 0.0f..1.0f floats instead of 0..255 integers.", "False"}, + {mvPythonDataType::Bool, "picker_hue_bar", "bar for Hue, rectangle for Sat/Value.", "False"}, + {mvPythonDataType::Bool, "picker_hue_wheel", "wheel for Hue, triangle for Sat/Value.", "False"}, + {mvPythonDataType::Bool, "input_rgb", "input and output data in RGB format.", "False"}, + {mvPythonDataType::Bool, "input_hsv", "input and output data in HSV format.", "False"}, + }, "Adds an rgba color picking widget. Click and draging the color square will copy the color to be applied on any other color widget. Right Click allows the style of the color picker to be changed", "None", "Adding Widgets") }); + } + + mvColorPicker3::mvColorPicker3(const std::string& name) + : + mvColorPtrBase(name) + { + } + + void mvColorPicker3::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 3, m_disabled_value); + + if (ImGui::ColorPicker3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + mvColorPicker4::mvColorPicker4(const std::string& name) + : + mvColorPtrBase(name) + { + } + + void mvColorPicker4::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 4, m_disabled_value); + + if (ImGui::ColorPicker4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + void mvColorPicker3::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + auto conflictingflagop = [dict](const std::vector& keywords, std::vector flags, int& mflags) + { + + for (size_t i = 0; i < keywords.size(); i++) + { + if (PyObject* item = PyDict_GetItemString(dict, keywords[i].c_str())) + { + //turning all conflicting flags false + for (const auto& flag : flags) mflags &= ~flag; + //writing only the first conflicting flag + ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i]; + break; + } + } + + }; + + flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + flagop("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + flagop("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags); + flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + flagop("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + flagop("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + flagop("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + + static std::vector AlphaPreviewKeywords{ "alpha_preview", "alpha_preview_half" }; + static std::vector AlphaPreviewFlags{ ImGuiColorEditFlags_AlphaPreview, ImGuiColorEditFlags_AlphaPreviewHalf }; + + static std::vector DisplayValueTypeKeywords{ "uint8", "floats" }; + static std::vector DisplayValueTypeFlags{ ImGuiColorEditFlags_Uint8, ImGuiColorEditFlags_Float }; + + static std::vector PickerTypeKeywords{ "picker_hue_bar", "picker_hue_wheel" }; + static std::vector PickerTypeFlags{ ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags_PickerHueWheel }; + + static std::vector IOTypeKeywords{ "input_rgb", "input_hsv" }; + static std::vector IOTypeFlags{ ImGuiColorEditFlags_InputRGB, ImGuiColorEditFlags_InputHSV }; + + conflictingflagop(AlphaPreviewKeywords, AlphaPreviewFlags, m_flags); + conflictingflagop(DisplayValueTypeKeywords, DisplayValueTypeFlags, m_flags); + conflictingflagop(PickerTypeKeywords, PickerTypeFlags, m_flags); + conflictingflagop(IOTypeKeywords, IOTypeFlags, m_flags); + + } + + void mvColorPicker3::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + checkbitset("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + checkbitset("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags); + checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + checkbitset("alpha_preview", ImGuiColorEditFlags_AlphaPreview, m_flags); + checkbitset("alpha_preview_half", ImGuiColorEditFlags_AlphaPreviewHalf, m_flags); + checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + checkbitset("unit8", ImGuiColorEditFlags_Uint8, m_flags); + checkbitset("floats", ImGuiColorEditFlags_Float, m_flags); + checkbitset("picker_hue_bar", ImGuiColorEditFlags_PickerHueBar, m_flags); + checkbitset("picker_hue_wheel", ImGuiColorEditFlags_PickerHueWheel, m_flags); + checkbitset("input_rgb", ImGuiColorEditFlags_InputRGB, m_flags); + checkbitset("input_hsv", ImGuiColorEditFlags_InputHSV, m_flags); + } + + void mvColorPicker4::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + auto conflictingflagop = [dict](const std::vector& keywords, std::vector flags, int& mflags) + { + + for (size_t i = 0; i < keywords.size(); i++) + { + if (PyObject* item = PyDict_GetItemString(dict, keywords[i].c_str())) + { + //turning all conflicting flags false + for (const auto& flag : flags) mflags &= ~flag; + //writing only the first conflicting flag + ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i]; + break; + } + } + + }; + + flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + flagop("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + flagop("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags); + flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + flagop("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + flagop("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + flagop("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + + static std::vector AlphaPreviewKeywords{ "alpha_preview", "alpha_preview_half" }; + static std::vector AlphaPreviewFlags{ ImGuiColorEditFlags_AlphaPreview, ImGuiColorEditFlags_AlphaPreviewHalf }; + + static std::vector DisplayValueTypeKeywords{ "uint8", "floats" }; + static std::vector DisplayValueTypeFlags{ ImGuiColorEditFlags_Uint8, ImGuiColorEditFlags_Float }; + + static std::vector PickerTypeKeywords{ "picker_hue_bar", "picker_hue_wheel" }; + static std::vector PickerTypeFlags{ ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags_PickerHueWheel }; + + static std::vector IOTypeKeywords{ "input_rgb", "input_hsv" }; + static std::vector IOTypeFlags{ ImGuiColorEditFlags_InputRGB, ImGuiColorEditFlags_InputHSV }; + + conflictingflagop(AlphaPreviewKeywords, AlphaPreviewFlags, m_flags); + conflictingflagop(DisplayValueTypeKeywords, DisplayValueTypeFlags, m_flags); + conflictingflagop(PickerTypeKeywords, PickerTypeFlags, m_flags); + conflictingflagop(IOTypeKeywords, IOTypeFlags, m_flags); + + } + + void mvColorPicker4::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags); + checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags); + checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags); + checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags); + checkbitset("no_label", ImGuiColorEditFlags_NoLabel, m_flags); + checkbitset("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags); + checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags); + checkbitset("alpha_preview", ImGuiColorEditFlags_AlphaPreview, m_flags); + checkbitset("alpha_preview_half", ImGuiColorEditFlags_AlphaPreviewHalf, m_flags); + checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags); + checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags); + checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags); + checkbitset("unit8", ImGuiColorEditFlags_Uint8, m_flags); + checkbitset("floats", ImGuiColorEditFlags_Float, m_flags); + checkbitset("picker_hue_bar", ImGuiColorEditFlags_PickerHueBar, m_flags); + checkbitset("picker_hue_wheel", ImGuiColorEditFlags_PickerHueWheel, m_flags); + checkbitset("input_rgb", ImGuiColorEditFlags_InputRGB, m_flags); + checkbitset("input_hsv", ImGuiColorEditFlags_InputHSV, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvColorPicker.h b/DearPyGui/src/core/AppItems/basic/mvColorPicker.h new file mode 100644 index 000000000..da0562f68 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvColorPicker.h @@ -0,0 +1,207 @@ +#pragma once + +#include "mvTypeBases.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvColorPicker3 +// * mvColorPicker4 +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvColorPicker3 + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvColorPicker3, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Color, 1); + class mvColorPicker3 : public mvColorPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorPicker3, add_color_picker3) + + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_DragDrop , ImGuiCol_DragDropTarget , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker3_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PopupRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PopupBorderSize, ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PopupPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PopupPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker3_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_Text , mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_Bg , mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_BgHovered , mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_BgActive , mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_DragDrop , mvColor(255, 255, 0, 230), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_Border , mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker3_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PopupRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PopupBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PopupPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PopupPaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker3_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvColorPicker3(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiColorEditFlags m_flags = ImGuiColorEditFlags_None; + + std::array m_default_value = { 0.0f, 0.0f, 0.0f, 1.0f }; + bool m_no_alpha = false; + bool m_no_small_preview = false; + bool m_no_inputs = false; + bool m_no_tooltip = false; + bool m_no_label = false; + bool m_no_side_preview = false; + bool m_alpha_bar = false; + bool m_alpha_preview = false; + bool m_alpha_preview_half = false; + bool m_display_rgb = false; + bool m_display_hsv = false; + bool m_display_hex = false; + bool m_uint8 = false; + bool m_floats = false; + bool m_picker_hue_bar = false; + bool m_picker_hue_wheel = false; + bool m_input_rgb = false; + bool m_input_hsv = false; + + }; + + //----------------------------------------------------------------------------- + // mvColorPicker4 + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvColorPicker4, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Color, 1); + class mvColorPicker4 : public mvColorPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorPicker4, add_color_picker4) + + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_DragDrop , ImGuiCol_DragDropTarget , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_ColorPicker4_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PopupRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PopupBorderSize, ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PopupPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PopupPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ColorPicker4_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_Text , mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_Bg , mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_BgHovered , mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_BgActive , mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_DragDrop , mvColor(255, 255, 0, 230), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_Border , mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ColorPicker4_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PopupRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PopupBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PopupPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PopupPaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ColorPicker4_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvColorPicker4(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiColorEditFlags m_flags = ImGuiColorEditFlags_None; + + std::array m_default_value = { 0.0f, 0.0f, 0.0f, 1.0f }; + bool m_no_alpha = false; + bool m_no_small_preview = false; + bool m_no_inputs = false; + bool m_no_tooltip = false; + bool m_no_label = false; + bool m_no_side_preview = false; + bool m_alpha_bar = false; + bool m_alpha_preview = false; + bool m_alpha_preview_half = false; + bool m_display_rgb = false; + bool m_display_hsv = false; + bool m_display_hex = false; + bool m_uint8 = false; + bool m_floats = false; + bool m_picker_hue_bar = false; + bool m_picker_hue_wheel = false; + bool m_input_rgb = false; + bool m_input_hsv = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvCombo.cpp b/DearPyGui/src/core/AppItems/basic/mvCombo.cpp new file mode 100644 index 000000000..29f6a1e45 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvCombo.cpp @@ -0,0 +1,146 @@ +#include +#include "mvCombo.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvCombo::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::StringList, "items", "", "()"}, + {mvPythonDataType::String, "default_value", "", "''"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "Overrides 'name' as value storage key", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::Bool, "show","Attemp to render", "True"}, + {mvPythonDataType::Bool, "popup_align_left","Align the popup toward the left by default", "False"}, + {mvPythonDataType::Bool, "height_small","Max ~4 items visible", "False"}, + {mvPythonDataType::Bool, "height_regular","Max ~8 items visible (default)", "False"}, + {mvPythonDataType::Bool, "height_large","Max ~20 items visible", "False"}, + {mvPythonDataType::Bool, "height_largest","As many items visible as possible", "False"}, + {mvPythonDataType::Bool, "no_arrow_button","Display on the preview box without the square arrow button", "False"}, + {mvPythonDataType::Bool, "no_preview","Display only a square arrow button", "False"}, + }, "Adds a combo.", "None", "Adding Widgets") }); + } + + mvCombo::mvCombo(const std::string& name) + : + mvStringPtrBase(name) + { + } + + void mvCombo::draw(ImDrawList* drawlist, float x, float y) + { + + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + static std::vector disabled_items{}; + + // The second parameter is the label previewed before opening the combo. + if (ImGui::BeginCombo(m_label.c_str(), m_value->c_str(), m_flags)) + { + for (const auto& name : m_enabled ? m_items : disabled_items) + { + bool is_selected = (*m_value == name); + if (ImGui::Selectable((name).c_str(), is_selected)) + { + if (m_enabled) { *m_value = name; } + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + + } + + // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + + ImGui::EndCombo(); + } + + } + + void mvCombo::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "items")) m_items = ToStringVect(item); + + // helpers for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + auto conflictingflagop = [dict](const char* const keywords[4], const int flags[4], int& mflags) + { + + for (size_t i = 0; i < 4; i++) + { + if (PyObject* item = PyDict_GetItemString(dict, keywords[i])) + { + //turning all conflicting flags false + for (int i = 0; i < 4; i++) mflags &= ~flags[i]; + //writing only the first conflicting flag + ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i]; + break; + } + } + + }; + + flagop("popup_align_left", ImGuiComboFlags_PopupAlignLeft, m_flags); + flagop("no_arrow_button", ImGuiComboFlags_NoArrowButton, m_flags); + flagop("no_preview", ImGuiComboFlags_NoPreview, m_flags); + + constexpr static const char* HeightKeywords[4]{ + "height_small", + "height_regular", + "height_large", + "height_largest" }; + + constexpr static const int HeightFlags[4]{ + ImGuiComboFlags_HeightSmall, + ImGuiComboFlags_HeightRegular, + ImGuiComboFlags_HeightLarge, + ImGuiComboFlags_HeightLargest }; + + conflictingflagop(HeightKeywords, HeightFlags, m_flags); + + } + + void mvCombo::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "items", ToPyList(m_items)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + checkbitset("popup_align_left", ImGuiComboFlags_PopupAlignLeft, m_flags); + checkbitset("height_small", ImGuiComboFlags_HeightSmall, m_flags); + checkbitset("height_regular", ImGuiComboFlags_HeightRegular, m_flags); + checkbitset("height_large", ImGuiComboFlags_HeightLarge, m_flags); + checkbitset("height_largest", ImGuiComboFlags_HeightLargest, m_flags); + checkbitset("no_arrow_button", ImGuiComboFlags_NoArrowButton, m_flags); + checkbitset("no_preview", ImGuiComboFlags_NoPreview, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvCombo.h b/DearPyGui/src/core/AppItems/basic/mvCombo.h new file mode 100644 index 000000000..4b0fe9aee --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvCombo.h @@ -0,0 +1,112 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvCombo, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1); + class mvCombo : public mvStringPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvCombo, add_combo) + + MV_CREATE_CONSTANT(mvThemeCol_Combo_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Selected , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Hovered , ImGuiCol_HeaderHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Active , ImGuiCol_HeaderActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_DropBg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_DropButtonBg , ImGuiCol_Button , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_DropButtonHovered , ImGuiCol_ButtonHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Combo_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Combo_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_DropPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_DropPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_DropBorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_DropRounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_ScrollbarSize , ImGuiStyleVar_ScrollbarSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_ScrollbarRounding , ImGuiStyleVar_ScrollbarRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_TextAlignX , ImGuiStyleVar_SelectableTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Combo_TextAlignY , ImGuiStyleVar_SelectableTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Combo_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Selected, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Hovered, mvColor( 41, 74, 74, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Active, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_BgHovered, mvColor( 41, 74, 74, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_DropBg, mvColor( 20, 20, 20, 240), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_DropButtonBg, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_DropButtonHovered, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Scrollbar, mvColor( 5, 5, 5, 135), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_ScrollbarGrab, mvColor( 79, 79, 79, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_ScrollbarGrabHovered, mvColor(105, 105, 105, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_ScrollbarGrabActive, mvColor(130, 130, 130, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Combo_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Combo_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Combo_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Combo_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_DropPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_DropPaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_DropBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Combo_DropRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Combo_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_ScrollbarSize ,14, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_ScrollbarRounding, 9, 12), + MV_ADD_CONSTANT(mvThemeStyle_Combo_TextAlignX , 0, 20), + MV_ADD_CONSTANT(mvThemeStyle_Combo_TextAlignY , 0, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvCombo(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + ImGuiComboFlags m_flags = ImGuiComboFlags_None; + + std::vector m_items; + std::string m_default_value = ""; + bool m_popup_align_left = false; + bool m_height_small = false; + bool m_height_regular = false; + bool m_height_large = false; + bool m_height_largest = false; + bool m_no_arrow_button = false; + bool m_no_preview = false; + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvDragMulti.cpp b/DearPyGui/src/core/AppItems/basic/mvDragMulti.cpp new file mode 100644 index 000000000..3e5ad9864 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvDragMulti.cpp @@ -0,0 +1,263 @@ +#include "mvDragMulti.h" +#include "mvTypeBases.h" +#include +#include "mvApp.h" +#include "mvModule_Core.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDragFloatMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0, 0.0, 0.0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Float, "speed", "", "1.0"}, + {mvPythonDataType::Float, "min_value", "", "0.0"}, + {mvPythonDataType::Float, "max_value", "", "100.0"}, + {mvPythonDataType::String, "format", "", "'%0.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds drag for multiple float values. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + } + + void mvDragIntMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0, 0, 0, 0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Float, "speed", "", "1.0"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::String, "format", "", "'%0.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds drag for multiple int values. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + } + + mvDragFloatMulti::mvDragFloatMulti(const std::string& name) + : mvFloat4PtrBase(name) + { + } + + void mvDragFloatMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 2, m_disabled_value); + + switch (m_size) + { + case 2: + if (ImGui::DragFloat2(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 3: + if (ImGui::DragFloat3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 4: + if (ImGui::DragFloat4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + default: + break; + } + + } + + void mvDragFloatMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + { + m_flags = m_stor_flags; + } + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvDragFloatMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "speed")) m_speed = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvDragFloatMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "speed", ToPyFloat(m_speed)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + + mvDragIntMulti::mvDragIntMulti(const std::string& name) + : mvInt4PtrBase(name) + { + } + + void mvDragIntMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 2, m_disabled_value); + + switch (m_size) + { + case 2: + if (ImGui::DragInt2(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 3: + if (ImGui::DragInt3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 4: + if (ImGui::DragInt4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + default: + break; + } + + } + + void mvDragIntMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + { + m_flags = m_stor_flags; + } + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvDragIntMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "speed")) m_speed = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvDragIntMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "speed", ToPyFloat(m_speed)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvDragMulti.h b/DearPyGui/src/core/AppItems/basic/mvDragMulti.h new file mode 100644 index 000000000..10ab28b97 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvDragMulti.h @@ -0,0 +1,161 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvDragFloatMulti +// * mvDragIntMulti +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvDragFloatMulti + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvDragFloatMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float4, 1); + class mvDragFloatMulti : public mvFloat4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragFloatMulti, add_drag_floatx) + + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_BgHovered, ImGuiCol_FrameBgHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_BgActive, ImGuiCol_FrameBgActive, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloatx_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloatx_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloatx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloatx_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvDragFloatMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_speed = 1.0f; + float m_min = 0.0f; + float m_max = 100.0f; + std::string m_format = "%.3f"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + int m_size = 4; + }; + + //----------------------------------------------------------------------------- + // mvDragIntMulti + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvDragIntMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int4, 1); + class mvDragIntMulti : public mvInt4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragIntMulti, add_drag_intx) + + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_BgHovered, ImGuiCol_FrameBgHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_BgActive, ImGuiCol_FrameBgActive, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragIntx_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragIntx_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_DragIntx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragIntx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragIntx_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragIntx_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragIntx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragIntx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragIntx_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvDragIntMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_speed = 1.0f; + int m_min = 0; + int m_max = 100; + std::string m_format = "%d"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + int m_size = 4; + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvDragSingle.cpp b/DearPyGui/src/core/AppItems/basic/mvDragSingle.cpp new file mode 100644 index 000000000..f0839db74 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvDragSingle.cpp @@ -0,0 +1,224 @@ +#include "mvDragSingle.h" +#include "mvTypeBases.h" +#include +#include "mvApp.h" +#include "mvModule_Core.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDragFloat::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "default_value", "", "0.0"}, + {mvPythonDataType::Float, "speed", "", "1.0"}, + {mvPythonDataType::Float, "min_value", "", "0.0"}, + {mvPythonDataType::Float, "max_value", "", "100.0"}, + {mvPythonDataType::String, "format", "", "'%0.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds drag for a single float value. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + } + + void mvDragInt::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Float, "speed", "", "1.0"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::String, "format", "", "'%d'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds drag for a single int value. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + } + + mvDragFloat::mvDragFloat(const std::string& name) + : mvFloatPtrBase(name) + { + } + + void mvDragFloat::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + { + m_flags = m_stor_flags; + } + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvDragFloat::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (ImGui::DragFloat(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value, m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + mvDragInt::mvDragInt(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvDragInt::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvDragInt::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (ImGui::DragInt(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value, m_speed, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + } + + void mvDragFloat::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "speed")) m_speed = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToFloat(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvDragFloat::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "speed", ToPyFloat(m_speed)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + + void mvDragInt::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "speed")) m_speed = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + } + + void mvDragInt::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "speed", ToPyFloat(m_speed)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvDragSingle.h b/DearPyGui/src/core/AppItems/basic/mvDragSingle.h new file mode 100644 index 000000000..4f7e3b5ea --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvDragSingle.h @@ -0,0 +1,163 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvDragFloat +// * mvDragInt +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvDragFloat + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvDragFloat, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvDragFloat : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragFloat, add_drag_float) + + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_BgHovered, ImGuiCol_FrameBgHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_BgActive, ImGuiCol_FrameBgActive, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragFloat_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragFloat_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_DragFloat_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloat_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloat_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloat_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloat_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragFloat_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragFloat_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvDragFloat(const std::string& name); + + void setEnabled(bool value) override; + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_speed = 1.0f; + float m_min = 0.0f; + float m_max = 100.0f; + std::string m_format = "%.3f"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + + }; + + //----------------------------------------------------------------------------- + // mvDragInt + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvDragInt, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvDragInt : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragInt, add_drag_int) + + MV_CREATE_CONSTANT(mvThemeCol_DragInt_Text, 0L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragInt_Bg, 7L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragInt_BgHovered, 8L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragInt_BgActive, 9L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragInt_Border, 5L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DragInt_BorderShadow, 6L, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_Rounding, 11L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_BorderSize, 12L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_PaddingX, 10L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_PaddingY, 10L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_InnerSpacingX, 14L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DragInt_InnerSpacingY, 14L, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_DragInt_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragInt_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragInt_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragInt_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragInt_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_DragInt_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DragInt_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_DragInt_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DragInt_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragInt_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragInt_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DragInt_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvDragInt(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_speed = 1.0f; + int m_min = 0; + int m_max = 100; + std::string m_format = "%d"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvImage.cpp b/DearPyGui/src/core/AppItems/basic/mvImage.cpp new file mode 100644 index 000000000..dfdf26e3c --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvImage.cpp @@ -0,0 +1,155 @@ +#include "mvImage.h" +#include "mvTextureStorage.h" +#include "mvItemRegistry.h" +#include "mvApp.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + void mvImage::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "value"}, + {mvPythonDataType::FloatList, "tint_color", "", "(255, 255, 255, 255)"}, + {mvPythonDataType::FloatList, "border_color", "", "(0, 0, 0, 0)"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "data source for shared data", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::FloatList, "uv_min", "normalized texture coordinates", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "uv_max", "normalized texture coordinates", "(1.0, 1.0)"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds an image." + "uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown." + "Using(0,0)->(1,1) texture coordinates will generally display the entire texture", "None", "Adding Widgets") }); + } + + mvImage::mvImage(const std::string& name) + : mvAppItem(name) + { + mvEventBus::Subscribe(this, mvEVT_DELETE_TEXTURE); + } + + mvImage::~mvImage() + { + mvEventBus::Publish(mvEVT_CATEGORY_TEXTURE, mvEVT_DEC_TEXTURE, { CreateEventArgument("NAME", m_value) }); + mvEventBus::UnSubscribe(this); + } + + bool mvImage::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvImage::onTextureDeleted), mvEVT_DELETE_TEXTURE); + + return event.handled; + } + + bool mvImage::onTextureDeleted(mvEvent& event) + { + std::string name = GetEString(event, "NAME"); + + if (name == m_value) + { + m_texture = nullptr; + return true; + } + + return false; + } + + void mvImage::draw(ImDrawList* drawlist, float x, float y) + { + + if (m_texture == nullptr && !m_value.empty()) + { + mvApp::GetApp()->getTextureStorage().addTexture(m_value); + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_value); + if (texture == nullptr) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + PyErr_Format(PyExc_Exception, + "Image %s could not be found for add_image. Check the path to the image " + "you provided.", m_value.c_str()); + PyErr_Print(); + m_value = ""; + }); + return; + } + + m_texture = texture->texture; + + if (m_width == 0) m_width = (int)((float)texture->width * (m_uv_max.x - m_uv_min.x)); + if (m_height == 0) m_height = (int)((float)texture->height * (m_uv_max.y - m_uv_min.y)); + + } + + if (m_dirty) + { + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_value); + if (texture) + { + m_texture = texture->texture; + m_width = (int)((float)texture->width * (m_uv_max.x - m_uv_min.x)); + m_height = (int)((float)texture->height * (m_uv_max.y - m_uv_min.y)); + } + m_dirty = false; + } + + if (m_texture) + { + ImGui::Image(m_texture, ImVec2((float)m_width, (float)m_height), ImVec2(m_uv_min.x, m_uv_min.y), ImVec2(m_uv_max.x, m_uv_max.y), + ImVec4((float)m_tintColor.r, (float)m_tintColor.g, (float)m_tintColor.b, (float)m_tintColor.a), + ImVec4((float)m_borderColor.r, (float)m_borderColor.g, (float)m_borderColor.b, (float)m_borderColor.a)); + + } + + } + + void mvImage::setValue(const std::string& value) + { + m_value = value; + } + + const std::string& mvImage::getValue() const + { + return m_value; + } + + void mvImage::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) + { + m_uv_min = ToVec2(item); + m_dirty = true; + } + if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) + { + m_uv_max = ToVec2(item); + m_dirty = true; + } + if (PyObject* item = PyDict_GetItemString(dict, "tint_color")) m_tintColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "border_color")) m_borderColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "value")) m_value = ToString(item); + } + + void mvImage::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "uv_min", ToPyPair(m_uv_min.x, m_uv_min.y)); + PyDict_SetItemString(dict, "uv_max", ToPyPair(m_uv_max.x, m_uv_max.y)); + PyDict_SetItemString(dict, "tint_color", ToPyColor(m_tintColor)); + PyDict_SetItemString(dict, "border_color", ToPyColor(m_borderColor)); + PyDict_SetItemString(dict, "value", ToPyString(m_value)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvImage.h b/DearPyGui/src/core/AppItems/basic/mvImage.h new file mode 100644 index 000000000..1b0bf7b70 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvImage.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvImage, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvImage : public mvAppItem, public mvEventHandler + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvImage, add_image) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvImage(const std::string& name); + + bool onEvent(mvEvent& event) override; + bool onTextureDeleted(mvEvent& event); + + ~mvImage() override; + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + void setValue (const std::string& value); + const std::string& getValue () const; + + private: + + std::string m_value; + mvVec2 m_uv_min = {0.0f, 0.0f}; + mvVec2 m_uv_max = {1.0f, 1.0f}; + mvColor m_tintColor = {1.0f, 1.0f, 1.0f, 1.0f}; + mvColor m_borderColor = {0.0f, 0.0f, 0.0f, 0.0f}; + void* m_texture = nullptr; + bool m_dirty = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvImageButton.cpp b/DearPyGui/src/core/AppItems/basic/mvImageButton.cpp new file mode 100644 index 000000000..592ab13f5 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvImageButton.cpp @@ -0,0 +1,150 @@ +#include "mvImageButton.h" +#include "mvTextureStorage.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + void mvImageButton::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "value"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::FloatList, "tint_color", "", "(255, 255, 255, 255)"}, + {mvPythonDataType::FloatList, "background_color", "", "(0, 0, 0, 0)"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::Integer, "frame_padding","", "-1"}, + {mvPythonDataType::FloatList, "uv_min", "normalized texture coordinates", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "uv_max", "normalized texture coordinates", "(1.0, 1.0)"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + }, "Adds an image button." + "uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown." + "Using(0,0)->(1,1) texture coordinates will generally display the entire texture", "None", "Adding Widgets") }); + } + + mvImageButton::mvImageButton(const std::string& name) + : mvAppItem(name) + { + mvEventBus::Subscribe(this, mvEVT_DELETE_TEXTURE); + } + + mvImageButton::~mvImageButton() + { + mvEventBus::Publish(mvEVT_CATEGORY_TEXTURE, mvEVT_DEC_TEXTURE, { CreateEventArgument("NAME", m_value) }); + mvEventBus::UnSubscribe(this); + } + + bool mvImageButton::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvImageButton::onTextureDeleted), mvEVT_DELETE_TEXTURE); + + return event.handled; + } + + bool mvImageButton::onTextureDeleted(mvEvent& event) + { + std::string name = GetEString(event, "NAME"); + + if (name == m_value) + { + m_texture = nullptr; + return true; + } + + return false; + } + + void mvImageButton::draw(ImDrawList* drawlist, float x, float y) + { + mvImGuiThemeScope scope(this); + + if (m_texture == nullptr && !m_value.empty()) + { + mvApp::GetApp()->getTextureStorage().addTexture(m_value); + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_value); + if (texture == nullptr) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + PyErr_Format(PyExc_Exception, + "Image %s could not be found for add_image_button. Check the path to the image " + "you provided.", m_value.c_str()); + PyErr_Print(); + m_value = ""; + }); + return; + } + if (m_width == 0) m_width = (int)((float)texture->width * (m_uv_max.x - m_uv_min.x)); + if (m_height == 0) m_height = (int)((float)texture->height * (m_uv_max.y - m_uv_min.y)); + + m_texture = texture->texture; + } + + if (m_dirty) + { + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_value); + if (texture) + { + m_width = (int)((float)texture->width * (m_uv_max.x - m_uv_min.x)); + m_height = (int)((float)texture->height * (m_uv_max.y - m_uv_min.y)); + } + m_dirty = false; + } + + if (m_texture) + { + ImGui::PushID(m_name.c_str()); + if (ImGui::ImageButton(m_texture, ImVec2((float)m_width, (float)m_height), + ImVec2(m_uv_min.x, m_uv_min.y), ImVec2(m_uv_max.x, m_uv_max.y), m_framePadding, + m_backgroundColor, m_tintColor)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + ImGui::PopID(); + } + + } + + void mvImageButton::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) + { + m_uv_min = ToVec2(item); + m_dirty = true; + } + if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) + { + m_uv_max = ToVec2(item); + m_dirty = true; + } + if (PyObject* item = PyDict_GetItemString(dict, "tint_color")) m_tintColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "background_color")) m_backgroundColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "frame_padding")) m_framePadding = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "value")) m_value = ToString(item); + } + + void mvImageButton::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "uv_min", ToPyPair(m_uv_min.x, m_uv_min.y)); + PyDict_SetItemString(dict, "uv_max", ToPyPair(m_uv_max.x, m_uv_max.y)); + PyDict_SetItemString(dict, "tint_color", ToPyColor(m_tintColor)); + PyDict_SetItemString(dict, "background_color", ToPyColor(m_backgroundColor)); + PyDict_SetItemString(dict, "frame_padding", ToPyInt(m_framePadding)); + PyDict_SetItemString(dict, "value", ToPyString(m_value)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvImageButton.h b/DearPyGui/src/core/AppItems/basic/mvImageButton.h new file mode 100644 index 000000000..14373d3a7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvImageButton.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvImageButton, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvImageButton : public mvAppItem, public mvEventHandler + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvImageButton, add_image_button) + + MV_CREATE_CONSTANT(mvThemeCol_ImageButton_Bg, ImGuiCol_Button, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ImageButton_BgHovered, ImGuiCol_ButtonHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ImageButton_BgActive, ImGuiCol_ButtonActive, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ImageButton_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ImageButton_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ImageButton_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ImageButton_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ImageButton_PaddingY, ImGuiStyleVar_FramePadding, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_ImageButton_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ImageButton_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ImageButton_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ImageButton_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_ImageButton_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ImageButton_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ImageButton_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ImageButton_PaddingY, 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvImageButton(const std::string& name); + + ~mvImageButton() override; + + bool onEvent(mvEvent& event) override; + bool onTextureDeleted(mvEvent& event); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::string m_value; + mvVec2 m_uv_min = { 0.0f, 0.0f }; + mvVec2 m_uv_max = { 1.0f, 1.0f }; + mvColor m_tintColor = { 1.0f, 1.0f, 1.0f, 1.0f }; + mvColor m_backgroundColor = { 0.0f, 0.0f, 0.0f, 0.0f }; + void* m_texture = nullptr; + int m_framePadding = -1; + bool m_dirty = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvInputMulti.cpp b/DearPyGui/src/core/AppItems/basic/mvInputMulti.cpp new file mode 100644 index 000000000..5be89feac --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputMulti.cpp @@ -0,0 +1,317 @@ +#include "mvInputMulti.h" +#include "mvTypeBases.h" +#include +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvInputIntMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::Bool, "min_clamped", "activates and deactivates min_value", "False"}, + {mvPythonDataType::Bool, "max_clamped", "activates and deactivates max_value", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "on_enter", "Only runs callback on enter", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "readonly", "", "False"}, + }, "Adds input for 4 integer values.", "None", "Adding Widgets") }); + } + + void mvInputFloatMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0, 0.0, 0.0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Float, "min_value", "", "0"}, + {mvPythonDataType::Float, "max_value", "", "100"}, + {mvPythonDataType::Bool, "min_clamped", "activates and deactivates min_value", "False"}, + {mvPythonDataType::Bool, "max_clamped", "activates and deactivates max_value", "False"}, + {mvPythonDataType::String, "format", "", "'%.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "on_enter", "Only runs callback on enter", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "readonly", "", "False"}, + }, "Adds input for 4 float values.", "None", "Adding Widgets") }); + } + + mvInputIntMulti::mvInputIntMulti(const std::string& name) + : mvInt4PtrBase(name) + { + m_last_value = *m_value; + } + + void mvInputIntMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiInputTextFlags_ReadOnly; + m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + } + + m_enabled = value; + } + + void mvInputIntMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + bool res = false; + + switch (m_size) + { + case 2: + res = ImGui::InputInt2(m_label.c_str(), m_value->data(), m_flags); + break; + case 3: + res = ImGui::InputInt3(m_label.c_str(), m_value->data(), m_flags); + break; + case 4: + res = ImGui::InputInt4(m_label.c_str(), m_value->data(), m_flags); + break; + default: + break; + } + + if (res) + { + auto inital_value = *m_value; + // determines clamped cases + if (m_min_clamped && m_max_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] < m_min) m_value->data()[i] = m_min; + else if (m_value->data()[i] > m_max) m_value->data()[i] = m_max; + } + } + else if (m_min_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] < m_min) m_value->data()[i] = m_min; + } + } + else if (m_max_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] > m_max) m_value->data()[i] = m_max; + } + } + + // If the widget is edited through ctrl+click mode the active value will be entered every frame. + // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the + // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every + // frame we check if the value was already submitted. + if (m_last_value != *m_value) + { + m_last_value = *m_value; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + } + } + + mvInputFloatMulti::mvInputFloatMulti(const std::string& name) + : mvFloat4PtrBase(name) + { + m_last_value = *m_value; + } + + void mvInputFloatMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiInputTextFlags_ReadOnly; + m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + } + + m_enabled = value; + } + + void mvInputFloatMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + bool res = false; + + switch (m_size) + { + case 2: + res = ImGui::InputFloat2(m_label.c_str(), m_value->data(), m_format.c_str(), m_flags); + break; + case 3: + res = ImGui::InputFloat3(m_label.c_str(), m_value->data(), m_format.c_str(), m_flags); + break; + case 4: + res = ImGui::InputFloat4(m_label.c_str(), m_value->data(), m_format.c_str(), m_flags); + break; + default: + break; + } + + if (res) + { + auto inital_value = *m_value; + // determines clamped cases + if (m_min_clamped && m_max_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] < m_min) m_value->data()[i] = m_min; + else if (m_value->data()[i] > m_max) m_value->data()[i] = m_max; + } + } + else if (m_min_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] < m_min) m_value->data()[i] = m_min; + } + } + else if (m_max_clamped) + { + for (int i = 0; i < 4; i++) + { + if (m_value->data()[i] > m_max) m_value->data()[i] = m_max; + } + } + + // If the widget is edited through ctrl+click mode the active value will be entered every frame. + // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the + // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every + // frame we check if the value was already submitted. + if (m_last_value != *m_value) + { + m_last_value = *m_value; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + } + } + + void mvInputIntMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "on_enter")) ToBool(item) ? m_flags |= ImGuiInputTextFlags_EnterReturnsTrue : m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + if (PyObject* item = PyDict_GetItemString(dict, "on_enter")) ToBool(item) ? m_stor_flags |= ImGuiInputTextFlags_EnterReturnsTrue : m_stor_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + if (PyObject* item = PyDict_GetItemString(dict, "readonly")) ToBool(item) ? m_flags |= ImGuiInputTextFlags_ReadOnly : m_flags &= ~ImGuiInputTextFlags_ReadOnly; + if (PyObject* item = PyDict_GetItemString(dict, "readonly")) ToBool(item) ? m_stor_flags |= ImGuiInputTextFlags_ReadOnly : m_stor_flags &= ~ImGuiInputTextFlags_ReadOnly; + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) { m_min = ToInt(item); m_min_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) { m_max = ToInt(item); m_max_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "min_clamped")) m_min_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_clamped")) m_max_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + } + + void mvInputIntMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "on_enter", ToPyBool(m_flags & ImGuiInputTextFlags_EnterReturnsTrue)); + PyDict_SetItemString(dict, "readonly", ToPyBool(m_flags & ImGuiInputTextFlags_ReadOnly)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + PyDict_SetItemString(dict, "min_clamped", ToPyBool(m_min_clamped)); + PyDict_SetItemString(dict, "max_clamped", ToPyBool(m_max_clamped)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + } + + void mvInputFloatMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) { m_min = ToFloat(item); m_min_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) { m_max = ToFloat(item); m_max_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "min_clamped")) m_min_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_clamped")) m_max_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_stor_flags); + flagop("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + flagop("readonly", ImGuiInputTextFlags_ReadOnly, m_stor_flags); + + } + + void mvInputFloatMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + PyDict_SetItemString(dict, "min_clamped", ToPyBool(m_min_clamped)); + PyDict_SetItemString(dict, "max_clamped", ToPyBool(m_max_clamped)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvInputMulti.h b/DearPyGui/src/core/AppItems/basic/mvInputMulti.h new file mode 100644 index 000000000..3ed62871c --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputMulti.h @@ -0,0 +1,162 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvInputIntMulti +// * mvInputFloatMulti +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvInputIntMulti + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvInputIntMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int4, 1); + class mvInputIntMulti : public mvInt4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvInputIntMulti, add_input_intx) + + MV_CREATE_CONSTANT(mvThemeCol_InputIntx_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputIntx_TextHighlight, ImGuiCol_TextSelectedBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputIntx_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputIntx_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputIntx_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputIntx_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_InputIntx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputIntx_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputIntx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputIntx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputIntx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputIntx_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvInputIntMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_min = 0; + int m_max = 100; + bool m_min_clamped = false; + bool m_max_clamped = false; + ImGuiInputTextFlags m_flags = 0; + ImGuiInputTextFlags m_stor_flags = 0; + std::array m_last_value = { 0, 0, 0, 0 }; + int m_size = 4; + + }; + + //----------------------------------------------------------------------------- + // mvInputFloatMulti + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvInputFloatMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float4, 1); + class mvInputFloatMulti : public mvFloat4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvInputFloatMulti, add_input_floatx) + + MV_CREATE_CONSTANT(mvThemeCol_InputFloatx_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloatx_TextHighlight, ImGuiCol_TextSelectedBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloatx_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloatx_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloatx_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloatx_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_InputFloatx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloatx_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloatx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloatx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloatx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloatx_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvInputFloatMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_min = 0.0f; + float m_max = 100.0f; + bool m_min_clamped = false; + bool m_max_clamped = false; + std::string m_format = "%.3f"; + ImGuiInputTextFlags m_flags = 0; + ImGuiInputTextFlags m_stor_flags = 0; + std::arraym_last_value = { 0.0f, 0.0f, 0.0f, 0.0f }; + int m_size = 4; + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvInputSingle.cpp b/DearPyGui/src/core/AppItems/basic/mvInputSingle.cpp new file mode 100644 index 000000000..a5d9811cc --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputSingle.cpp @@ -0,0 +1,273 @@ +#include "mvInputSingle.h" +#include "mvTypeBases.h" +#include +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvInputInt::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::Bool, "min_clamped", "activates and deactivates min_value", "False"}, + {mvPythonDataType::Bool, "max_clamped", "activates and deactivates max_value", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "on_enter", "Only runs callback on enter", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "step", "", "1"}, + {mvPythonDataType::Integer, "step_fast", "", "100"}, + {mvPythonDataType::Bool, "readonly", "", "False"}, + }, "Adds input for integer values.", "None", "Adding Widgets") }); + } + + void mvInputFloat::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "default_value", "", "0.0"}, + {mvPythonDataType::Float, "min_value", "", "0"}, + {mvPythonDataType::Float, "max_value", "", "100"}, + {mvPythonDataType::Bool, "min_clamped", "activates and deactivates min_value", "False"}, + {mvPythonDataType::Bool, "max_clamped", "activates and deactivates max_value", "False"}, + {mvPythonDataType::String, "format", "", "'%.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "on_enter", "Only runs callback on enter", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Float, "step", "", "0.1"}, + {mvPythonDataType::Float, "step_fast", "", "1.0"}, + {mvPythonDataType::Bool, "readonly", "", "False"}, + }, "Adds input for float values.", "None", "Adding Widgets") }); + } + + mvInputInt::mvInputInt(const std::string& name) + : mvIntPtrBase(name) + { + m_last_value = *m_value; + } + + void mvInputInt::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiInputTextFlags_ReadOnly; + m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + } + + m_enabled = value; + } + + void mvInputInt::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::InputInt(m_label.c_str(), m_value.get(), m_step, m_step_fast, m_flags)) + { + // determines clamped cases + if (m_min_clamped && m_max_clamped) + { + if (*m_value < m_min) *m_value = m_min; + else if (*m_value > m_max) *m_value = m_max; + } + else if (m_min_clamped) + { + if (*m_value < m_min) *m_value = m_min; + } + else if (m_max_clamped) + { + if (*m_value > m_max) *m_value = m_max; + } + + // If the widget is edited through ctrl+click mode the active value will be entered every frame. + // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the + // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every + // frame we check if the value was already submitted. + if (m_last_value != *m_value) + { + m_last_value = *m_value; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + } + + } + + mvInputFloat::mvInputFloat(const std::string& name) + : mvFloatPtrBase(name) + { + m_last_value = *m_value; + } + + void mvInputFloat::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiInputTextFlags_ReadOnly; + m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + } + + m_enabled = value; + } + + void mvInputFloat::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::InputFloat(m_label.c_str(), m_value.get(), m_step, m_step_fast, m_format.c_str(), m_flags)) + { + auto inital_value = *m_value; + // determines clamped cases + if (m_min_clamped && m_max_clamped) + { + if (*m_value < m_min) *m_value = m_min; + else if (*m_value > m_max) *m_value = m_max; + } + else if (m_min_clamped) + { + if (*m_value < m_min) *m_value = m_min; + } + else if (m_max_clamped) + { + if (*m_value > m_max) *m_value = m_max; + } + + // If the widget is edited through ctrl+click mode the active value will be entered every frame. + // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the + // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every + // frame we check if the value was already submitted. + if (m_last_value != *m_value) + { + m_last_value = *m_value; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + } + } + + void mvInputInt::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "on_enter")) ToBool(item) ? m_flags |= ImGuiInputTextFlags_EnterReturnsTrue : m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + if (PyObject* item = PyDict_GetItemString(dict, "on_enter")) ToBool(item) ? m_stor_flags |= ImGuiInputTextFlags_EnterReturnsTrue : m_stor_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + if (PyObject* item = PyDict_GetItemString(dict, "readonly")) ToBool(item) ? m_flags |= ImGuiInputTextFlags_ReadOnly : m_flags &= ~ImGuiInputTextFlags_ReadOnly; + if (PyObject* item = PyDict_GetItemString(dict, "readonly")) ToBool(item) ? m_stor_flags |= ImGuiInputTextFlags_ReadOnly : m_stor_flags &= ~ImGuiInputTextFlags_ReadOnly; + if (PyObject* item = PyDict_GetItemString(dict, "step")) m_step = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "step_fast")) m_step_fast = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) { m_min = ToInt(item); m_min_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) { m_max = ToInt(item); m_max_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "min_clamped")) m_min_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_clamped")) m_max_clamped = ToBool(item); + } + + void mvInputInt::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "on_enter", ToPyBool(m_flags & ImGuiInputTextFlags_EnterReturnsTrue)); + PyDict_SetItemString(dict, "readonly", ToPyBool(m_flags & ImGuiInputTextFlags_ReadOnly)); + PyDict_SetItemString(dict, "step", ToPyInt(m_step)); + PyDict_SetItemString(dict, "step_fast", ToPyInt(m_step_fast)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + PyDict_SetItemString(dict, "min_clamped", ToPyBool(m_min_clamped)); + PyDict_SetItemString(dict, "max_clamped", ToPyBool(m_max_clamped)); + + } + + void mvInputFloat::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "step")) m_step = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "step_fast")) m_step_fast = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) { m_min = ToFloat(item); m_min_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) { m_max = ToFloat(item); m_max_clamped = true; } + if (PyObject* item = PyDict_GetItemString(dict, "min_clamped")) m_min_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_clamped")) m_max_clamped = ToBool(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_stor_flags); + flagop("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + flagop("readonly", ImGuiInputTextFlags_ReadOnly, m_stor_flags); + + } + + void mvInputFloat::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "step", ToPyFloat(m_step)); + PyDict_SetItemString(dict, "step_fast", ToPyFloat(m_step_fast)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + PyDict_SetItemString(dict, "min_clamped", ToPyBool(m_min_clamped)); + PyDict_SetItemString(dict, "max_clamped", ToPyBool(m_max_clamped)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvInputSingle.h b/DearPyGui/src/core/AppItems/basic/mvInputSingle.h new file mode 100644 index 000000000..d4914adcc --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputSingle.h @@ -0,0 +1,185 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvInputInt +// * mvInputFloat +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvInputInt + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvInputInt, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvInputInt : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvInputInt, add_input_int) + + MV_CREATE_CONSTANT(mvThemeCol_InputInt_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_TextHighlight , ImGuiCol_TextSelectedBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_ButtonBg , ImGuiCol_Button , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_ButtonBgHovered , ImGuiCol_ButtonHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_ButtonBgActive , ImGuiCol_ButtonActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputInt_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_ButtonTextAlignX, ImGuiStyleVar_ButtonTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputInt_ButtonTextAlignY, ImGuiStyleVar_ButtonTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_InputInt_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_ButtonBg, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_ButtonBgHovered, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_ButtonBgActive, mvColor( 15, 135, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputInt_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_InputInt_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_ButtonTextAlignX , 0.5, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputInt_ButtonTextAlignY , 0.5, 1), + MV_END_STYLE_CONSTANTS + + public: + + mvInputInt(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_step = 1; + int m_step_fast = 100; + int m_min = 0; + int m_max = 100; + bool m_min_clamped = false; + bool m_max_clamped = false; + ImGuiInputTextFlags m_flags = 0; + ImGuiInputTextFlags m_stor_flags = 0; + int m_last_value = 0; + + }; + + //----------------------------------------------------------------------------- + // mvInputFloat + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvInputFloat, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvInputFloat : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvInputFloat, add_input_float) + + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_TextHighlight , ImGuiCol_TextSelectedBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_ButtonBg , ImGuiCol_Button , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_ButtonBgHovered , ImGuiCol_ButtonHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_ButtonBgActive , ImGuiCol_ButtonActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputFloat_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_ButtonTextAlignX, ImGuiStyleVar_ButtonTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputFloat_ButtonTextAlignY, ImGuiStyleVar_ButtonTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_InputFloat_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_ButtonBg, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_ButtonBgHovered, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_ButtonBgActive, mvColor( 15, 135, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputFloat_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_ButtonTextAlignX, 0.5, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputFloat_ButtonTextAlignY, 0.5, 1), + MV_END_STYLE_CONSTANTS + + public: + + mvInputFloat(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_min = 0.0f; + float m_max = 100.0f; + bool m_min_clamped = false; + bool m_max_clamped = false; + std::string m_format = "%.3f"; + float m_step = 0.1f; + float m_step_fast = 1.0f; + ImGuiInputTextFlags m_flags = 0; + ImGuiInputTextFlags m_stor_flags = 0; + float m_last_value = 0.0f; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvInputText.cpp b/DearPyGui/src/core/AppItems/basic/mvInputText.cpp new file mode 100644 index 000000000..ba45f8508 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputText.cpp @@ -0,0 +1,145 @@ +#include "mvInputText.h" +#include +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvInputText::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "default_value", "", "''"}, + {mvPythonDataType::String, "hint", "", "''"}, + {mvPythonDataType::Bool, "multiline", "", "False"}, + {mvPythonDataType::Bool, "no_spaces", "Filter out spaces, tabs", "False"}, + {mvPythonDataType::Bool, "uppercase", "", "False"}, + {mvPythonDataType::Bool, "tab_input", "Allows tabs to be input instead of changing widget focus", "False"}, + {mvPythonDataType::Bool, "decimal", "Allow 0123456789.+-*/", "False"}, + {mvPythonDataType::Bool, "hexadecimal", "Allow 0123456789ABCDEFabcdef", "False"}, + {mvPythonDataType::Bool, "readonly", "", "False"}, + {mvPythonDataType::Bool, "password", "Password mode, display all characters as '*'", "False"}, + {mvPythonDataType::Bool, "scientific", "Allow 0123456789.+-*/eE (Scientific notation input)", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::Bool, "on_enter", "Only runs callback on enter", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds input for text values.", "None", "Adding Widgets") }); + } + + mvInputText::mvInputText(const std::string& name) + : + mvStringPtrBase(name) + { + } + + void mvInputText::setEnabled(bool value) + { + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiInputTextFlags_ReadOnly; + m_flags &= ~ImGuiInputTextFlags_EnterReturnsTrue; + } + + m_enabled = value; + } + + void mvInputText::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_multiline) + m_hint = ""; + + if (m_hint.empty()) + { + if (m_multiline) + { + if (ImGui::InputTextMultiline(m_label.c_str(), m_value.get(), ImVec2((float)m_width, (float)m_height), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + else + { + if (ImGui::InputText(m_label.c_str(), m_value.get(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + } + + else + { + if (ImGui::InputTextWithHint(m_label.c_str(), m_hint.c_str(), m_value.get(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + + } + + void mvInputText::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "hint")) m_hint = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "multiline")) m_multiline = ToBool(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("no_spaces", ImGuiInputTextFlags_CharsNoBlank, m_flags); + flagop("uppercase", ImGuiInputTextFlags_CharsUppercase, m_flags); + flagop("decimal", ImGuiInputTextFlags_CharsDecimal, m_flags); + flagop("hexadecimal", ImGuiInputTextFlags_CharsHexadecimal, m_flags); + flagop("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + flagop("password", ImGuiInputTextFlags_Password, m_flags); + flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + flagop("scientific", ImGuiInputTextFlags_CharsScientific, m_flags); + flagop("tab_input", ImGuiInputTextFlags_AllowTabInput, m_flags); + } + + void mvInputText::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "hint", ToPyString(m_hint)); + PyDict_SetItemString(dict, "multline", ToPyBool(m_multiline)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("no_spaces", ImGuiInputTextFlags_CharsNoBlank, m_flags); + checkbitset("uppercase", ImGuiInputTextFlags_CharsUppercase, m_flags); + checkbitset("decimal", ImGuiInputTextFlags_CharsDecimal, m_flags); + checkbitset("hexadecimal", ImGuiInputTextFlags_CharsHexadecimal, m_flags); + checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, m_flags); + checkbitset("password", ImGuiInputTextFlags_Password, m_flags); + checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, m_flags); + checkbitset("scientific", ImGuiInputTextFlags_CharsScientific, m_flags); + checkbitset("tab_input", ImGuiInputTextFlags_AllowTabInput, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvInputText.h b/DearPyGui/src/core/AppItems/basic/mvInputText.h new file mode 100644 index 000000000..6266dc2ec --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvInputText.h @@ -0,0 +1,75 @@ +#pragma once + +#include "mvApp.h" +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvInputText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1); + class mvInputText : public mvStringPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvInputText, add_input_text) + + MV_CREATE_CONSTANT(mvThemeCol_InputText_Text, ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputText_TextHighlight, ImGuiCol_TextSelectedBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputText_Bg, ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputText_Hint, ImGuiCol_TextDisabled, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputText_Border, ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_InputText_BorderShadow, ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_InputText_Rounding, ImGuiStyleVar_FrameRounding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputText_BorderSize, ImGuiStyleVar_FrameBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputText_PaddingX, ImGuiStyleVar_FramePadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputText_PaddingY, ImGuiStyleVar_FramePadding, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_InputText_InnerSpacingX, ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_InputText_InnerSpacingY, ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_InputText_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputText_TextHighlight, mvColor( 66, 150, 250, 89), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputText_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputText_Hint, mvColor(128, 128, 128, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputText_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_InputText_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_InputText_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_InputText_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_InputText_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputText_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputText_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_InputText_InnerSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvInputText(const std::string& name); + + void setEnabled (bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::string m_hint; + bool m_multiline = false; + ImGuiInputTextFlags m_flags = 0; + ImGuiInputTextFlags m_stor_flags = 0; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvListbox.cpp b/DearPyGui/src/core/AppItems/basic/mvListbox.cpp new file mode 100644 index 000000000..cc4da3cc0 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvListbox.cpp @@ -0,0 +1,72 @@ +#include +#include "mvListbox.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvListbox::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "Name of the listbox"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::StringList, "items", "", "()"}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "num_items", "number of items to show", "3"}, + {mvPythonDataType::String, "label","", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a listbox.", "None", "Adding Widgets") }); + } + + mvListbox::mvListbox(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvListbox::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (ImGui::ListBox(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value, m_charNames.data(), (int)m_names.size(), m_itemsHeight)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + } + + void mvListbox::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "num_items")) m_itemsHeight = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "items")) + { + m_names = ToStringVect(item); + m_charNames.clear(); + for (const std::string& item : m_names) + m_charNames.emplace_back(item.c_str()); + } + } + + void mvListbox::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "items", ToPyList(m_names)); + PyDict_SetItemString(dict, "num_items", ToPyInt(m_itemsHeight)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvListbox.h b/DearPyGui/src/core/AppItems/basic/mvListbox.h new file mode 100644 index 000000000..e1f606ac0 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvListbox.h @@ -0,0 +1,88 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvListbox, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvListbox : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvListbox, add_listbox) + + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Selected , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Hovered , ImGuiCol_HeaderHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Active , ImGuiCol_HeaderActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Listbox_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_ScrollbarSize , ImGuiStyleVar_ScrollbarSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_ScrollbarRounding , ImGuiStyleVar_ScrollbarRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_TextAlignX , ImGuiStyleVar_SelectableTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Listbox_TextAlignY , ImGuiStyleVar_SelectableTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Listbox_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Selected, mvColor( 60, 150, 250, 79), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Hovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Active, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_Scrollbar, mvColor( 5, 5, 5, 135), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_ScrollbarGrab, mvColor( 79, 79, 79, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_ScrollbarGrabHovered, mvColor(105, 105, 105, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Listbox_ScrollbarGrabActive, mvColor(130, 130, 130, 255), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Listbox_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_ScrollbarSize ,14, 20), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_ScrollbarRounding , 9, 12), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_TextAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Listbox_TextAlignY , 0, 1), + MV_END_STYLE_CONSTANTS + + public: + + mvListbox(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::vector m_names; + int m_itemsHeight = 3; // number of items to show (default -1) + std::vector m_charNames; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvMenuItem.cpp b/DearPyGui/src/core/AppItems/basic/mvMenuItem.cpp new file mode 100644 index 000000000..e5fef9548 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvMenuItem.cpp @@ -0,0 +1,74 @@ +#include "mvMenuItem.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvMenuItem::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "False"}, + {mvPythonDataType::String, "shortcut", "Adds a shortcut", "''"}, + {mvPythonDataType::Bool, "check", "Makes menu item with checkmark. Only one menu item per container can be checked at a time.", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "source", "Overrides 'name' as value storage key", "''"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a menu item to an existing menu.", "None", "Containers") }); + } + + mvMenuItem::mvMenuItem(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvMenuItem::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + // This is ugly and goes against our style system but its the only widget that ImGui chooses to push teh disable color for us + // so we have to map our text disable color to the system text disable color, or we can create a new constant which goes agains our + // constants. + ImGui::PushStyleColor(ImGuiCol_TextDisabled, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + + // create menu item and see if its selected + if (ImGui::MenuItem(m_label.c_str(), m_shortcut.c_str(), m_check ? m_value.get() : nullptr, m_enabled)) + { + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + + ImGui::PopStyleColor(); + + } + + void mvMenuItem::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "shortcut")) m_shortcut = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "check")) m_check = ToBool(item); + +} + + void mvMenuItem::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "shortcut", ToPyString(m_shortcut)); + PyDict_SetItemString(dict, "check", ToPyBool(m_check)); + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvMenuItem.h b/DearPyGui/src/core/AppItems/basic/mvMenuItem.h new file mode 100644 index 000000000..575039e82 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvMenuItem.h @@ -0,0 +1,58 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvMenuItem, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Bool, 1); + class mvMenuItem : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvMenuItem, add_menu_item) + + MV_CREATE_CONSTANT(mvThemeCol_MenuItem_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_MenuItem_BgHovered , ImGuiCol_HeaderHovered, 0L); + + MV_CREATE_CONSTANT(ImGuiStyleVar_MenuItem_TextAlignX , ImGuiStyleVar_SelectableTextAlign, 0L); + MV_CREATE_CONSTANT(ImGuiStyleVar_MenuItem_TextAlignY , ImGuiStyleVar_SelectableTextAlign, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_MenuItem_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_MenuItem_BgHovered, mvColor( 66, 150, 250, 240), mvColor(128, 128, 128, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(ImGuiStyleVar_MenuItem_TextAlignX, 0, 1), + MV_ADD_CONSTANT(ImGuiStyleVar_MenuItem_TextAlignY, 0, 1), + MV_END_STYLE_CONSTANTS + + public: + + explicit mvMenuItem(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::string m_shortcut; + bool m_default_value = false; + bool m_check = false; + std::string m_source = ""; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvRadioButton.cpp b/DearPyGui/src/core/AppItems/basic/mvRadioButton.cpp new file mode 100644 index 000000000..5c4a1cf58 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvRadioButton.cpp @@ -0,0 +1,74 @@ +#include +#include "mvRadioButton.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + void mvRadioButton::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::StringList, "items", "", "()"}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Bool, "horizontal", "", "False"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a set of radio buttons. If items is empty, nothing will be shown.", "None", "Adding Widgets") }); + } + + mvRadioButton::mvRadioButton(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvRadioButton::draw(ImDrawList* drawlist, float x, float y) + { + + ImGui::BeginGroup(); + + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + for (size_t i = 0; i < m_itemnames.size(); i++) + { + if (m_horizontal && i != 0) + ImGui::SameLine(); + + if (ImGui::RadioButton((m_itemnames[i] + "##" + m_name).c_str(), m_enabled ? m_value.get() : &m_disabled_value, (int)i)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + } + + ImGui::EndGroup(); + } + + void mvRadioButton::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "items")) m_itemnames = ToStringVect(item); + if (PyObject* item = PyDict_GetItemString(dict, "horizontal")) m_horizontal = ToBool(item); + } + + void mvRadioButton::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "items", ToPyList(m_itemnames)); + PyDict_SetItemString(dict, "horizontal", ToPyBool(m_horizontal)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvRadioButton.h b/DearPyGui/src/core/AppItems/basic/mvRadioButton.h new file mode 100644 index 000000000..87600e56d --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvRadioButton.h @@ -0,0 +1,68 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvRadioButton, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvRadioButton : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvRadioButton, add_radio_button) + + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_BgActive , ImGuiCol_CheckMark , 0L); + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_RadioButton_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_RadioButton_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_RadioButton_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_RadioButton_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_RadioButton_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_RadioButton_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_RadioButton_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_RadioButton_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_RadioButton_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_RadioButton_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_RadioButton_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_RadioButton_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_RadioButton_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_RadioButton_PaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_RadioButton_PaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_RadioButton_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_RadioButton_InnerSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvRadioButton(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::vector m_itemnames; + bool m_horizontal = false; + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvSelectable.cpp b/DearPyGui/src/core/AppItems/basic/mvSelectable.cpp new file mode 100644 index 000000000..5736b6073 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSelectable.cpp @@ -0,0 +1,95 @@ +#include +#include "mvSelectable.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvSelectable::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "default_value", "", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "span_columns", "span all columns", "False"}, + }, "Adds a selectable.", "None", "Adding Widgets") }); + } + + mvSelectable::mvSelectable(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvSelectable::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags &= ~ImGuiSelectableFlags_Disabled; + + else + m_flags |= ImGuiSelectableFlags_Disabled; + + m_enabled = value; + } + + void mvSelectable::draw(ImDrawList* drawlist, float x, float y) + { + + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::Selectable(m_label.c_str(), m_value.get(), m_flags, ImVec2((float)m_width, (float)m_height))) + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + + } + + void mvSelectable::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags, bool flip) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false); + + } + + void mvSelectable::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags, bool flip) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvSelectable.h b/DearPyGui/src/core/AppItems/basic/mvSelectable.h new file mode 100644 index 000000000..88100d519 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSelectable.h @@ -0,0 +1,62 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvSelectable, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Bool, 1); + class mvSelectable : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSelectable, add_selectable) + + MV_CREATE_CONSTANT(mvThemeCol_Selectable_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Selectable_Bg , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Selectable_BgHovered , ImGuiCol_HeaderHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Selectable_BgActive , ImGuiCol_HeaderActive , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Selectable_TextAlignX , ImGuiStyleVar_SelectableTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Selectable_TextAlignY , ImGuiStyleVar_SelectableTextAlign , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Selectable_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Selectable_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Selectable_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Selectable_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Selectable_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_Selectable_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Selectable_TextAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Selectable_TextAlignY , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Selectable_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Selectable_ItemSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvSelectable(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiSelectableFlags m_flags = ImGuiSelectableFlags_None; + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvSliderMulti.cpp b/DearPyGui/src/core/AppItems/basic/mvSliderMulti.cpp new file mode 100644 index 000000000..372e2cfec --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSliderMulti.cpp @@ -0,0 +1,258 @@ +#include "mvSliderMulti.h" +#include "mvTypeBases.h" +#include +#include "mvAppItem.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + + void mvSliderFloatMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0, 0.0, 0.0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Float, "min_value", "", "0.0"}, + {mvPythonDataType::Float, "max_value", "", "100.0"}, + {mvPythonDataType::String, "format", "", "'%.3f'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds slider for a 4 float values. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + + } + + void mvSliderIntMulti::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "default_value", "", "(0, 0, 0, 0)"}, + {mvPythonDataType::Integer, "size", "number of components", "4"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::String, "format", "", "'%d'"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds slider for a 4 int values. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + + } + + mvSliderFloatMulti::mvSliderFloatMulti(const std::string& name) + : mvFloat4PtrBase(name) + { + } + + void mvSliderFloatMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvSliderFloatMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 4, m_disabled_value); + + switch (m_size) + { + case 2: + if (ImGui::SliderFloat2(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 3: + if (ImGui::SliderFloat3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 4: + if (ImGui::SliderFloat4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + default: + break; + } + } + + mvSliderIntMulti::mvSliderIntMulti(const std::string& name) + : mvInt4PtrBase(name) + { + } + + void mvSliderIntMulti::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvSliderIntMulti::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) std::copy(m_value->data(), m_value->data() + 4, m_disabled_value); + + switch (m_size) + { + case 2: + if (ImGui::SliderInt2(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 3: + if (ImGui::SliderInt3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + case 4: + if (ImGui::SliderInt4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + break; + default: + break; + } + + } + + void mvSliderFloatMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvSliderFloatMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + + void mvSliderIntMulti::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvSliderIntMulti::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvSliderMulti.h b/DearPyGui/src/core/AppItems/basic/mvSliderMulti.h new file mode 100644 index 000000000..e0807e5df --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSliderMulti.h @@ -0,0 +1,174 @@ +#pragma once +#include "mvTypeBases.h" +#include +#include "mvModule_Core.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvSliderFloatMulti +// * mvSliderIntMulti +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvSliderFloat4 + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvSliderFloatMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float4, 1); + class mvSliderFloatMulti : public mvFloat4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSliderFloatMulti, add_slider_floatx) + + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_Grab , ImGuiCol_SliderGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_GrabActive , ImGuiCol_SliderGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloatx_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_GrabMinSize , ImGuiStyleVar_GrabMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloatx_GrabRounding , ImGuiStyleVar_GrabRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_Grab, mvColor( 61, 133, 224, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_GrabActive, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloatx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_InnerSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_InnerSpacingY, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_GrabMinSize ,10, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloatx_GrabRounding , 0, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvSliderFloatMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_min = 0.0f; + float m_max = 100.0f; + std::string m_format = "%.3f"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + int m_size = 4; + }; + + //----------------------------------------------------------------------------- + // mvSliderIntMulti + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvSliderIntMulti, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int4, 1); + class mvSliderIntMulti : public mvInt4PtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSliderIntMulti, add_slider_intx) + + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_Grab , ImGuiCol_SliderGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_GrabActive , ImGuiCol_SliderGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderIntx_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_GrabMinSize , ImGuiStyleVar_GrabMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderIntx_GrabRounding , ImGuiStyleVar_GrabRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_Grab, mvColor( 61, 133, 224, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_GrabActive, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderIntx_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_GrabMinSize ,10, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderIntx_GrabRounding , 0, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvSliderIntMulti(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_min = 0; + int m_max = 100; + std::string m_format = "%d"; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + int m_size = 4; + }; + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvSliderSingle.cpp b/DearPyGui/src/core/AppItems/basic/mvSliderSingle.cpp new file mode 100644 index 000000000..80270daba --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSliderSingle.cpp @@ -0,0 +1,257 @@ +#include "mvSliderSingle.h" +#include "mvTypeBases.h" +#include +#include "mvAppItem.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvSliderFloat::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "default_value", "", "0.0"}, + {mvPythonDataType::Float, "min_value", "", "0.0"}, + {mvPythonDataType::Float, "max_value", "", "100.0"}, + {mvPythonDataType::String, "format", "", "'%.3f'"}, + {mvPythonDataType::Bool, "vertical", "sets orientation to vertical", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","Height of a vertical slider", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds slider for a single float value. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + + } + + void mvSliderInt::InsertParser(std::map* parsers) + { + parsers->insert({ "add_slider_int", mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Integer, "min_value", "", "0"}, + {mvPythonDataType::Integer, "max_value", "", "100"}, + {mvPythonDataType::String, "format", "", "'%d'"}, + {mvPythonDataType::Bool, "vertical", "sets orientation to vertical", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","Height of a vertical slider", "0"}, + {mvPythonDataType::Bool, "no_input", "Disable CTRL+Click or Enter key allowing to input text directly into the widget", "False"}, + {mvPythonDataType::Bool, "clamped", "Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds slider for a single int value. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + + } + + mvSliderFloat::mvSliderFloat(const std::string& name) + : mvFloatPtrBase(name) + { + } + + void mvSliderFloat::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvSliderFloat::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (m_vertical) + { + if ((float)m_height < 1.0f) + m_height = 100; + if ((float)m_width < 1.0f) + m_width = 20; + + if (ImGui::VSliderFloat(m_label.c_str(), ImVec2((float)m_width, (float)m_height), m_enabled ? m_value.get() : &m_disabled_value, m_min, m_max, m_format.c_str())) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + else + { + if (ImGui::SliderFloat(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + } + + mvSliderInt::mvSliderInt(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvSliderInt::setEnabled(bool value) + { + if (value == m_enabled) + return; + + if (value) + m_flags = m_stor_flags; + + else + { + m_stor_flags = m_flags; + m_flags |= ImGuiSliderFlags_NoInput; + } + + m_enabled = value; + } + + void mvSliderInt::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!m_enabled) m_disabled_value = *m_value; + + if (m_vertical) + { + if ((float)m_height < 1.0f) + m_height = 100; + if ((float)m_width < 1.0f) + m_width = 20; + + if (ImGui::VSliderInt(m_label.c_str(), ImVec2((float)m_width, (float)m_height), m_enabled ? m_value.get() : &m_disabled_value, m_min, m_max, m_format.c_str())) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + } + else + { + if (ImGui::SliderInt(m_label.c_str(), m_enabled ? m_value.get() : &m_disabled_value, m_min, m_max, m_format.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + } + + void mvSliderFloat::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "vertical")) m_vertical = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToFloat(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvSliderFloat::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "vertical", ToPyBool(m_vertical)); + PyDict_SetItemString(dict, "min_value", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyFloat(m_max)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + + void mvSliderInt::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "vertical")) m_vertical = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_value")) m_min = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_value")) m_max = ToInt(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + flagop("clamped", ImGuiSliderFlags_ClampOnInput, m_stor_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_flags); + flagop("no_input", ImGuiSliderFlags_NoInput, m_stor_flags); + + } + + void mvSliderInt::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "format", ToPyString(m_format)); + PyDict_SetItemString(dict, "vertical", ToPyBool(m_vertical)); + PyDict_SetItemString(dict, "min_value", ToPyInt(m_min)); + PyDict_SetItemString(dict, "max_value", ToPyInt(m_max)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("clamped", ImGuiSliderFlags_ClampOnInput, m_flags); + checkbitset("no_input", ImGuiSliderFlags_NoInput, m_flags); + + } + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvSliderSingle.h b/DearPyGui/src/core/AppItems/basic/mvSliderSingle.h new file mode 100644 index 000000000..c7be377b1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvSliderSingle.h @@ -0,0 +1,176 @@ +#pragma once +#include "mvTypeBases.h" +#include +#include "mvModule_Core.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvSliderFloat +// * mvSliderInt +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvSliderFloat + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvSliderFloat, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvSliderFloat : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSliderFloat, add_slider_float) + + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_Grab , ImGuiCol_SliderGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_GrabActive , ImGuiCol_SliderGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderFloat_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_GrabMinSize , ImGuiStyleVar_GrabMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderFloat_GrabRounding , ImGuiStyleVar_GrabRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_Grab, mvColor( 61, 133, 224, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_GrabActive, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderFloat_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_GrabMinSize ,10, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderFloat_GrabRounding , 0, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvSliderFloat(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_min = 0.0f; + float m_max = 100.0f; + std::string m_format = "%.3f"; + bool m_vertical = false; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + + }; + + //----------------------------------------------------------------------------- + // mvSliderInt + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvSliderInt, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvSliderInt : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSliderInt, add_slider_int) + + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_Bg , ImGuiCol_FrameBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_BgHovered , ImGuiCol_FrameBgHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_BgActive , ImGuiCol_FrameBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_Grab , ImGuiCol_SliderGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_GrabActive , ImGuiCol_SliderGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_SliderInt_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_GrabMinSize , ImGuiStyleVar_GrabMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SliderInt_GrabRounding , ImGuiStyleVar_GrabRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_SliderInt_Text, mvColor(255, 255, 255, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_Bg, mvColor( 41, 74, 122, 138), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_BgHovered, mvColor( 66, 150, 250, 102), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_BgActive, mvColor( 66, 150, 250, 171), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_Grab, mvColor( 61, 133, 224, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_GrabActive, mvColor( 66, 150, 250, 255), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_Border, mvColor(110, 110, 128, 128), mvColor(128, 128, 128, 63)), + MV_ADD_CONSTANT(mvThemeCol_SliderInt_BorderShadow, mvColor( 0, 0, 0, 0), mvColor(128, 128, 128, 63)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_InnerSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_GrabMinSize ,10, 20), + MV_ADD_CONSTANT(mvThemeStyle_SliderInt_GrabRounding , 0, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvSliderInt(const std::string& name); + + void setEnabled(bool value) override; + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_min = 0; + int m_max = 100; + std::string m_format = "%d"; + bool m_vertical = false; + ImGuiInputTextFlags m_flags = ImGuiSliderFlags_None; + ImGuiInputTextFlags m_stor_flags = ImGuiSliderFlags_None; + }; + + +} diff --git a/DearPyGui/src/core/AppItems/basic/mvTabButton.cpp b/DearPyGui/src/core/AppItems/basic/mvTabButton.cpp new file mode 100644 index 000000000..7a8901bac --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvTabButton.cpp @@ -0,0 +1,100 @@ +#include "mvTabButton.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTabButton::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "no_reorder", "Disable reordering this tab or having another tab cross over this tab", "False"}, + {mvPythonDataType::Bool, "leading", "Enforce the tab position to the left of the tab bar (after the tab list popup button)", "False"}, + {mvPythonDataType::Bool, "trailing", "Enforce the tab position to the right of the tab bar (before the scrolling buttons)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "Disable tooltip for the given tab", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a tab button to a tab bar", "None", "Containers") }); + } + + mvTabButton::mvTabButton(const std::string& name) + : + mvAppItem(name) + { + } + + void mvTabButton::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::TabItemButton(m_label.c_str(), m_flags)) + mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_name, m_callback_data); + + } + + bool mvTabButton::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvTabBar) + return true; + + mvThrowPythonError(1000, "Tab button parent must be a tab bar."); + MV_ITEM_REGISTRY_ERROR("Tab button parent must be a tab bar."); + assert(false); + return false; + } + + void mvTabButton::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("no_reorder", ImGuiTabItemFlags_NoReorder, m_flags); + flagop("leading", ImGuiTabItemFlags_Leading, m_flags); + flagop("trailing", ImGuiTabItemFlags_Trailing, m_flags); + flagop("no_tooltip", ImGuiTabItemFlags_NoTooltip, m_flags); + + if (m_flags & ImGuiTabItemFlags_Leading && m_flags & ImGuiTabItemFlags_Trailing) + m_flags &= ~ImGuiTabItemFlags_Leading; + + } + + void mvTabButton::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("no_reorder", ImGuiTabBarFlags_Reorderable, m_flags); + checkbitset("leading", ImGuiTabItemFlags_Leading, m_flags); + checkbitset("trailing", ImGuiTabItemFlags_Trailing, m_flags); + checkbitset("no_tooltip", ImGuiTabItemFlags_NoTooltip, m_flags); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvTabButton.h b/DearPyGui/src/core/AppItems/basic/mvTabButton.h new file mode 100644 index 000000000..f84849ac1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvTabButton.h @@ -0,0 +1,65 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTabButton, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvTabButton : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTabButton, add_tab_button) + + MV_CREATE_CONSTANT(mvThemeCol_TabButton_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TabButton_Bg , ImGuiCol_Tab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TabButton_BgHovered , ImGuiCol_TabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TabButton_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TabButton_PopupBg , ImGuiCol_PopupBg , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_TabButton_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TabButton_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TabButton_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TabButton_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabButton_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabButton_Bg, mvColor( 41, 74, 122, 138)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabButton_BgHovered, mvColor( 66, 150, 250, 102)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabButton_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabButton_PopupBg, mvColor( 20, 20, 20, 240)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_TabButton_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_TabButton_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_TabButton_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_TabButton_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvTabButton(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiTabItemFlags m_flags = ImGuiTabItemFlags_None; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvText.cpp b/DearPyGui/src/core/AppItems/basic/mvText.cpp new file mode 100644 index 000000000..7f862d2d7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvText.cpp @@ -0,0 +1,143 @@ +#include "mvText.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvText::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "wrap", "number of characters until wraping", "-1"}, + {mvPythonDataType::FloatList, "color", "color of the text (rgba)", "(-1, 0, 0, 0)"}, + {mvPythonDataType::Bool, "bullet", "makes the text bulleted", "False"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "default_value", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds text", "None", "Adding Widgets") }); + } + + void mvLabelText::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "default_value", "", "''"}, + {mvPythonDataType::FloatList, "color", "", "(-1, 0, 0, 0)"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "data source for shared data", "''"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds text with a label. Useful for output values.", "None", "Adding Widgets") }); + } + + mvText::mvText(const std::string& name) + : + mvStringPtrBase(name) + { + *m_value = name; + } + + void mvText::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_color.r > 0.0f) + ImGui::PushStyleColor(ImGuiCol_Text, m_color.toVec4()); + + if (m_wrap >= 0) + ImGui::PushTextWrapPos((float)m_wrap); + + if (m_bullet) + ImGui::Bullet(); + + //ImGui::Text("%s", m_value.c_str()); + ImGui::TextUnformatted(m_value->c_str()); // this doesn't have a buffer size limit + + if (m_wrap >= 0) + ImGui::PopTextWrapPos(); + + if (m_color.r > 0.0f) + ImGui::PopStyleColor(); + + } + + mvLabelText::mvLabelText(const std::string& name) + : + mvStringPtrBase(name) + { + } + + void mvLabelText::draw(ImDrawList* drawlist, float x, float y) + { + + if (m_color.r > 0.0f) + { + ImGui::PushStyleColor(ImGuiCol_Text, m_color.toVec4()); + + ImGui::TextUnformatted(m_value->c_str()); + + ImGui::PopStyleColor(); + + ImGui::SameLine(); + + mvImGuiThemeScope scope(this); + ImGui::TextUnformatted(m_specificedlabel.c_str()); + } + + else + { + mvImGuiThemeScope scope(this); + ImGui::LabelText(m_specificedlabel.c_str(), m_value->c_str()); + } + + } + + void mvText::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "wrap")) m_wrap = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "bullet")) m_bullet = ToBool(item); + + } + + void mvText::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "wrap", ToPyInt(m_wrap)); + PyDict_SetItemString(dict, "bullet", ToPyBool(m_bullet)); + } + + void mvLabelText::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + } + + void mvLabelText::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/basic/mvText.h b/DearPyGui/src/core/AppItems/basic/mvText.h new file mode 100644 index 000000000..e6157ca14 --- /dev/null +++ b/DearPyGui/src/core/AppItems/basic/mvText.h @@ -0,0 +1,111 @@ +#pragma once + +#include "mvTypeBases.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvText +// * mvLabelText +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvText + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1); + class mvText : public mvStringPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvText, add_text) + + MV_CREATE_CONSTANT(mvThemeCol_Text_Text, ImGuiCol_Text, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Text_Text, mvColor(255, 255, 255, 255)) + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvText(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + mvColor m_color = {-1.0f, 0.0f, 0.0f, 1.0f}; + int m_wrap = -1; + bool m_bullet = false; + + }; + + //----------------------------------------------------------------------------- + // mvLabelText + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvLabelText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1); + class mvLabelText : public mvStringPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvLabelText, add_label_text) + + MV_CREATE_CONSTANT(mvThemeCol_LabelText_Text , ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_LabelText_PaddingX , ImGuiCol_TitleBg, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_LabelText_PaddingY , ImGuiCol_TitleBg, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingX , 14L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingY , 14L, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_LabelText_Text, mvColor(255, 255, 255, 255)) + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_LabelText_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_LabelText_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvLabelText(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + mvColor m_color = { -1.0f, 0.0f, 0.0f, 1.0f}; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvAboutWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvAboutWindow.cpp new file mode 100644 index 000000000..d5a12aa57 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvAboutWindow.cpp @@ -0,0 +1,163 @@ +#include "mvAboutWindow.h" +#include "mvTypeBases.h" +#include "mvAppItem.h" +#include "mvInput.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvAboutWindow::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "-1"}, + {mvPythonDataType::Integer, "height", "", "-1"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "False"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Creates an about window.", + "None", "Containers") }); + } + + mvAboutWindow::mvAboutWindow(const std::string& name) + : mvBaseWindowAppitem(name) + { + m_windowflags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings; + } + + void mvAboutWindow::draw(ImDrawList* drawlist, float x, float y) + { + if (!prerender()) + return; + + ImGui::Text("Dear PyGui %s", mvApp::GetVersion()); + ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "Authors"); + ImGui::BulletText("Jonathan Hoffstadt"); + ImGui::BulletText("Preston Cothren"); + ImGui::Text("Dear PyGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "Corporate"); + ImGui::BulletText("Anthony Tanbakuchi"); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "Partners"); + ImGui::BulletText("Dean Keinan"); + ImGui::BulletText("He Lingfeng"); + ImGui::BulletText("Anthony Doupe"); + ImGui::BulletText("Ray Heasman"); + ImGui::BulletText("Marco Studer"); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "ImPlot"); + ImGui::Text("ImPlot Author Evan Pezent."); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "imnodes"); + ImGui::Text("imnodes Author Johann Muszynski."); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), "Dear ImGui"); + ImGui::Text("Dear ImGui Author Omar Cornut and all Dear ImGui contributors."); + ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); + + static bool show_config_info = false; + ImGui::Checkbox("Config/Build Information", &show_config_info); + if (show_config_info) + { + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + + bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); + ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove); + if (copy_to_clipboard) + { + ImGui::LogToClipboard(); + ImGui::LogText("```\n"); // Back quotes will make the text appears without formatting when pasting to GitHub + } + + ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + ImGui::Separator(); + ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert)); + ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); + ImGui::Text("define: _WIN32"); + ImGui::Text("define: _WIN64"); + #if defined (_WIN32) + ImGui::Text("define: _MSC_VER=%d", _MSC_VER); + #endif + ImGui::Separator(); + ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); + ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL"); + ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad"); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) ImGui::Text(" NavEnableSetMousePos"); + if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) ImGui::Text(" NavNoCaptureKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange"); + if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); + if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); + if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); + if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); + if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); + ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); + if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); + if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); + ImGui::Separator(); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); + ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); + ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + ImGui::Separator(); + ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); + ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); + ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y); + ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding); + ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize); + ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y); + ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y); + + if (copy_to_clipboard) + { + ImGui::LogText("\n```\n"); + ImGui::LogFinish(); + } + ImGui::EndChildFrame(); + } + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != m_name) + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", m_name) }); + } + + ImGui::End(); + + } + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvAboutWindow.h b/DearPyGui/src/core/AppItems/composite/mvAboutWindow.h new file mode 100644 index 000000000..8e56c1d40 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvAboutWindow.h @@ -0,0 +1,36 @@ +#pragma once +#include "mvTypeBases.h" +#include "mvModule_Core.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvAboutWindow, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvAboutWindow : public mvBaseWindowAppitem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvAboutWindow, add_about_window) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvAboutWindow(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + }; + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvDataGrid.cpp b/DearPyGui/src/core/AppItems/composite/mvDataGrid.cpp new file mode 100644 index 000000000..e508b2aee --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDataGrid.cpp @@ -0,0 +1,1078 @@ +#include "mvDataGrid.h" +#include "mvApp.h" +#include "mvAppLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDataGrid::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::StringList, "headers"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "200"}, + {mvPythonDataType::Bool, "hide_headers", "Hide headers of the table", "False"}, + {mvPythonDataType::Bool, "show","Attempt to render", "True"} + }, "Adds data grid.", "None", "Tables") }); + + parsers->insert({ "set_grid_data", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::ListStrList, "data"} + }, "Overwrites data grid data.", "None", "Tables") }); + + parsers->insert({ "get_grid_data", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + }, "Gets data grid data.", "List[List[str]]", "Tables") }); + + parsers->insert({ "set_grid_headers", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::StringList, "headers"}, + }, "Sets a data grid's headers.", "None", "Tables") }); + + parsers->insert({ "clear_data_grid", mvPythonParser({ + {mvPythonDataType::String, "data_grid"} + }, "Clears data in a data grid", "None", "Tables") }); + + parsers->insert({ "add_grid_column", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::StringList, "column"}, + }, "Adds a column to the end of a data grid.", "None", "Tables") }); + + parsers->insert({ "insert_grid_column", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "column_index"}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::StringList, "column"}, + }, "Inserts a column into a data grid.", "None", "Tables") }); + + parsers->insert({ "delete_grid_column", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "column"} + }, "Delete a column in a data grid.", "None", "Tables") }); + + parsers->insert({ "add_grid_row", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::StringList, "row"}, + }, "Adds a row to the end of a data grid.", "None", "Tables") }); + + parsers->insert({ "insert_grid_row", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "row_index"}, + {mvPythonDataType::StringList, "row"}, + }, "Inserts a row into a data grid.", "None", "Tables") }); + + parsers->insert({ "delete_grid_row", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "row"} + }, "Delete a row in a data grid.", "None", "Tables") }); + + parsers->insert({ "get_grid_item", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "row"}, + {mvPythonDataType::Integer, "column"} + }, "Gets a data grid's cell value.", "str", "Tables") }); + + parsers->insert({ "set_grid_item", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "row"}, + {mvPythonDataType::Integer, "column"}, + {mvPythonDataType::String, "value"}, + }, "Sets a data grid's cell value.", "None", "Tables") }); + + parsers->insert({ "get_grid_selections", mvPythonParser({ + {mvPythonDataType::String, "data_grid"} + }, "Retrieves data from storage.", "List[List[int]]", "Tables") }); + + parsers->insert({ "set_grid_selection", mvPythonParser({ + {mvPythonDataType::String, "data_grid"}, + {mvPythonDataType::Integer, "row"}, + {mvPythonDataType::Integer, "column"}, + {mvPythonDataType::Bool, "value"}, + }, "Sets a data grid's cell selection value.", "None", "Tables") }); + } + + mvDataGrid::mvDataGrid(const std::string& name) + : mvAppItem(name) + { + m_height = 200; + m_hide_headers = false; + } + + void mvDataGrid::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "hide_headers")) m_hide_headers = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "headers")) + { + m_headers = ToStringVect(item); + m_columns = m_headers.size(); + } + } + + void mvDataGrid::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "hide_headers", ToPyBool(m_hide_headers)); + } + + bool mvDataGrid::isIndexValid(int row, int column) const + { + if (column < 0 || row < 0) + { + ThrowPythonException("Data Grid index must be a positive integer."); + return false; + } + + if (static_cast(column) > m_columns + 1 || static_cast(row) > m_values.size() + 1) + { + ThrowPythonException("Data Grid indices out of range."); + return false; + } + + return true; + } + + void mvDataGrid::updateHashValues() + { + m_hashValues.clear(); + + m_hashValues = m_values; + + for (size_t i = 0; i < m_hashValues.size(); i++) + { + for (size_t j = 0; j < m_hashValues[i].size(); j++) + m_hashValues[i][j] = m_hashValues[i][j] + "##" + m_name + "-" + std::to_string(i) + "-" + std::to_string(j); + + for (size_t j = m_hashValues[i].size(); j < m_columns; j++) + m_hashValues[i].push_back("##" + m_name + "-" + std::to_string(i) + "-" + std::to_string(j)); + } + } + + void mvDataGrid::setGridItem(int row, int column, const std::string& value) + { + if (!isIndexValid(row, column)) + return; + + m_values[row][column] = value; + m_hashValues[row][column] = value + "##" + m_name + "-" + std::to_string(row) + "-" + std::to_string(column); + + } + + std::string mvDataGrid::getGridItem(int row, int column) const + { + if (!isIndexValid(row, column)) + return ""; + + return m_values[row][column]; + } + + void mvDataGrid::setSelection(int row, int column, bool value) + { + if (!isIndexValid(row, column)) + return; + + m_selections[{row, column}] = value; + } + + void mvDataGrid::setPyValue(PyObject* value) + { + auto values = ToVectVectString(value, m_name + " requires a list/tuple or list/tuple of strings."); + + m_values = std::move(values); + + if (!m_values.empty()) // just in case value is set to an empty list + { + while (m_headers.size() > m_columns) + m_headers.pop_back(); + } + + updateHashValues(); + + m_selections.clear(); + } + + PyObject* mvDataGrid::getPyValue() + { + return ToPyList(m_values); + } + + PyObject* mvDataGrid::getSelections() const + { + int selectionCount = 0; + + for (auto& item : m_selections) + if (item.second) selectionCount++; + + std::vector> selections; + + for (auto& item : m_selections) + { + if (item.second) + selections.emplace_back(item.first.first, item.first.second); + } + + return ToPyList(selections); + } + + void mvDataGrid::addHeaders(const std::vector& headers) + { + m_headers = headers; + m_columns = headers.size(); + + if (m_values.empty()) + return; + + if (m_columns > m_values[0].size()) + { + for (auto& row : m_values) + row.emplace_back(""); + } + else if (m_columns < m_values[0].size()) + { + m_columns = m_values[0].size(); + while (m_headers.size() < m_columns) + m_headers.emplace_back("Header"); + } + updateHashValues(); + } + + void mvDataGrid::addRow(const std::vector& row) + { + m_values.push_back(row); + + while (m_values.back().size() < m_headers.size()) + m_values.back().emplace_back(""); + + while (m_values.back().size() > m_headers.size()) + m_values.back().pop_back(); + + updateHashValues(); + } + + void mvDataGrid::addColumn(const std::string& name, const std::vector& column) + { + m_headers.push_back(name); + + if (column.size() > m_values.size()) + { + for (unsigned i = 0; i < column.size(); i++) + { + // row exists + if (i < m_values.size()) + { + m_values[i].emplace_back(column[i]); + continue; + } + + // row does not exist + m_values.push_back({}); + for (unsigned j = 0; j < m_headers.size() - 1; j++) + m_values[i].emplace_back(""); + + m_values[i].emplace_back(column[i]); + } + } + + else + { + size_t index = 0; + for (auto& row : m_values) + { + if (index >= column.size()) + { + row.emplace_back(""); + index++; + continue; + + } + + row.push_back(column[index]); + index++; + } + } + + m_columns++; + + updateHashValues(); + } + + void mvDataGrid::insertColumn(int column_index, const std::string& name, const std::vector& column) + { + if (!isIndexValid(0, column_index)) + return; + + if (static_cast(column_index) == m_headers.size()) + { + addColumn(name, column); + return; + } + + auto oldValues = m_values; + auto oldHeaders = m_headers; + + m_values.clear(); + m_headers.clear(); + m_columns++; + + for (size_t i = 0; i < m_columns; i++) + { + if (i < static_cast(column_index)) + m_headers.push_back(oldHeaders[i]); + else if (i == static_cast(column_index)) + m_headers.push_back(name); + else + m_headers.push_back(oldHeaders[i - 1]); + } + + if (column.size() > oldValues.size()) + { + for (size_t i = 0; i < column.size(); i++) + { + if (i < oldValues.size()) + { + std::vector row; + for (size_t j = 0; j < oldHeaders.size(); j++) + { + if (j == static_cast(column_index)) + { + row.push_back(column[i]); + continue; + } + + if (j > static_cast(column_index)) + row.push_back(oldValues[i][j - 1]); + + else + row.push_back(oldValues[i][j]); + + } + row.push_back(oldValues[i].back()); + + m_values.push_back(row); + } + + else + { + std::vector row; + for (size_t j = 0; j < oldHeaders.size(); j++) + { + if (j == static_cast(column_index)) + { + row.push_back(column[i]); + continue; + } + row.push_back(""); + } + row.push_back(""); + + m_values.push_back(row); + } + } + } + + else + { + for (size_t i = 0; i < oldValues.size(); i++) + { + std::vector row; + for (size_t j = 0; j < oldHeaders.size(); j++) + { + if (j == static_cast(column_index)) + { + if (i >= column.size()) + row.emplace_back(""); + else + row.push_back(column[i]); + continue; + } + + if (j > static_cast(column_index)) + row.push_back(oldValues[i][j - 1]); + + else + row.push_back(oldValues[i][j]); + + } + row.push_back(oldValues[i].back()); + + m_values.push_back(row); + } + } + + updateHashValues(); + + // update selections + std::map, bool> oldSelection = m_selections; + m_selections.clear(); + + for (auto& item : oldSelection) + { + + if (item.first.second >= column_index) + m_selections[{item.first.first, item.first.second + 1}] = item.second; + + else + m_selections[item.first] = item.second; + + } + + } + + void mvDataGrid::insertRow(int row_index, const std::vector& row) + { + if (!isIndexValid(row_index, 0)) + return; + + if (static_cast(row_index) >= m_values.size()) + { + addRow(row); + return; + } + + auto oldValues = m_values; + + m_values.clear(); + + for (size_t i = 0; i < oldValues.size(); i++) + { + if (i == static_cast(row_index)) + { + m_values.push_back(row); + continue; + } + + if(i > static_cast(row_index)) + m_values.push_back(oldValues[i-1]); + else + m_values.push_back(oldValues[i]); + } + m_values.push_back(oldValues.back()); + + while (m_values[row_index].size() < m_headers.size()) + m_values[row_index].emplace_back(""); + + while (m_values.back().size() > m_headers.size()) + m_values.back().pop_back(); + + updateHashValues(); + + // update selections + std::map, bool> oldSelection = m_selections; + m_selections.clear(); + + for (auto& item : oldSelection) + { + + if (item.first.first >= row_index) + m_selections[{item.first.first + 1, item.first.second}] = item.second; + + else + m_selections[item.first] = item.second; + + } + + } + + void mvDataGrid::deleteRow(int row) + { + if (!isIndexValid(row, 0)) + return ; + + auto oldValues = m_values; + + m_values.clear(); + + int index = 0; + for (auto& item : oldValues) + { + + if (index == row) + { + index++; + continue; + } + m_values.push_back(item); + + index++; + + } + + updateHashValues(); + + // update selections + std::map, bool> oldSelection = m_selections; + m_selections.clear(); + + for (auto& item : oldSelection) + { + if (item.first.first == row) + continue; + + else if (item.first.first < row) + m_selections[item.first] = item.second; + + + else if (item.first.first > row) + m_selections[{item.first.first - 1, item.first.second}] = item.second; + } + + } + + void mvDataGrid::deleteColumn(int column) + { + if (!isIndexValid(0, column)) + return; + + if (static_cast(column) >= m_headers.size()) + { + ThrowPythonException("Column to delete does not exist."); + return; + } + + auto oldValues = m_values; + auto oldHeaders = m_headers; + + m_values.clear(); + m_headers.clear(); + m_columns--; + + for (size_t i = 0; i < oldHeaders.size(); i++) + { + if (i == static_cast(column)) + continue; + m_headers.push_back(oldHeaders[i]); + } + + //for (int i = 0; i < oldValues.size(); i++) + for (auto& oldvalue : oldValues) + { + std::vector row; + for (size_t j = 0; j < oldHeaders.size(); j++) + { + if (j == static_cast(column)) + continue; + row.push_back(oldvalue[j]); + } + + m_values.push_back(row); + } + + updateHashValues(); + + // update selections + std::map, bool> oldSelection = m_selections; + m_selections.clear(); + for (auto& item : oldSelection) + { + if (item.first.second == column) + continue; + + else if (item.first.second < column) + m_selections[item.first] = item.second; + + + else if (item.first.second > column) + m_selections[{item.first.first, item.first.second - 1}] = item.second; + } + + } + + void mvDataGrid::clearGrid() + { + m_selections.clear(); + m_hashValues.clear(); + m_values.clear(); + } + + void mvDataGrid::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::BeginTable(m_name.c_str(), m_columns, + ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) + { + if (!m_hide_headers) + { + for (auto& header : m_headers) + ImGui::TableSetupColumn(header.c_str()); + ImGui::TableHeadersRow(); + //ImGui::TableNextColumn(); + } + + for (size_t i = 0; i < m_hashValues.size(); i++) + { + ImGui::TableNextRow(); + for (size_t j = 0; j < m_hashValues[i].size(); j++) + { + ImGui::TableSetColumnIndex(j); + if (ImGui::Selectable(m_hashValues[i][j].c_str(), m_selections[{i, j}])) + { + m_selections[{i, j}] = !m_selections[{i, j}]; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, + m_name, m_callback_data); + } + } + + } + + ImGui::EndTable(); + } + + + } + + PyObject* mvDataGrid::get_grid_data(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + + if (!(mvApp::GetApp()->getParsers())["get_grid_data"].parse(args, kwargs, __FUNCTION__, &grid)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(std::string(grid)); + + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " table does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a table."); + return GetPyNone(); + } + + return static_cast(item.get())->getPyValue(); + } + + PyObject* mvDataGrid::set_grid_data(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + PyObject* value; + + if (!(mvApp::GetApp()->getParsers())["set_grid_data"].parse(args, kwargs, __FUNCTION__, &grid, &value)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(std::string(grid)); + + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + static_cast(item.get())->setPyValue(value); + + return GetPyNone(); + } + + PyObject* mvDataGrid::set_grid_headers(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + PyObject* headers; + + if (!(mvApp::GetApp()->getParsers())["set_grid_headers"].parse(args, kwargs, __FUNCTION__, &grid, &headers)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + auto prow = ToStringVect(headers); + mvDataGrid* atable = static_cast(item.get()); + + atable->addHeaders(prow); + + return GetPyNone(); + } + + PyObject* mvDataGrid::clear_data_grid(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + + if (!(mvApp::GetApp()->getParsers())["clear_data_grid"].parse(args, kwargs, __FUNCTION__, &grid)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + atable->clearGrid(); + Py_RETURN_NONE; + } + + PyObject* mvDataGrid::get_grid_item(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int row; + int column; + + if (!(mvApp::GetApp()->getParsers())["get_grid_item"].parse(args, kwargs, __FUNCTION__, &grid, &row, + &column)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + return Py_BuildValue("s", atable->getGridItem(row, column).c_str()); + + } + + PyObject* mvDataGrid::set_grid_item(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int row; + int column; + const char* value; + + if (!(mvApp::GetApp()->getParsers())["set_grid_item"].parse(args, kwargs, __FUNCTION__, &grid, &row, + &column, &value)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + atable->setGridItem(row, column, value); + + return GetPyNone(); + } + + PyObject* mvDataGrid::get_grid_selections(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + + if (!(mvApp::GetApp()->getParsers())["get_grid_selections"].parse(args, kwargs, __FUNCTION__, &grid)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + return atable->getSelections(); + } + + PyObject* mvDataGrid::set_grid_selection(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int row; + int column; + int value; + + if (!(mvApp::GetApp()->getParsers())["set_grid_selection"].parse(args, kwargs, __FUNCTION__, &grid, &row, + &column, &value)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + atable->setSelection(row, column, value); + + return GetPyNone(); + } + + PyObject* mvDataGrid::add_grid_column(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + const char* name; + PyObject* column; + + if (!(mvApp::GetApp()->getParsers())["add_grid_column"].parse(args, kwargs, __FUNCTION__, &grid, &name, &column)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " table does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a table."); + return GetPyNone(); + } + + auto pcolumn = ToStringVect(column); + + mvDataGrid* atable = static_cast(item.get()); + atable->addColumn(name, pcolumn); + + return GetPyNone(); + } + + PyObject* mvDataGrid::insert_grid_column(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int column_index; + const char* name; + PyObject* column; + + if (!(mvApp::GetApp()->getParsers())["insert_grid_column"].parse(args, kwargs, __FUNCTION__, &grid, &column_index, &name, &column)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + auto prow = ToStringVect(column); + + mvDataGrid* atable = static_cast(item.get()); + atable->insertColumn(column_index, name, prow); + + return GetPyNone(); + } + + PyObject* mvDataGrid::delete_grid_column(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int column; + + if (!(mvApp::GetApp()->getParsers())["delete_grid_column"].parse(args, kwargs, __FUNCTION__, &grid, &column)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + atable->deleteColumn(column); + + return GetPyNone(); + } + + PyObject* mvDataGrid::add_grid_row(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + PyObject* row; + + if (!(mvApp::GetApp()->getParsers())["add_grid_row"].parse(args, kwargs, __FUNCTION__, &grid, &row)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + auto prow = ToStringVect(row); + mvDataGrid* atable = static_cast(item.get()); + if (atable->getColumnCount() == 0) + { + std::vector headers; + for (size_t i = 0; i < prow.size(); i++) + headers.emplace_back("Header" + std::to_string(i)); + atable->addHeaders(headers); + } + atable->addRow(prow); + + return GetPyNone(); + } + + PyObject* mvDataGrid::insert_grid_row(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int row_index; + PyObject* row; + + if (!(mvApp::GetApp()->getParsers())["insert_grid_row"].parse(args, kwargs, __FUNCTION__, &grid, &row_index, &row)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + auto prow = ToStringVect(row); + mvDataGrid* atable = static_cast(item.get()); + if (atable->getColumnCount() == 0) + { + std::vector headers; + for (size_t i = 0; i < prow.size(); i++) + headers.emplace_back("Header" + std::to_string(i)); + atable->addHeaders(headers); + } + atable->insertRow(row_index, prow); + + return GetPyNone(); + } + + PyObject* mvDataGrid::delete_grid_row(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* grid; + int row; + + if (!(mvApp::GetApp()->getParsers())["delete_grid_row"].parse(args, kwargs, __FUNCTION__, &grid, &row)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(grid); + if (item == nullptr) + { + std::string message = grid; + ThrowPythonException(message + " grid does not exist."); + return GetPyNone(); + } + + if (item->getType() != mvAppItemType::mvDataGrid) + { + std::string message = grid; + ThrowPythonException(message + " is not a grid."); + return GetPyNone(); + } + + mvDataGrid* atable = static_cast(item.get()); + atable->deleteRow(row); + + return GetPyNone(); + } + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvDataGrid.h b/DearPyGui/src/core/AppItems/composite/mvDataGrid.h new file mode 100644 index 000000000..f5a5cec8d --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDataGrid.h @@ -0,0 +1,141 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvApp.h" +#include "mvAppLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDataGrid, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvDataGrid : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDataGrid, add_data_grid) + + MV_CREATE_EXTRA_COMMAND(set_grid_headers); + MV_CREATE_EXTRA_COMMAND(set_grid_data); + MV_CREATE_EXTRA_COMMAND(get_grid_data); + MV_CREATE_EXTRA_COMMAND(clear_data_grid); + MV_CREATE_EXTRA_COMMAND(get_grid_item); + MV_CREATE_EXTRA_COMMAND(set_grid_item); + MV_CREATE_EXTRA_COMMAND(get_grid_selections); + MV_CREATE_EXTRA_COMMAND(set_grid_selection); + MV_CREATE_EXTRA_COMMAND(add_grid_column); + MV_CREATE_EXTRA_COMMAND(insert_grid_column); + MV_CREATE_EXTRA_COMMAND(delete_grid_column); + MV_CREATE_EXTRA_COMMAND(add_grid_row); + MV_CREATE_EXTRA_COMMAND(insert_grid_row); + MV_CREATE_EXTRA_COMMAND(delete_grid_row); + + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_HeaderBg , ImGuiCol_TableHeaderBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_RowBg , ImGuiCol_TableRowBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_RowBgAlt , ImGuiCol_TableRowBgAlt , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_Item , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_ItemHovered , ImGuiCol_HeaderHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_ItemActive , ImGuiCol_HeaderActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_BorderStrong , ImGuiCol_TableBorderStrong , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_BorderLight , ImGuiCol_TableBorderLight , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_BorderHovered , ImGuiCol_SeparatorHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DataGrid_BorderActive , ImGuiCol_SeparatorActive , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_CellPaddingX , ImGuiStyleVar_CellPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_CellPaddingY , ImGuiStyleVar_CellPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_ItemTextAlignX , ImGuiStyleVar_SelectableTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DataGrid_ItemTextAlignY , ImGuiStyleVar_SelectableTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(set_grid_headers); + MV_ADD_EXTRA_COMMAND(set_grid_data); + MV_ADD_EXTRA_COMMAND(get_grid_data); + MV_ADD_EXTRA_COMMAND(clear_data_grid); + MV_ADD_EXTRA_COMMAND(get_grid_item); + MV_ADD_EXTRA_COMMAND(set_grid_item); + MV_ADD_EXTRA_COMMAND(get_grid_selections); + MV_ADD_EXTRA_COMMAND(set_grid_selection); + MV_ADD_EXTRA_COMMAND(add_grid_column); + MV_ADD_EXTRA_COMMAND(insert_grid_column); + MV_ADD_EXTRA_COMMAND(delete_grid_column); + MV_ADD_EXTRA_COMMAND(add_grid_row); + MV_ADD_EXTRA_COMMAND(insert_grid_row); + MV_ADD_EXTRA_COMMAND(delete_grid_row); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_HeaderBg, mvColor( 48, 48, 51, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_RowBg, mvColor( 0, 0, 0, 0)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_RowBgAlt, mvColor(255, 255, 255, 15)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_Item, mvColor( 66, 150, 250, 79)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_ItemHovered, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_ItemActive, mvColor( 15, 135, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_BorderStrong, mvColor( 79, 79, 89, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_BorderLight, mvColor( 59, 59, 64, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_BorderHovered, mvColor( 26, 102, 191, 199)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DataGrid_BorderActive, mvColor( 26, 102, 191, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_CellPaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_CellPaddingY , 2, 20), + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_ItemTextAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DataGrid_ItemTextAlignY , 0, 1), + MV_END_STYLE_CONSTANTS + + public: + + mvDataGrid(const std::string& name); + + // table operations + void setGridItem (int row, int column, const std::string& value); + void setSelection (int row, int column, bool value); + void addHeaders (const std::vector& headers); + void addRow (const std::vector& row); + void insertRow (int row_index, const std::vector& row); + void deleteRow (int row); + void addColumn (const std::string& name, const std::vector& column); + void insertColumn (int column_index, const std::string& name, const std::vector& column); + void deleteColumn (int column); + void clearGrid (); + int getColumnCount() const { return (int)m_columns; } + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + [[nodiscard]] std::string getGridItem (int row, int column) const; + [[nodiscard]] PyObject* getSelections() const; + + void setPyValue(PyObject* value) override; + [[nodiscard]] PyObject* getPyValue() override; + void draw(ImDrawList* drawlist, float x, float y) override; + + private: + + [[nodiscard]] bool isIndexValid(int row, int column) const; + void updateHashValues(); + + private: + + std::map, bool> m_selections; + std::vector m_headers; + std::vector> m_hashValues; + std::vector> m_values; + size_t m_columns; + bool m_hide_headers; + + // new table api items + ImGuiTableFlags m_flags = 0; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvDebugWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvDebugWindow.cpp new file mode 100644 index 000000000..e28cb636e --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDebugWindow.cpp @@ -0,0 +1,362 @@ +#include "mvDebugWindow.h" +#include "mvEvents.h" +#include +#include "mvApp.h" +#include "mvInput.h" +#include "mvTextureStorage.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + mvDebugWindow::mvDebugWindow(const std::string& name) + : mvBaseWindowAppitem(name) + { + m_width = 700; + m_height = 500; + + for (const auto& item : mvModule_Core::GetModuleParsers()) + m_commands.emplace_back(item.first, item.second.getDocumentation()); + } + + void mvDebugWindow::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "700"}, + {mvPythonDataType::Integer, "height", "", "500"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "False"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Creates a debug window.", + "None", "Containers") }); + } + + static void DebugItem(const char* label, const char* item) + { + ImGui::Text("%s", label); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%s", item); + } + + static void DebugItem(const char* label, float x) + { + ImGui::Text("%s", label); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%s", std::to_string(x).c_str()); + } + + static void DebugItem(const char* label, float x, float y) + { + ImGui::Text("%s", label); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%s", (std::to_string(x) + ", " + std::to_string(y)).c_str()); + } + + void mvDebugWindow::renderItem(mvAppItem* item) + { + + if (mvAppItem::DoesItemHaveFlag(item, MV_ITEM_DESC_CONTAINER)) + { + std::string container = item->m_name + "*"; + + ImGui::PushID(item); + if (ImGui::TreeNodeEx(container.c_str())) + { + + auto stringPos = item->m_name.find_first_not_of("###"); + if (stringPos != std::string::npos && stringPos > 0) + { + ImGui::PushID(item); + if (ImGui::Selectable(item->m_name.substr().erase(0, 2).c_str(), + item->m_name == m_selectedItem && ImGui::GetID(item->m_name.substr().erase(0, 2).c_str()) == m_selectedID)) + { + m_selectedItem = item->m_name; + m_selectedID = ImGui::GetID(item->m_name.substr().erase(0, 2).c_str()); + } + ImGui::PopID(); + } + else + { + ImGui::PushID(item); + if (ImGui::Selectable(item->m_name.c_str(), + item->m_name == m_selectedItem && ImGui::GetID(item->m_name.c_str()) == m_selectedID)) + { + m_selectedItem = item->m_name; + m_selectedID = ImGui::GetID(item->m_name.c_str()); + } + ImGui::PopID(); + } + + for (auto child : item->m_children[1]) + renderItem(child.get()); + + ImGui::TreePop(); + } + ImGui::PopID(); + } + else + { + auto stringPos = item->m_name.find_first_not_of("###"); + if (stringPos != std::string::npos && stringPos > 0) + { + ImGui::PushID(item); + if (ImGui::Selectable(item->m_name.substr().erase(0, 2).c_str(), + item->m_name == m_selectedItem && ImGui::GetID(item->m_name.substr().erase(0, 2).c_str()) == m_selectedID)) + { + m_selectedItem = item->m_name; + m_selectedID = ImGui::GetID(item->m_name.substr().erase(0, 2).c_str()); + } + ImGui::PopID(); + } + else + { + ImGui::PushID(item); + if (ImGui::Selectable(item->m_name.c_str(), + item->m_name == m_selectedItem && ImGui::GetID(item->m_name.c_str()) == m_selectedID)) + { + m_selectedItem = item->m_name; + m_selectedID = ImGui::GetID(item->m_name.c_str()); + } + ImGui::PopID(); + } + + } + + + } + + void mvDebugWindow::draw(ImDrawList* drawlist, float x, float y) + { + if (!prerender()) + return; + + static char ts[6] = "True"; + static char fs[6] = "False"; + static std::string commandstring = "set_theme(\"Light\")"; + + ImGuiIO& io = ImGui::GetIO(); + + static auto app = mvApp::GetApp(); + + if (ImGui::BeginTabBar("Main Tabbar")) + { + if (ImGui::BeginTabItem("App State")) + { + + ImGui::PushItemWidth(200); + ImGui::BeginGroup(); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + ImGui::Text("%d active allocations", io.MetricsActiveAllocations); + DebugItem("DearPyGui Version: ", mvApp::GetVersion()); + DebugItem("ImGui Version: ", IMGUI_VERSION); + + + ImGui::EndGroup(); + ImGui::PopItemWidth(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Input Polling")) + { + + ImGui::PushItemWidth(200); + ImGui::BeginGroup(); + + auto mousepos = mvInput::getMousePosition(); + DebugItem("Active Window: ", mvApp::GetApp()->getItemRegistry().getActiveWindow().c_str()); + DebugItem("Local Mouse Position:", mousepos.x, mousepos.y); + DebugItem("Global Mouse Position:", io.MousePos.x, io.MousePos.y); + DebugItem("Plot Mouse Position:", mvInput::getPlotMousePosition().x, mvInput::getPlotMousePosition().y); + DebugItem("Mouse Drag Delta:", mvInput::getMouseDragDelta().x, mvInput::getMouseDragDelta().y); + DebugItem("Mouse Drag Threshold:", mvInput::getMouseDragThreshold()); + + ImGui::Spacing(); + ImGui::Spacing(); + ImGui::Text("ImGui State Inputs"); + + ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); + ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); + + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (0x%X) (%.02f secs)", i, i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } + ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } + + ImGui::EndGroup(); + ImGui::PopItemWidth(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("App Item Layout")) + { + auto selectedItem = mvApp::GetApp()->getItemRegistry().getItem(m_selectedItem); + std::string parentName; + + if (selectedItem == nullptr) + selectedItem = mvApp::GetApp()->getItemRegistry().getBackWindows()[0]; + + if (selectedItem->m_parentPtr) + parentName = selectedItem->m_parentPtr->m_name; + + std::string width = std::to_string(selectedItem->m_width); + std::string height = std::to_string(selectedItem->m_height); + + std::string sizex = std::to_string(selectedItem->getState().getItemRectSize().x); + std::string sizey = std::to_string(selectedItem->getState().getItemRectSize().y); + + ImGui::BeginGroup(); + + if (ImGui::ArrowButton("Move Up", ImGuiDir_Up)) + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + mvApp::GetApp()->getItemRegistry().moveItemUp(m_selectedItem); + }); + + ImGui::SameLine(); + if (ImGui::ArrowButton("Move Down", ImGuiDir_Down)) + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + mvApp::GetApp()->getItemRegistry().moveItemDown(m_selectedItem); + }); + ImGui::SameLine(); + if (ImGui::Button("Delete")) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + mvApp::GetApp()->getItemRegistry().deleteItem(m_selectedItem, false); + m_selectedItem = ""; + }); + } + ImGui::SameLine(); + if (ImGui::Button("Show")) + mvApp::GetApp()->getItemRegistry().getItem(m_selectedItem)->show(); + ImGui::SameLine(); + if (ImGui::Button("Hide")) + mvApp::GetApp()->getItemRegistry().getItem(m_selectedItem)->hide(); + + ImGui::PushItemWidth(200); + DebugItem("Item Name:", m_selectedItem.c_str()); + //DebugItem("Item Type:", selectedItem->getStringType().c_str()); + DebugItem("Container:", mvAppItem::DoesItemHaveFlag(selectedItem.get(), MV_ITEM_DESC_CONTAINER) ? ts : fs); + DebugItem("Item Parent:", parentName.c_str()); + DebugItem("Item Width:", width.c_str()); + DebugItem("Item Height:", height.c_str()); + DebugItem("Item Size x:", sizex.c_str()); + DebugItem("Item Size y:", sizey.c_str()); + DebugItem("Item Show:", selectedItem->m_show ? ts : fs); + DebugItem("Item Visible:", selectedItem->getState().isItemVisible() ? ts : fs); + DebugItem("Item Hovered:", selectedItem->getState().isItemHovered() ? ts : fs); + DebugItem("Item Active:", selectedItem->getState().isItemActive() ? ts : fs); + DebugItem("Item Focused:", selectedItem->getState().isItemFocused() ? ts : fs); + DebugItem("Item Clicked:", selectedItem->getState().isItemClicked() ? ts : fs); + DebugItem("Item Edited:", selectedItem->getState().isItemEdited() ? ts : fs); + DebugItem("Item Activated:", selectedItem->getState().isItemActivated() ? ts : fs); + DebugItem("Item Deactivated:", selectedItem->getState().isItemDeactivated() ? ts : fs); + DebugItem("Item DeactivatedAfterEdit:", selectedItem->getState().isItemDeactivatedAfterEdit() ? ts : fs); + DebugItem("Item ToggledOpen:", selectedItem->getState().isItemToogledOpen() ? ts : fs); + ImGui::EndGroup(); + ImGui::PopItemWidth(); + ImGui::SameLine(); + + ImGui::BeginChild("TreeChild", ImVec2(-1.0f, -1.0f), true); + for (auto window : mvApp::GetApp()->getItemRegistry().getFrontWindows()) + renderItem(window.get()); + for (auto window : mvApp::GetApp()->getItemRegistry().getBackWindows()) + renderItem(window.get()); + ImGui::EndChild(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Commands##debug")) + { + + static size_t commandselection = 0; + const char* commanddoc = m_commands[commandselection].second.c_str(); + static ImGuiTextFilter filter; + filter.Draw(); + + ImGui::PushItemWidth(-1); + ImGui::BeginChild("CommandsChild##debug", ImVec2(400.0f, 400.0f), true); + ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 1.0f, 0.0f, 1.0f }); + for (size_t i = 0; igetCallbackRegistry().submitCallback([=]() { + PyRun_SimpleString(command.c_str()); + }); + + } + + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "debug##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("debug##standard")) }); + + } + + ImGui::End(); + + } + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvDebugWindow.h b/DearPyGui/src/core/AppItems/composite/mvDebugWindow.h new file mode 100644 index 000000000..8d1989f5d --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDebugWindow.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvModule_Core.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDebugWindow, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvDebugWindow : public mvBaseWindowAppitem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDebugWindow, add_debug_window) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDebugWindow(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void renderItem(mvAppItem* item); + + private: + + std::string m_selectedItem; + ImGuiID m_selectedID = 0u; + std::vector> m_commands; + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvDocWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvDocWindow.cpp new file mode 100644 index 000000000..58c2281ce --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDocWindow.cpp @@ -0,0 +1,657 @@ +#include "mvDocWindow.h" +#include +#include "mvApp.h" +#include "mvModule_Core.h" +#include "mvInput.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDocWindow::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "-1"}, + {mvPythonDataType::Integer, "height", "", "-1"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "True"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Creates a documentation window.", + "None", "Containers") }); + } + + static void ColorText(const char* item) + { + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotLinesHovered), "%s", item); + } + + static void CodeColorText(const char* item) + { + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), "%s", item); + } + + static void WidgetTableEntry(const char* widget, const char* container, const char* callback, const char* source, const char* desc) + { + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget), widget); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), container); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered), callback); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_PlotLinesHovered), source); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_Text), desc); ImGui::NextColumn(); + } + + mvDocWindow::mvDocWindow(const std::string& name) + : mvBaseWindowAppitem(name) + { + m_width = 700; + m_height = 500; + setup(); + } + + void mvDocWindow::setup() + { + + for (const auto& item : m_constants) + { + m_cconstants.push_back(item.first.c_str()); + m_constantsValues.emplace_back("Constant with a value of " + std::to_string(item.second)); + } + + for (const auto& item : m_docmap) + { + m_commands.emplace_back(item.first.c_str(), item.second.getDocumentation()); + + std::string category = item.second.getCategory(); + + if (category == "App") + { + m_app.push_back(item.first.c_str()); + m_docApp.push_back(item.second.getDocumentation()); + } + + else if (category == "Logging") + { + m_logging.push_back(item.first.c_str()); + m_docLogging.push_back(item.second.getDocumentation()); + } + + else if (category == "Adding Widgets") + { + m_widgets.push_back(item.first.c_str()); + m_docWidgets.push_back(item.second.getDocumentation()); + } + + else if (category == "Widget Commands") + { + m_widgetsCommands.push_back(item.first.c_str()); + m_docWidgetsCommands.push_back(item.second.getDocumentation()); + } + + else if (category == "Containers") + { + m_containers.push_back(item.first.c_str()); + m_docContainers.push_back(item.second.getDocumentation()); + } + + else if (category == "Drawing") + { + m_drawing.push_back(item.first.c_str()); + m_docDrawing.push_back(item.second.getDocumentation()); + } + + else if (category == "Plotting") + { + m_plotting.push_back(item.first.c_str()); + m_docPlotting.push_back(item.second.getDocumentation()); + } + + else if (category == "Tables") + { + m_tables.push_back(item.first.c_str()); + m_docTables.push_back(item.second.getDocumentation()); + } + + else if (category == "Themes and Styles") + { + m_themes.push_back(item.first.c_str()); + m_docThemes.push_back(item.second.getDocumentation()); + } + + else if (category == "Input Polling") + { + m_inputs.push_back(item.first.c_str()); + m_docInputs.push_back(item.second.getDocumentation()); + } + + else if (category == "Standard Windows") + { + m_windows.push_back(item.first.c_str()); + m_docWindows.push_back(item.second.getDocumentation()); + } + + } + + + } + + void mvDocWindow::draw(ImDrawList* drawlist, float x, float y) + { + mvFontScope fscope(this); + + if (!prerender()) + return; + + if (ImGui::BeginTabBar("Main Tabbar##doc")) + { + if (ImGui::BeginTabItem("Help##doc")) + { + + + ColorText("ABOUT THIS GUIDE:"); + ImGui::BulletText("Sections below cover the basic aspects of Dear PyGui Core."); + ImGui::BulletText("This document can be found by calling the \"show_documentation\" command."); + ImGui::BulletText("Additional information on specific commands can be found in the commands tab."); + ImGui::BulletText("The complete documentation can be found at: https://hoffstadt.github.io/DearPyGui/"); + + if (ImGui::CollapsingHeader("Logging and Console Output")) + { + + ColorText("LOGGING"); + ImGui::BulletText("In order to show the logger window, you must use the \"show_logger\" command."); + ImGui::BulletText("In order to filter what is displayed, you can set the log level."); + ImGui::BulletText("By Default the logger is set to log level mvDebug."); + ImGui::BulletText("Can be set like \"set_log_level(mvINFO)\""); + ImGui::BulletText("The log levels are:"); + + ImGui::Columns(3); + ImGui::Separator(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget), "level"); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget), "constant"); ImGui::NextColumn(); + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget), "command"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("TRACE"); ImGui::NextColumn(); + ColorText("mvTRACE"); ImGui::NextColumn(); + CodeColorText("log('some message')"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("DEBUG"); ImGui::NextColumn(); + ColorText("mvDEBUG"); ImGui::NextColumn(); + CodeColorText("log_debug('some message')"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("INFO"); ImGui::NextColumn(); + ColorText("mvINFO"); ImGui::NextColumn(); + CodeColorText("log_info('some message')"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("WARNING"); ImGui::NextColumn(); + ColorText("mvWARNING"); ImGui::NextColumn(); + CodeColorText("log_warning('some message')"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("ERROR"); ImGui::NextColumn(); + ColorText("mvERROR"); ImGui::NextColumn(); + CodeColorText("log_error('some message')"); ImGui::NextColumn(); + + ImGui::Separator(); + CodeColorText("OFF"); ImGui::NextColumn(); + ColorText("mvOFF"); ImGui::NextColumn(); ImGui::NextColumn(); + + ImGui::Columns(1); + + + } + + + if (ImGui::CollapsingHeader("Widgets")) + { + + ColorText("WIDGETS:"); + ImGui::Columns(5); + WidgetTableEntry("WIDGET", "CONTAINER", "CALLBACK", "SOURCE TYPE", "DESCRIPTION"); + WidgetTableEntry("button", "", "yes", "", "button"); + WidgetTableEntry("checkbox", "", "yes", "bool", "checkbox"); + WidgetTableEntry("child", "yes", "", "bool", "embedded window"); + WidgetTableEntry("collapsing header", "yes", "", "bool", "collapsible header"); + WidgetTableEntry("color button", "", "yes", "", "color button"); + WidgetTableEntry("color edit3", "", "yes", "color", "rgb color editing widget"); + WidgetTableEntry("color edit4", "", "yes", "color", "rgba color editing widget"); + WidgetTableEntry("color picker3", "", "yes", "color", "rgb color picking widget"); + WidgetTableEntry("color picker4", "", "yes", "color", "rgba color picking widget"); + WidgetTableEntry("columns", "yes", "", "", "a layout widget"); + WidgetTableEntry("combo", "", "yes", "string", "dropdown combo box"); + WidgetTableEntry("date picker", "", "yes", "time", "data selector widget"); + WidgetTableEntry("drag float", "", "yes", "float", "drag widget"); + WidgetTableEntry("drag float2", "", "yes", "[float, float]", "drag widget"); + WidgetTableEntry("drag float3", "", "yes", "[float, float, float]", "drag widget"); + WidgetTableEntry("drag float4", "", "yes", "[float, float, float, float]", "drag widget"); + WidgetTableEntry("drag int", "", "yes", "int", "drag widget"); + WidgetTableEntry("drag int2", "", "yes", "[int, int]", "drag widget"); + WidgetTableEntry("drag int3", "", "yes", "[int, int, int]", "drag widget"); + WidgetTableEntry("drag int4", "", "yes", "[int, int, int, int]", "drag widget"); + WidgetTableEntry("drawing", "", "", "", "embeddable canvas"); + WidgetTableEntry("dummy", "", "", "", "spacing widget"); + WidgetTableEntry("group", "yes", "", "", "grouping/layout widget"); + WidgetTableEntry("image", "", "", "", "image widget"); + WidgetTableEntry("image button", "", "yes", "", "clickable image"); + WidgetTableEntry("indent", "", "", "float", "layout widget, indents until unindent called"); + WidgetTableEntry("input float", "", "yes", "float", "input widget"); + WidgetTableEntry("input float2", "", "yes", "[float, float]", "input widget"); + WidgetTableEntry("input float3", "", "yes", "[float, float, float]", "input widget"); + WidgetTableEntry("input float4", "", "yes", "[float, float, float, float]", "input widget"); + WidgetTableEntry("input int", "", "yes", "int", "input widget"); + WidgetTableEntry("input int2", "", "yes", "[int, int]", "input widget"); + WidgetTableEntry("input int3", "", "yes", "[int, int, int]", "input widget"); + WidgetTableEntry("input int4", "", "yes", "[int, int, int, int]", "input widget"); + WidgetTableEntry("input text", "", "yes", "string", "input widget"); + WidgetTableEntry("listbox", "", "yes", "int", "item list widget"); + WidgetTableEntry("logger", "", "", "", "logger widget"); + WidgetTableEntry("managed columns", "yes", "", "", "layout widget"); + WidgetTableEntry("menu", "yes", "", "bool", "menu widget"); + WidgetTableEntry("menu bar", "yes", "", "bool", "menu bar widget"); + WidgetTableEntry("menu item", "yes", "", "bool", "menu item widget"); + WidgetTableEntry("next column", "", "", "", "layout widget"); + WidgetTableEntry("popup", "yes", "", "bool", "popup window"); + WidgetTableEntry("progress bar", "", "", "float", "progress bar widget"); + WidgetTableEntry("radio button", "", "yes", "int", "set of radio buttons"); + WidgetTableEntry("same line", "", "", "", "layout widget, places next item on same line"); + WidgetTableEntry("selectable", "", "yes", "bool", "selectable widget"); + WidgetTableEntry("seperator", "", "", "", "horizontal line"); + WidgetTableEntry("simple plot", "", "", "List[float]", "simple plot for data visualization"); + WidgetTableEntry("slider float", "", "yes", "float", "slider widget"); + WidgetTableEntry("slider float2", "", "yes", "[float, float]", "slider widget"); + WidgetTableEntry("slider float3", "", "yes", "[float, float, float]", "slider widget"); + WidgetTableEntry("slider float4", "", "yes", "[float, float, float, float]", "slider widget"); + WidgetTableEntry("slider int", "", "yes", "int", "slider widget"); + WidgetTableEntry("slider int2", "", "yes", "[int, int]", "slider widget"); + WidgetTableEntry("slider int3", "", "yes", "[int, int, int]", "slider widget"); + WidgetTableEntry("slider int4", "", "yes", "[int, int, int, int]", "slider widget"); + WidgetTableEntry("spacing", "", "", "int", "layout widget, vertical spacing"); + WidgetTableEntry("tab", "yes", "", "bool", "layout widget, tab widget"); + WidgetTableEntry("tab bar", "yes", "", "string", "layout widget, tab container"); + WidgetTableEntry("tab button", "", "yes", "", "button for tab bars"); + WidgetTableEntry("table", "", "yes", "", "simple table widget"); + WidgetTableEntry("text", "", "", "string", "text widget"); + WidgetTableEntry("time picker", "", "yes", "time", "time selecting widget"); + WidgetTableEntry("tooltip", "yes", "", "bool", "window that appears on hovering another item"); + WidgetTableEntry("tree node", "yes", "", "bool", "collapsing node widget"); + WidgetTableEntry("window", "yes", "", "", "new window widget"); + + ImGui::Columns(1); + + } + + if (ImGui::CollapsingHeader("Widget Basics")) + { + ColorText("BASICS:"); + ImGui::BulletText("Widgets are added with a command of the form \"add_*\""); + ImGui::BulletText("Some widgets can contain other widgets."); + ImGui::Separator(); + + ColorText("WIDGETS NAMING:"); + ImGui::BulletText("Widgets MUST have unique names."); + ImGui::BulletText("Most widgets require you to give a name with the exception of:"); + ImGui::Indent(); + CodeColorText("seperator"); + CodeColorText("spacing"); + CodeColorText("same_line"); + CodeColorText("indent"); + CodeColorText("unindent"); + CodeColorText("next_column"); + ImGui::Unindent(); + ImGui::BulletText("The above widget's names are optional (they are auto generated)."); + ImGui::BulletText("If a widget uses the name to display text (i.e. button) and you need"); + ImGui::Text(" multiple buttons to display the same text, you can do the following:"); + ImGui::Indent(); + CodeColorText("add_button('Press me')"); + CodeColorText("add_button('Press me##123')"); + CodeColorText("add_button('Some unique name', label='Press me')"); + ImGui::Unindent(); + ImGui::Separator(); + + ColorText("ADDING WIDGETS:"); + ImGui::BulletText("There are 2 methods for adding widgets."); + ImGui::Indent(); + ImGui::BulletText("METHOD 1 (RECOMMENDED):"); + ImGui::Indent(); + ImGui::Text("You simply call the add_* commands, while creating a nested hierarchy by"); + ImGui::Text("placing widgets between the add_* and end of container widgets."); + ImGui::Text("With this method, widgets automatically know which containers they"); + ImGui::Text("belong to. Example:"); + ImGui::Spacing(); + CodeColorText("add_child(...)"); + CodeColorText("add_button(...) # belongs to child"); + CodeColorText("add_group(...) # belongs to child"); + CodeColorText("add_button(...) # belongs to group"); + CodeColorText("add_button(...) # belongs to group"); + CodeColorText("end()"); + CodeColorText("end()"); + ImGui::Unindent(); + ImGui::BulletText("METHOD 2:"); + ImGui::Indent(); + ImGui::Text("You add widgets to their parent containers using the \"parent\" keyword."); + ImGui::Text("Containers are created by calling their add_* command followed immediately"); + ImGui::Text("by an end command."); + ImGui::Text("Example:"); + ImGui::Spacing(); + CodeColorText("add_child(...)"); + CodeColorText("end()"); + CodeColorText("add_button(..., parent='childname')"); + ImGui::Unindent(); + ImGui::Unindent(); + + } + + if (ImGui::CollapsingHeader("Data Storage")) + { + + ColorText("USE CASE"); + ImGui::BulletText("To store data for later usage, just use the following commands:"); + ImGui::Indent(); + CodeColorText("add_data"); + CodeColorText("get_data"); + ImGui::Unindent(); + ImGui::Separator(); + + } + + if (ImGui::CollapsingHeader("Value Storage")) + { + ColorText("BASICS"); + ImGui::BulletText("There are 2 use cases for the data storage system:"); + ImGui::Indent(); + ImGui::BulletText("1. For widgets to use the same underlying data (i.e. both modify the same data)"); + ImGui::BulletText("2. To store data for use at a later time or in a different callback."); + ImGui::Unindent(); + ImGui::Separator(); + + ColorText("USE CASE 1"); + ImGui::BulletText("To share the underlying data of multiple widgets, just use the 'source' keyword when adding the widget."); + ImGui::BulletText("Ensure the underlying data structures match or it will not work."); + ImGui::Separator(); + + ColorText("USE CASE 2"); + ImGui::BulletText("To store data for later usage, just use the following commands:"); + ImGui::Indent(); + CodeColorText("add_value"); + CodeColorText("get_value"); + CodeColorText("set_value"); + ImGui::Unindent(); + ImGui::Separator(); + + } + + if (ImGui::CollapsingHeader("Callbacks")) + { + ColorText("BASICS:"); + ImGui::BulletText("Callbacks are functions that are ran when some event occurs."); + ImGui::BulletText("There are currently 3 'types' of callbacks used in Dear PyGui:"); + ImGui::Indent(); + CodeColorText("Render - ran every frame"); + CodeColorText("Inputs - ran when mouse/keyboard events occurr"); + CodeColorText("Widgets - ran when certain widgets are interacted with"); + ImGui::Unindent(); + ImGui::BulletText("Notes:"); + ImGui::Indent(); + ImGui::BulletText("The 'set_*_callback' commands take a string with the name of the callback to use."); + ImGui::BulletText("Always ran on the same thread as the GUI."); + ImGui::BulletText("Should NOT be computationally expensive (because of the note above),"); + ImGui::Text("otherwise you may see a drop in frame rate."); + ImGui::Unindent(); + ImGui::Separator(); + + ColorText("RENDER CALLBACK:"); + ImGui::BulletText("Useful for live updating (for example a progress bar)"); + ImGui::BulletText("The command is 'set_render_callback(...)'"); + ImGui::BulletText("Notes:"); + ImGui::Indent(); + ImGui::BulletText("Should take the following form:"); + ImGui::Indent(); + CodeColorText("def callbackname(sender, data):"); + CodeColorText(" ..."); + ImGui::Unindent(); + ImGui::BulletText("The data parameter depends on the actual callback. Check the documentation."); + ImGui::Unindent(); + ImGui::Separator(); + + ColorText("INPUT CALLBACKS:"); + ImGui::BulletText("Useful for capturing key strokes, making iteractive drawings, etc."); + ImGui::BulletText("Commands take the form of 'set_*_callback(...)'"); + ImGui::BulletText("Most should take the following form:"); + ImGui::Indent(); + CodeColorText("def callbackname(sender, data):"); + CodeColorText(" ..."); + ImGui::Unindent(); + ImGui::BulletText("The 'sender' parameter is the name of widget the callback was sent from."); + ImGui::BulletText("The data parameter depends on the actual callback. Check the documentation."); + ImGui::Separator(); + + ColorText("WIDGET CALLBACKS:"); + ImGui::BulletText("Useful for performing actions during widget interactions."); + ImGui::BulletText("Set using the 'callback' keyword."); + ImGui::BulletText("Should take the following form:"); + ImGui::Indent(); + CodeColorText("def callbackname(sender, data):"); + CodeColorText(" ..."); + ImGui::Unindent(); + ImGui::BulletText("The 'sender' parameter is the name of widget the callback was sent from."); + + } + + if (ImGui::CollapsingHeader("Input Polling")) + { + ImGui::BulletText("During any callback, you can poll information about the mouse and keyboard."); + ImGui::BulletText("The following commands are used for this:"); + ImGui::Indent(); + CodeColorText("get_mouse_pos"); + CodeColorText("is_key_pressed"); + CodeColorText("is_key_released"); + CodeColorText("is_key_down"); + CodeColorText("is_mouse_button_dragging"); + CodeColorText("is_mouse_button_down"); + CodeColorText("is_mouse_button_clicked"); + CodeColorText("is_mouse_button_double_clicked"); + CodeColorText("is_mouse_button_released"); + ImGui::Unindent(); + + } + + if (ImGui::CollapsingHeader("Drawings")) + { + ColorText("BASICS:"); + ImGui::BulletText("The drawing API is a low-level drawing API useful for simple graphics."); + ImGui::BulletText("Drawings are added using the 'add_drawing(...)' command."); + ImGui::BulletText("All drawing commands' first argument can either refer to a drawing widget,"); + ImGui::Text(" window, '##FOREGROUND', or '##BACKGROUND'."); + ImGui::Separator(); + + ColorText("TAGS:"); + ImGui::BulletText("To efficiently update a drawing, you should use the tag system (as opposed to clearing and redrawing)"); + ImGui::BulletText("All draw commands of the form 'draw_*' accept an optional tag argument."); + ImGui::BulletText("The tag argument is a string that acts as an indentifier for the draw item."); + ImGui::BulletText("You can update previously submitted draw commands using 'modify_draw_command'."); + } + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Commands##doc")) + { + ImGui::BeginGroup(); + ImGui::SetNextItemWidth(500); + ImGui::ListBox("Category", &categorySelection, &m_categories[0], 12, 7); + + ImGui::SetNextItemWidth(500); + ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32(255, 0, 0, 100)); + if (categorySelection == 0) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_app.data(), (int)m_app.size(), 30)) + m_doc = m_docApp[selection]; + } + + else if (categorySelection == 1) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_logging.data(), (int)m_logging.size(), 30)) + m_doc = m_docLogging[selection]; + } + + else if (categorySelection == 2) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_widgets.data(), (int)m_widgets.size(), 30)) + m_doc = m_docWidgets[selection]; + } + + else if (categorySelection == 3) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_widgetsCommands.data(), (int)m_widgetsCommands.size(), 30)) + m_doc = m_docWidgetsCommands[selection]; + } + + else if (categorySelection == 4) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_containers.data(), (int)m_containers.size(), 30)) + m_doc = m_docContainers[selection]; + } + + else if (categorySelection == 5) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_drawing.data(), (int)m_drawing.size(), 30)) + m_doc = m_docDrawing[selection]; + } + + else if (categorySelection == 6) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_plotting.data(), (int)m_plotting.size(), 30)) + m_doc = m_docPlotting[selection]; + } + + else if (categorySelection == 7) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_tables.data(), (int)m_tables.size(), 30)) + m_doc = m_docTables[selection]; + } + + else if (categorySelection == 8) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_themes.data(), (int)m_themes.size(), 30)) + m_doc = m_docThemes[selection]; + } + + else if (categorySelection == 9) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_inputs.data(), (int)m_inputs.size(), 30)) + m_doc = m_docInputs[selection]; + } + + else if (categorySelection == 10) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_windows.data(), (int)m_windows.size(), 30)) + m_doc = m_docWindows[selection]; + } + else if (categorySelection == 11) + { + static int selection = 0; + if (ImGui::ListBox("Commands", &selection, m_cconstants.data(), (int)m_cconstants.size(), 30)) + m_doc = m_constantsValues[selection].c_str(); + } + + ImGui::PopStyleColor(); + ImGui::EndGroup(); + + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 255, 100)); + ImGui::BeginChild("DocChild", ImVec2(0, 0), true); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + 400); + ImGui::Text("%s", m_doc); + ImGui::PopTextWrapPos(); + ImGui::EndChild(); + ImGui::PopStyleColor(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Search Commands##doc")) + { + + static size_t commandselection = 0; + const char* commanddoc = m_commands[commandselection].second.c_str(); + static ImGuiTextFilter filter; + filter.Draw(); + + ImGui::PushItemWidth(300); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); + ImGui::BeginChild("CommandsChild##debug", ImVec2(500.0f, 0), true); + + for (size_t i = 0; i < m_commands.size(); i++) + { + auto& item = m_commands[i]; + + if (filter.PassFilter(item.first.c_str())) + { + if (ImGui::Selectable(item.first.c_str(), i == commandselection)) + commandselection = i; + } + } + ImGui::PopStyleColor(); + ImGui::EndChild(); + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 255, 100)); + ImGui::BeginChild("CommandsDoc##debug", ImVec2(0, 0), true); + ImGui::PushTextWrapPos(500); + ImGui::Text("%s", commanddoc); + ImGui::PopStyleColor(); + ImGui::PopTextWrapPos(); + ImGui::EndChild(); + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "documentation##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("documentation##standard")) }); + + } + + ImGui::End(); + } + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvDocWindow.h b/DearPyGui/src/core/AppItems/composite/mvDocWindow.h new file mode 100644 index 000000000..342f95300 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvDocWindow.h @@ -0,0 +1,90 @@ +#pragma once +#include +#include +#include +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDocWindow, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvDocWindow : public mvBaseWindowAppitem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDocWindow, add_doc_window) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDocWindow(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + void setup(); + + private: + + int categorySelection = 0; + const char* m_doc = "None"; + + const char* m_categories[12] = { + "App", + "Logging", + "Adding Widgets", + "Widget Commands", + "Containers", + "Drawing", + "Plotting", + "Tables", + "Themes and Styles", + "Input Polling", + "Standard Windows", + "Constants", + }; + + std::vector m_app; + std::vector m_widgets; + std::vector m_widgetsCommands; + std::vector m_containers; + std::vector m_drawing; + std::vector m_plotting; + std::vector m_tables; + std::vector m_inputs; + std::vector m_windows; + std::vector m_logging; + std::vector m_themes; + std::vector m_cconstants; + + std::vector m_docApp; + std::vector m_docWidgets; + std::vector m_docWidgetsCommands; + std::vector m_docDrawing; + std::vector m_docPlotting; + std::vector m_docTables; + std::vector m_docInputs; + std::vector m_docWindows; + std::vector m_docLogging; + std::vector m_docThemes; + std::vector m_docContainers; + + std::vector> m_commands; + const std::vector>& m_constants = mvModule_Core::GetModuleConstants(); + std::vector m_constantsValues; + const std::map& m_docmap = mvModule_Core::GetModuleParsers(); + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvFileDialog.cpp b/DearPyGui/src/core/AppItems/composite/mvFileDialog.cpp new file mode 100644 index 000000000..d470f7abc --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvFileDialog.cpp @@ -0,0 +1,114 @@ +#include "mvFileDialog.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvFileDialog::InsertParser(std::map* parsers) + { + parsers->insert({ "open_file_dialog", mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::Callable, "callback", "function to call on completion", "None"}, + {mvPythonDataType::String, "extensions", "filters items with extensions i.e '.*, .py'", "''"}, + }, "Opens an 'open file' dialog.") }); + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::Callable, "callback", "function to call on completion", "None"}, + }, "Opens a select directory dialog.") }); + } + + mvFileDialog::mvFileDialog() : mvBaseWindowAppitem("filedialog") + { + } + + bool mvFileDialog::prerender2() + { + return true; + } + + void mvFileDialog::setCallback(mvCallable callback) + { + m_callback2 = callback; + } + + void mvFileDialog::draw(ImDrawList* drawlist, float x, float y) + { + if (!prerender2()) + return; + + mvFontScope fscope(this); + + // display + if (ImGuiFileDialog::Instance()->Display("ChooseFileDlgKey", ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings, ImVec2(500, 600))) + { + + // action if OK + if (ImGuiFileDialog::Instance()->IsOk()) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + mvApp::GetApp()->getCallbackRegistry().runCallback(m_callback2, "File Dialog", ToPyList({ ImGuiFileDialog::Instance()->GetCurrentPath(), + ImGuiFileDialog::Instance()->FileNameBuffer })); + + // action + if (m_callback2) + Py_XDECREF(m_callback2); + m_callback2 = nullptr; + }); + + } + // close + ImGuiFileDialog::Instance()->Close(); + m_show = false; + } + } + + PyObject* mvFileDialog::select_directory_dialog(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback = nullptr; + + if (!(mvApp::GetApp()->getParsers())["select_directory_dialog"].parse(args, kwargs, __FUNCTION__, &callback)) + return GetPyNone(); + + if (callback) + Py_XINCREF(callback); + + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + ImGuiFileDialog::Instance()->OpenModal("ChooseFileDlgKey", "Choose Directory", 0, "."); + auto window = mvApp::GetApp()->getItemRegistry().getItem("filedialog"); + auto dialog = static_cast(window.get()); + dialog->setCallback(callback); + window->show(); + }); + + return GetPyNone(); + } + + PyObject* mvFileDialog::open_file_dialog(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback = nullptr; + const char* extensions = ".*"; + + if (!(mvApp::GetApp()->getParsers())["open_file_dialog"].parse(args, kwargs, __FUNCTION__, + &callback, &extensions)) + return GetPyNone(); + + if (callback) + Py_XINCREF(callback); + + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + ImGuiFileDialog::Instance()->OpenModal("ChooseFileDlgKey", "Choose File", extensions, "."); + auto window = mvApp::GetApp()->getItemRegistry().getItem("filedialog"); + auto dialog = static_cast(window.get()); + + dialog->setCallback(callback); + window->show(); + }); + + return GetPyNone(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvFileDialog.h b/DearPyGui/src/core/AppItems/composite/mvFileDialog.h new file mode 100644 index 000000000..71b5d783b --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvFileDialog.h @@ -0,0 +1,54 @@ +#pragma once +#include "mvTypeBases.h" +#include "mvApp.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvFileDialog, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvFileDialog : public mvBaseWindowAppitem + { + public: + + static void InsertParser(std::map* parsers); + + //MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvFileDialog, open_file_dialog) + static constexpr const long s_internal_type = (long)mvAppItemType::mvFileDialog; + static constexpr const char* const s_internal_id = "mvAppItemType::mvFileDialog"; + static constexpr const char* const s_command = "open_file_dialog"; + mvAppItemType getType() const override { return mvAppItemType::mvFileDialog; }\ + int getTarget() const override { return mvItemTypeMap<(int)mvAppItemType::mvFileDialog>::target; } + int getDescFlags() const override { return mvItemTypeMap<(int)mvAppItemType::mvFileDialog>::flags; } + StorageValueTypes getValueType() const override { return mvItemTypeMap<(int)mvAppItemType::mvFileDialog>::value_type; } + static PyObject* open_file_dialog(PyObject* self, PyObject* args, PyObject* kwargs); + static PyMethodDef GetMethodDefinition() { return { s_command, (PyCFunction)open_file_dialog, METH_VARARGS | METH_KEYWORDS, mvApp::GetApp()->getParsers()[s_command].getDocumentation() }; } + + MV_CREATE_EXTRA_COMMAND(select_directory_dialog); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(select_directory_dialog); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvFileDialog(); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool prerender2 (); + void setCallback(mvCallable callback); + + private: + + mvCallable m_callback2 = nullptr; + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvLogger.cpp b/DearPyGui/src/core/AppItems/composite/mvLogger.cpp new file mode 100644 index 000000000..3f18ce445 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvLogger.cpp @@ -0,0 +1,627 @@ +#include "mvLogger.h" +#include +#include "mvInput.h" +#include "mvCore.h" +#include "mvGlobalIntepreterLock.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +typedef std::chrono::high_resolution_clock clock_; +typedef std::chrono::duration > second_; + +namespace Marvel { + + void mvLoggerItem::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "log_level", "", "1"}, + {mvPythonDataType::Bool, "auto_scroll", "auto scroll", "True"}, + {mvPythonDataType::Bool, "auto_scroll_button", "show auto scroll button", "True"}, + {mvPythonDataType::Bool, "clear_button", "show clear button", "True"}, + {mvPythonDataType::Bool, "copy_button", "show copy button", "True"}, + {mvPythonDataType::Bool, "filter", "show filter", "True"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "autosize_x", "", "False"}, + {mvPythonDataType::Bool, "autosize_y", "", "False"}, + + }, "Adds a logging widget.", "None", "Adding Widgets") }); + + parsers->insert({ "get_log_level", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Returns the log level.", "int", "Logging") }); + + parsers->insert({ "clear_log", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Clears the logger.", "None", "Logging") }); + + parsers->insert({ "set_log_level", mvPythonParser({ + {mvPythonDataType::Integer, "level"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Sets the log level.", "None", "Logging") }); + + parsers->insert({ "log", mvPythonParser({ + {mvPythonDataType::Object, "message"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "level", "logger widget", "'TRACE'"}, + {mvPythonDataType::String, "logger", "logger widget", "''"} + }, "Logs a trace level log.", "None", "Logging") }); + + parsers->insert({ "log_debug", mvPythonParser({ + {mvPythonDataType::Object, "message"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Logs a debug level log.", "None", "Logging") }); + + parsers->insert({ "log_info", mvPythonParser({ + {mvPythonDataType::Object, "message"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Logs a info level log.", "None", "Logging") }); + + parsers->insert({ "log_warning", mvPythonParser({ + {mvPythonDataType::Object, "message"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Logs a warning level log.", "None", "Logging") }); + + parsers->insert({ "log_error", mvPythonParser({ + {mvPythonDataType::Object, "message"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "logger", "logger widget", "''"}, + }, "Logs a error level log.", "None", "Logging") }); + + parsers->insert({ "show_logger", mvPythonParser({ + }, "Shows the logging window. The Default log level is Trace", "None", "Standard Windows") }); + + parsers->insert({ "set_logger_window_title", mvPythonParser({ + {mvPythonDataType::String, "title"} + }, "Sets the title of the logger window.") + }); + } + +#if defined (_WIN32) + std::chrono::steady_clock::time_point mvLoggerItem::s_start = clock_::now(); +#elif defined(__APPLE__) + std::chrono::steady_clock::time_point mvLoggerItem::s_start = clock_::now(); +#else + std::chrono::system_clock::time_point mvLoggerItem::s_start = clock_::now(); +#endif + + void mvLoggerItem::draw(ImDrawList* drawlist, float x, float y) + { + mvFontScope fscope(this); + + ImGui::BeginGroup(); + + ImGui::PushID(this); + + // auto scroll button + if (m_autoScrollButton) + { + ImGui::Checkbox(m_autoScrollButtonName.c_str(), &AutoScroll); + ImGui::SameLine(); + } + + if (m_clearButton) + { + if (ImGui::Button(m_clearButtonName.c_str())) + ClearLog(); + ImGui::SameLine(); + } + + if (m_copyButton) + { + if (ImGui::Button(m_copyButtonName.c_str())) + ImGui::LogToClipboard(); + ImGui::SameLine(); + } + + if (m_filter) + { + ImGui::NewLine(); + Filter.Draw("Filter", m_width-100.0f); + } + + ImGui::BeginChild(m_name.c_str(), ImVec2(m_autosize_x ? 0 : (float)m_width, m_autosize_y ? 0 : (float)m_height), true, ImGuiWindowFlags_AlwaysHorizontalScrollbar); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + const char* buf = Buf.begin(); + const char* buf_end = Buf.end(); + if (Filter.IsActive()) + { + // In this example we don't use the clipper when Filter is enabled. + // This is because we don't have a random access on the result on our filter. + // A real application processing logs with ten of thousands of entries may want to store the result of search/filter. + // especially if the filtering function is not trivial (e.g. reg-exp). + for (int line_no = 0; line_no < LineOffsets.Size; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + if (Filter.PassFilter(line_start, line_end)) + ImGui::TextUnformatted(line_start, line_end); + } + } + else + { + + + // The simplest and easy way to display the entire buffer: + // ImGui::TextUnformatted(buf_begin, buf_end); + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines. + // Here we instead demonstrate using the clipper to only process lines that are within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended. + // Using ImGuiListClipper requires A) random access into your data, and B) items all being the same height, + // both of which we can handle since we an array pointing to the beginning of each line of text. + // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper. + // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries) + ImGuiListClipper clipper; + clipper.Begin(LineOffsets.Size); + while (clipper.Step()) + { + for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) + { + + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + + std::string mystring = line_start; + + std::string splitstring = mystring.substr(0, 20); + + if (strstr(splitstring.c_str(), "[ERROR]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + + else if (strstr(splitstring.c_str(), "[WARNING]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered)); + + else if (strstr(splitstring.c_str(), "[TRACE]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); + + else if (strstr(splitstring.c_str(), "[INFO]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + + else if (strstr(splitstring.c_str(), "[DEBUG]")) + + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.25f, 0.50f, 1.0f, 1.0f)); + + else + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + + ImGui::TextUnformatted(line_start, line_end); + ImGui::PopStyleColor(); + } + } + clipper.End(); + } + ImGui::PopStyleVar(); + + if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) + ImGui::SetScrollHereY(0.0f); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + mvInput::setGlobalMousePosition(mousePos.x, mousePos.y); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != m_name) + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", m_name) }); + + + } + + m_width = (int)ImGui::GetWindowWidth(); + m_height = (int)ImGui::GetWindowHeight(); + + ImGui::EndChild(); + ImGui::PopID(); + ImGui::EndGroup(); + + } + + void mvLoggerItem::AddLog(const char* fmt, ...) + { + static std::mutex mutex; + + std::lock_guard lock(mutex); + + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendfv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size + 1); + } + + void mvLoggerItem::Log(const std::string& text, const std::string& level) + { + if (m_loglevel < 1) + { + AddLog("[%0.2f] [%1s] %2s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + level.c_str(), text.c_str()); + } + } + + void mvLoggerItem::LogDebug(const std::string& text) + { + if (m_loglevel < 2) + AddLog("[%0.2f] [DEBUG] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvLoggerItem::LogInfo(const std::string& text) + { + if (m_loglevel < 3) + AddLog("[%0.2f] [INFO] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvLoggerItem::LogWarning(const std::string& text) + { + if (m_loglevel < 4) + AddLog("[%0.2f] [WARNING] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvLoggerItem::LogError(const std::string& text) + { + if (m_loglevel < 5) + AddLog("[%0.2f] [ERROR] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvLoggerItem::ClearLog() + { + Buf.clear(); + LineOffsets.clear(); + LineOffsets.push_back(0); + } + + void mvLoggerItem::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "auto_scroll")) AutoScroll = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "auto_scroll_button")) m_autoScrollButton = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "clear_button")) m_clearButton = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "copy_button")) m_copyButton = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "filter")) m_filter = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "autosize_x")) m_autosize_x = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "autosize_y")) m_autosize_y = ToBool(item); + + if (PyObject* item = PyDict_GetItemString(dict, "log_level")) + { + m_loglevel = ToInt(item); + DecodelibID(m_loglevel, &m_loglevel); + } + + + } + + void mvLoggerItem::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + PyDict_SetItemString(dict, "log_level", ToPyInt(MV_ENCODE_CONSTANT(m_loglevel, 0))); + PyDict_SetItemString(dict, "auto_scroll", ToPyBool(AutoScroll)); + PyDict_SetItemString(dict, "auto_scroll_button", ToPyBool(m_autoScrollButton)); + PyDict_SetItemString(dict, "clear_button", ToPyBool(m_clearButton)); + PyDict_SetItemString(dict, "copy_button", ToPyBool(m_copyButton)); + PyDict_SetItemString(dict, "filter", ToPyBool(m_filter)); + PyDict_SetItemString(dict, "autosize_x", ToPyBool(m_autosize_x)); + PyDict_SetItemString(dict, "autosize_y", ToPyBool(m_autosize_y)); + } + + PyObject* mvLoggerItem::get_log_level(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["get_log_level"].parse(args, kwargs, __FUNCTION__, &logger)) + return GetPyNone(); + + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return ToPyInt(-1); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return ToPyInt(-1); + } + + auto loggerwidget = static_cast(loggeritem.get()); + return ToPyInt(loggerwidget->getLogLevel()); + + } + else + return ToPyInt((int)mvAppLog::getLogLevel()); + + } + + PyObject* mvLoggerItem::set_log_level(PyObject* self, PyObject* args, PyObject* kwargs) + { + int level; + const char* logger = ""; + if (!(mvApp::GetApp()->getParsers())["set_log_level"].parse(args, kwargs, __FUNCTION__, + &level, &logger)) + return GetPyNone(); + + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->setLogLevel(level); + + } + else + mvAppLog::setLogLevel(level); + + return GetPyNone(); + } + + PyObject* mvLoggerItem::log(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* message; + const char* level = "TRACE"; + const char* logger = ""; + if (!(mvApp::GetApp()->getParsers())["log"].parse(args, kwargs, __FUNCTION__, &message, &level, &logger)) + return GetPyNone(); + + std::string cmessage = ToString(message); + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->Log(cmessage, std::string(level)); + + } + else + mvAppLog::Log(cmessage, std::string(level)); + + return GetPyNone(); + } + + PyObject* mvLoggerItem::log_debug(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* message; + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["log_debug"].parse(args, kwargs, __FUNCTION__, &message, &logger)) + return GetPyNone(); + + std::string cmessage = ToString(message); + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->LogDebug(cmessage); + + } + else + mvAppLog::LogDebug(cmessage); + + return GetPyNone(); + } + + PyObject* mvLoggerItem::log_info(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* message; + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["log_info"].parse(args, kwargs, __FUNCTION__, &message, &logger)) + return GetPyNone(); + + std::string cmessage = ToString(message); + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->LogInfo(cmessage); + + } + else + mvAppLog::LogInfo(cmessage); + + return GetPyNone(); + } + + PyObject* mvLoggerItem::log_warning(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* message; + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["log_warning"].parse(args, kwargs, __FUNCTION__, &message, &logger)) + return GetPyNone(); + + std::string cmessage = ToString(message); + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->LogWarning(cmessage); + + } + else + mvAppLog::LogWarning(cmessage); + return GetPyNone(); + } + + PyObject* mvLoggerItem::log_error(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* message; + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["log_error"].parse(args, kwargs, __FUNCTION__, &message, &logger)) + return GetPyNone(); + + std::string cmessage = ToString(message); + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->LogError(cmessage); + + } + else + mvAppLog::LogError(cmessage); + return GetPyNone(); + } + + PyObject* mvLoggerItem::clear_log(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* logger = ""; + + if (!(mvApp::GetApp()->getParsers())["clear_log"].parse(args, kwargs, __FUNCTION__, &logger)) + return GetPyNone(); + + if (!std::string(logger).empty()) + { + auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger); + if (loggeritem == nullptr) + { + ThrowPythonException(std::string(logger) + " logger does not exist."); + return GetPyNone(); + } + + if (loggeritem->getType() != mvAppItemType::mvLoggerItem) + { + ThrowPythonException(std::string(logger) + " is not a logger."); + return GetPyNone(); + } + + auto loggerwidget = static_cast(loggeritem.get()); + loggerwidget->ClearLog(); + + } + else + mvAppLog::ClearLog(); + + return GetPyNone(); + } + + PyObject* mvLoggerItem::show_logger(PyObject* self, PyObject* args) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvAppLog::Show(); + return GetPyNone(); + } + + PyObject* mvLoggerItem::set_logger_window_title(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* title; + + if (!(mvApp::GetApp()->getParsers())["set_logger_window_title"].parse(args, kwargs, __FUNCTION__, + &title)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvAppLog::setTitle(title); + + return GetPyNone(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvLogger.h b/DearPyGui/src/core/AppItems/composite/mvLogger.h new file mode 100644 index 000000000..64ca58f3e --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvLogger.h @@ -0,0 +1,127 @@ +#pragma once + +#include "mvApp.h" +#include "mvAppItem.h" +#include "mvItemRegistry.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvLoggerItem, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvLoggerItem : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvLoggerItem, add_logger) + + MV_CREATE_CONSTANT(mvTRACE, 0L, 0L); + MV_CREATE_CONSTANT(mvDEBUG, 1L, 0L); + MV_CREATE_CONSTANT(mvINFO, 2L, 0L); + MV_CREATE_CONSTANT(mvWARNING, 3L, 0L); + MV_CREATE_CONSTANT(mvERROR, 4L, 0L); + MV_CREATE_CONSTANT(mvOFF, 5L, 0L); + + MV_CREATE_EXTRA_COMMAND(get_log_level); + MV_CREATE_EXTRA_COMMAND(set_log_level); + MV_CREATE_EXTRA_COMMAND(log); + MV_CREATE_EXTRA_COMMAND(log_debug); + MV_CREATE_EXTRA_COMMAND(log_info); + MV_CREATE_EXTRA_COMMAND(log_warning); + MV_CREATE_EXTRA_COMMAND(log_error); + MV_CREATE_EXTRA_COMMAND(clear_log); + static PyObject* show_logger(PyObject* self, PyObject* args); + MV_CREATE_EXTRA_COMMAND(set_logger_window_title); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(get_log_level); + MV_ADD_EXTRA_COMMAND(set_log_level); + MV_ADD_EXTRA_COMMAND(log); + MV_ADD_EXTRA_COMMAND(log_debug); + MV_ADD_EXTRA_COMMAND(log_info); + MV_ADD_EXTRA_COMMAND(log_warning); + MV_ADD_EXTRA_COMMAND(log_error); + MV_ADD_EXTRA_COMMAND(clear_log); + MV_ADD_EXTRA_COMMAND(show_logger); + MV_ADD_EXTRA_COMMAND(set_logger_window_title); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_ADD_GENERAL_CONSTANT(mvTRACE), + MV_ADD_GENERAL_CONSTANT(mvDEBUG), + MV_ADD_GENERAL_CONSTANT(mvINFO), + MV_ADD_GENERAL_CONSTANT(mvWARNING), + MV_ADD_GENERAL_CONSTANT(mvERROR), + MV_ADD_GENERAL_CONSTANT(mvOFF), + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvLoggerItem(const std::string& name) + : mvAppItem(name) + { + m_autoScrollButtonName = "Auto-scroll##" + name; + m_clearButtonName = "Clear##" + name; + m_copyButtonName = "Copy##" + name; + ClearLog(); + LogInfo("[Logger] " + m_name); + } + + void draw(ImDrawList* drawlist, float x, float y) override; + + inline void setLogLevel(int level) { m_loglevel = level; } + inline int getLogLevel() const { return m_loglevel; } + + void AddLog(const char* fmt, ...); + void Log(const std::string& text, const std::string& level = "TRACE"); + void LogDebug(const std::string& text); + void LogInfo(const std::string& text); + void LogWarning(const std::string& text); + void LogError(const std::string& text); + void ClearLog(); + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + // configurable options + int m_loglevel = 1; + bool m_autoScrollButton = true; + bool m_clearButton = true; + bool m_copyButton = true; + bool m_filter = true; + bool m_autosize_x = false; + bool m_autosize_y = false; + + // + std::string m_autoScrollButtonName; + std::string m_clearButtonName; + std::string m_copyButtonName; + + // internal + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines + bool AutoScroll = true; // Keep scrolling if already at the bottom + bool show = true; // Keep scrolling if already at the bottom + bool mainmode = false; + +#if defined (_WIN32) + static std::chrono::steady_clock::time_point s_start; +#elif defined(__APPLE__) + static std::chrono::steady_clock::time_point s_start; +#else + static std::chrono::system_clock::time_point s_start; +#endif + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.cpp new file mode 100644 index 000000000..e24050993 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.cpp @@ -0,0 +1,80 @@ +#include "mvMetricsWindow.h" +#include "mvTypeBases.h" +#include "mvAppItem.h" +#include "mvInput.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvMetricsWindow::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "700"}, + {mvPythonDataType::Integer, "height", "", "500"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "False"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Creates a metrics window.", + "None", "Containers") }); + } + + mvMetricsWindow::mvMetricsWindow(const std::string& name) + : mvBaseWindowAppitem(name) + { + } + + void mvMetricsWindow::draw(ImDrawList* drawlist, float x, float y) + { + mvFontScope fscope(this); + + if (!prerender()) + return; + + ImGuiIO& io = ImGui::GetIO(); + ImGui::Text("Dear PyGui %s", mvApp::GetVersion()); + ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); + ImGui::Text("%d active allocations", io.MetricsActiveAllocations); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "metrics##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("metrics##standard")) }); + + } + + ImGui::End(); + + } + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.h b/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.h new file mode 100644 index 000000000..be527d47e --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvMetricsWindow.h @@ -0,0 +1,39 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include +#include "mvModule_Core.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvMetricsWindow, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvMetricsWindow : public mvBaseWindowAppitem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvMetricsWindow, add_metrics_window) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvMetricsWindow(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + }; + +} diff --git a/DearPyGui/src/core/AppItems/composite/mvSourceWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvSourceWindow.cpp new file mode 100644 index 000000000..0c7a7b6da --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvSourceWindow.cpp @@ -0,0 +1,89 @@ +#include "mvSourceWindow.h" +#include "mvApp.h" +#include "mvInput.h" +#include +#include +#include + +namespace Marvel { + + void mvSourceWindow::setFile(const std::string& file) + { + m_file = file; + m_editor.SetLanguageDefinition(mvTextEditor::LanguageDefinition::Python()); + { + std::ifstream t(m_file.c_str()); + if (t.good()) + { + std::string str((std::istreambuf_iterator(t)), std::istreambuf_iterator()); + m_editor.SetText(str); + } + } + + m_editor.SetReadOnly(true); + m_editor.SetShowWhitespaces(false); + } + + void mvSourceWindow::render(bool& show) + { + if (!prerender()) + return; + + auto cpos = m_editor.GetCursorPosition(); + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Edit")) + { + + ImGui::Separator(); + + if (ImGui::MenuItem("Copy", "Ctrl-C", nullptr, m_editor.HasSelection())) + m_editor.Copy(); + + ImGui::Separator(); + + if (ImGui::MenuItem("Select all", nullptr, nullptr)) + m_editor.SetSelection(mvTextEditor::Coordinates(), mvTextEditor::Coordinates(m_editor.GetTotalLines(), 0)); + + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("View")) + { + if (ImGui::MenuItem("Dark palette")) + m_editor.SetPalette(mvTextEditor::GetDarkPalette()); + if (ImGui::MenuItem("Light palette")) + m_editor.SetPalette(mvTextEditor::GetLightPalette()); + if (ImGui::MenuItem("Retro blue palette")) + m_editor.SetPalette(mvTextEditor::GetRetroBluePalette()); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Text("%6d/%-6d %6d lines | %s | %s | %s | %s", cpos.mLine + 1, cpos.mColumn + 1, m_editor.GetTotalLines(), + m_editor.IsOverwrite() ? "Ovr" : "Ins", + m_editor.CanUndo() ? "*" : " ", + m_editor.GetLanguageDefinition().mName.c_str(), m_file.c_str()); + + m_editor.Render("TextEditor"); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "source##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("source##standard")) }); + + } + ImGui::End(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvSourceWindow.h b/DearPyGui/src/core/AppItems/composite/mvSourceWindow.h new file mode 100644 index 000000000..2bac3c992 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvSourceWindow.h @@ -0,0 +1,31 @@ +#pragma once +#include "mvTextEditor.h" +#include "mvTypeBases.h" + +namespace Marvel { + + class mvSourceWindow : public mvBaseWindowAppitem + { + + MV_APPLY_WIDGET_REGISTRATION_OLD_SYSTEM(mvAppItemType::SourceWindow, "add_source_window") + + public: + + mvSourceWindow(const std::string& name) : + mvBaseWindowAppitem(name) + { + m_windowflags = ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar; + } + + void setFile(const std::string& file); + + void draw(ImDrawList* drawlist, float x, float y) override; + + private: + + mvTextEditor m_editor; + std::string m_file; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvStyleWindow.cpp b/DearPyGui/src/core/AppItems/composite/mvStyleWindow.cpp new file mode 100644 index 000000000..34d8accd1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvStyleWindow.cpp @@ -0,0 +1,223 @@ +#include +#include "mvApp.h" +#include "mvAppItemCommons.h" +#include "mvStyleWindow.h" +#include "mvInput.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +// Helper to display a little (?) mark which shows a tooltip when hovered. +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) +static void HelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +namespace Marvel { + + void mvStyleWindow::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "700"}, + {mvPythonDataType::Integer, "height", "", "500"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "False"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Creates a style window.", + "None", "Containers") }); + } + + void mvStyleWindow::draw(ImDrawList* drawlist, float x, float y) + { + + mvFontScope fscope(this); + + if (!prerender()) + return; + + ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); + ImGui::PushItemWidth(-350); + + if(ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None)) + { + + if (ImGui::BeginTabItem("Styles")) + { + + + HelpMarker( + "Export saves commands to your clipboard. Paste into your file."); + ImGui::SameLine(); + if (ImGui::Button("Export Styles")) + { + + ImGui::LogToClipboard(); + + for (auto item : mvThemeManager::GetStylesPtr()) + { + // Uncomment and replace with new command + + //ImGui::LogText("set_theme_item(mvGuiCol_%s, %i, %i, %i, %i)\r\n", + // name, (int)(round(col.x * 255.0f)), (int)(round(col.y * 255.0f)), (int)(round(col.z * 255.0f)), + // (int)(round(col.w * 255.0f))); + } + ImGui::LogFinish(); + } + + static ImGuiTextFilter filter1; + filter1.Draw("Filter Styles", ImGui::GetFontSize() * 16); + + ImGui::Separator(); + + for (auto& item : mvThemeManager::GetStylesPtr()) + { + if (!filter1.PassFilter(std::get<0>(item).c_str())) + continue; + + ImGui::PushID(&item); + if(ImGui::SliderFloat("##style", std::get<2>(item), 0.0f, std::get<3>(item))) + mvThemeManager::InValidateStyleTheme(); + ImGui::SameLine(); + ImGui::TextUnformatted(std::get<0>(item).c_str()); + ImGui::PopID(); + } + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Colors")) + { + + HelpMarker( + "Export saves commands to your clipboard. Paste into your file."); + ImGui::SameLine(); + if (ImGui::Button("Export Colors")) + { + + ImGui::LogToClipboard(); + + for (auto item : mvThemeManager::GetColorsPtr()) + { + // Uncomment and replace with new command + + //ImGui::LogText("set_theme_item(mvGuiCol_%s, %i, %i, %i, %i)\r\n", + // name, (int)(round(col.x * 255.0f)), (int)(round(col.y * 255.0f)), (int)(round(col.z * 255.0f)), + // (int)(round(col.w * 255.0f))); + } + ImGui::LogFinish(); + } + + static ImGuiTextFilter filter2; + filter2.Draw("Filter Colors", ImGui::GetFontSize() * 16); + + ImGui::Separator(); + + for (auto& item : mvThemeManager::GetColorsPtr()) + { + if (!filter2.PassFilter(std::get<0>(item).c_str())) + continue; + + ImGui::PushID(&item); + if (ImGui::ColorEdit4("##color", *std::get<2>(item), ImGuiColorEditFlags_AlphaBar)) + mvThemeManager::InValidateColorTheme(); + ImGui::SameLine(); + ImGui::TextUnformatted(std::get<0>(item).c_str()); + ImGui::PopID(); + } + + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Colors (disabled)")) + { + + HelpMarker( + "Export saves commands to your clipboard. Paste into your file."); + ImGui::SameLine(); + if (ImGui::Button("Export Colors (disabled)")) + { + + ImGui::LogToClipboard(); + + for (auto item : mvThemeManager::GetColorsPtr()) + { + // Uncomment and replace with new command + + //ImGui::LogText("set_theme_item(mvGuiCol_%s, %i, %i, %i, %i)\r\n", + // name, (int)(round(col.x * 255.0f)), (int)(round(col.y * 255.0f)), (int)(round(col.z * 255.0f)), + // (int)(round(col.w * 255.0f))); + } + ImGui::LogFinish(); + } + + static ImGuiTextFilter filter3; + filter3.Draw("Filter Colors##(disabled)", ImGui::GetFontSize() * 16); + + ImGui::Separator(); + + for (auto& item : mvThemeManager::GetColorsPtr()) + { + if (!filter3.PassFilter(std::get<0>(item).c_str())) + continue; + + ImGui::PushID(&item); + if(ImGui::ColorEdit4("##color(disable)", *std::get<3>(item), ImGuiColorEditFlags_AlphaBar)) + mvThemeManager::InValidateColorTheme(); + ImGui::SameLine(); + ImGui::TextUnformatted(std::get<0>(item).c_str()); + ImGui::PopID(); + } + + ImGui::EndTabItem(); + } + + } + + ImGui::EndTabBar(); + + ImGui::PopItemWidth(); + ImGui::EndChild(); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "style##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("style##standard")) }); + + } + + ImGui::End(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/composite/mvStyleWindow.h b/DearPyGui/src/core/AppItems/composite/mvStyleWindow.h new file mode 100644 index 000000000..7df653799 --- /dev/null +++ b/DearPyGui/src/core/AppItems/composite/mvStyleWindow.h @@ -0,0 +1,39 @@ +#pragma once +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvStyleWindow, MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvStyleWindow : public mvBaseWindowAppitem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvStyleWindow, add_style_window) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvStyleWindow(const std::string& name) + : mvBaseWindowAppitem(name) + { + } + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvChild.cpp b/DearPyGui/src/core/AppItems/containers/mvChild.cpp new file mode 100644 index 000000000..8260c8d8e --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvChild.cpp @@ -0,0 +1,123 @@ +#include "mvChild.h" +#include "mvInput.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvChild::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::Bool, "border", "", "True"}, + {mvPythonDataType::Bool, "autosize_x", "Autosize the window to fit it's items in the x.", "False"}, + {mvPythonDataType::Bool, "autosize_y", "Autosize the window to fit it's items in the y.", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "menubar", "", "False"}, + }, "Adds an embedded child window. Will show scrollbars when items do not fit. Must be followed by a call to end.", + "None", "Containers") }); + } + + mvChild::mvChild(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvChild::addFlag(ImGuiWindowFlags flag) + { + m_windowflags |= flag; + } + + void mvChild::removeFlag(ImGuiWindowFlags flag) + { + m_windowflags &= ~flag; + } + + void mvChild::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImGui::BeginChild(m_label.c_str(), ImVec2(m_autosize_x ? 0 : (float)m_width, m_autosize_y ? 0 : (float)m_height), m_border, m_windowflags); + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + // allows this item to have a render callback + registerWindowFocusing(); + + m_width = (int)ImGui::GetWindowWidth(); + m_height = (int)ImGui::GetWindowHeight(); + + ImGui::EndChild(); + } + + void mvChild::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "border")) m_border = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "autosize_x")) m_autosize_x = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "autosize_y")) m_autosize_y = ToBool(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + flagop("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + flagop("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + } + + void mvChild::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "border", ToPyBool(m_border)); + PyDict_SetItemString(dict, "autosize_x", ToPyBool(m_autosize_x)); + PyDict_SetItemString(dict, "autosize_y", ToPyBool(m_autosize_y)); + + // helper for bit flipping + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + checkbitset("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + checkbitset("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvChild.h b/DearPyGui/src/core/AppItems/containers/mvChild.h new file mode 100644 index 000000000..91c3a1634 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvChild.h @@ -0,0 +1,82 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvChild, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvChild : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvChild, add_child) + + MV_CREATE_CONSTANT(mvThemeCol_Child_Bg , ImGuiCol_ChildBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_MenuBar , ImGuiCol_MenuBarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_ScrollbarGrabHovered , ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Child_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Child_BorderSize , ImGuiStyleVar_ChildBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_Rounding , ImGuiStyleVar_ChildRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_PaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_PaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_ScrollbarSize , ImGuiStyleVar_ScrollbarSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Child_ScrollbarRounding , ImGuiStyleVar_ScrollbarRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_Bg, mvColor( 0, 0, 0, 0)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_MenuBar, mvColor( 36, 36, 36, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_Scrollbar, mvColor( 5, 5, 5, 135)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_ScrollbarGrab, mvColor( 79, 79, 79, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_ScrollbarGrabHovered, mvColor(105, 105, 105, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Child_ScrollbarGrabActive, mvColor(130, 130, 130, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Child_BorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Child_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Child_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Child_PaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Child_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Child_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Child_ScrollbarSize ,14, 20), + MV_ADD_CONSTANT(mvThemeStyle_Child_ScrollbarRounding , 9, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvChild(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + void addFlag (ImGuiWindowFlags flag); + void removeFlag (ImGuiWindowFlags flag); + + private: + + bool m_border = true; + bool m_autosize_x = false; + bool m_autosize_y = false; + ImGuiWindowFlags m_windowflags = ImGuiWindowFlags_NoSavedSettings; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.cpp b/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.cpp new file mode 100644 index 000000000..8897d6558 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.cpp @@ -0,0 +1,113 @@ +#include "mvCollapsingHeader.h" +#include "mvInput.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvCollapsingHeader::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "closable", "", "False"}, + {mvPythonDataType::Bool, "default_open", "", "False"}, + {mvPythonDataType::Bool, "open_on_double_click", "Need double-click to open node", "False"}, + {mvPythonDataType::Bool, "open_on_arrow", "Only open when clicking on the arrow part.", "False"}, + {mvPythonDataType::Bool, "leaf", "No collapsing, no arrow (use as a convenience for leaf nodes).", "False"}, + {mvPythonDataType::Bool, "bullet", "Display a bullet instead of arrow", "False"}, + }, "Adds a collapsing header to add items to. Must be closed with the end command.", + "None", "Containers") }); + } + + mvCollapsingHeader::mvCollapsingHeader(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvCollapsingHeader::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + bool* toggle = nullptr; + if (m_closable) + toggle = &m_show; + *m_value = ImGui::CollapsingHeader(m_label.c_str(), toggle, m_flags); + + //we do this so that the children dont get the theme + scope.cleanup(); + + if (*m_value) + { + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + } + } + + void mvCollapsingHeader::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "closable")) m_closable = ToBool(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("default_open", ImGuiTreeNodeFlags_DefaultOpen, m_flags); + flagop("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, m_flags); + flagop("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, m_flags); + flagop("leaf", ImGuiTreeNodeFlags_Leaf, m_flags); + flagop("bullet", ImGuiTreeNodeFlags_Bullet, m_flags); + + + } + + void mvCollapsingHeader::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "closable", ToPyBool(m_closable)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // flags + checkbitset("default_open", ImGuiTreeNodeFlags_DefaultOpen, m_flags); + checkbitset("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, m_flags); + checkbitset("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, m_flags); + checkbitset("leaf", ImGuiTreeNodeFlags_Leaf, m_flags); + checkbitset("bullet", ImGuiTreeNodeFlags_Bullet, m_flags); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.h b/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.h new file mode 100644 index 000000000..02e08e22b --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvCollapsingHeader.h @@ -0,0 +1,70 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvCollapsingHeader, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvCollapsingHeader : public mvBoolPtrBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvCollapsingHeader, add_collapsing_header) + + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_Bg , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_BgHovered , ImGuiCol_HeaderHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_BgActive , ImGuiCol_HeaderActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_CollapsingHeader_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_CollapsingHeader_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_Bg, mvColor( 66, 150, 250, 79)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_BgHovered, mvColor( 66, 150, 250, 204)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_BgActive, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_CollapsingHeader_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_CollapsingHeader_ItemSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvCollapsingHeader(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiTreeNodeFlags m_flags = ImGuiTreeNodeFlags_None; + bool m_closable = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvGroup.cpp b/DearPyGui/src/core/AppItems/containers/mvGroup.cpp new file mode 100644 index 000000000..13cf48905 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvGroup.cpp @@ -0,0 +1,90 @@ +#include "mvGroup.h" +#include "mvInput.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvGroup::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Bool, "horizontal", "", "False"}, + {mvPythonDataType::Float, "horizontal_spacing","", "-1"}, + }, "Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members.\ + Must be closed with the end command." + , "None", "Containers") }); + } + + mvGroup::mvGroup(const std::string& name) + : mvAppItem(name) + { + } + + void mvGroup::draw(ImDrawList* drawlist, float x, float y) + { + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_width != 0) + ImGui::PushItemWidth((float)m_width); + + ImGui::BeginGroup(); + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + if (m_width != 0) + item->setWidth(m_width); + + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + if (m_horizontal) + ImGui::SameLine(0.0, m_hspacing); + + item->getState().update(); + } + + if (m_width != 0) + ImGui::PopItemWidth(); + + ImGui::EndGroup(); + } + + void mvGroup::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "horizontal")) m_horizontal = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "horizontal_spacing")) m_hspacing = ToFloat(item); + } + + void mvGroup::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "horizontal", ToPyBool(m_horizontal)); + PyDict_SetItemString(dict, "horizontal_spacing", ToPyFloat(m_hspacing)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvGroup.h b/DearPyGui/src/core/AppItems/containers/mvGroup.h new file mode 100644 index 000000000..b6dd4b265 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvGroup.h @@ -0,0 +1,50 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvGroup, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvGroup : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvGroup, add_group) + + MV_CREATE_CONSTANT(mvThemeStyle_Group_ItemSpacingX, ImGuiStyleVar_ItemSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Group_ItemSpacingY, ImGuiStyleVar_ItemSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Group_ItemSpacingX, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Group_ItemSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvGroup(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_horizontal = false; + float m_hspacing = -1.0f; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvMenu.cpp b/DearPyGui/src/core/AppItems/containers/mvMenu.cpp new file mode 100644 index 000000000..20f72707d --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvMenu.cpp @@ -0,0 +1,91 @@ +#include "mvMenu.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvMenu::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "enabled", "", "True"}, + }, "Adds a menu to an existing menu bar. Must be followed by a call to end.", "None", "Containers") }); + } + + mvMenu::mvMenu(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvMenu::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + // create menu and see if its selected + if (ImGui::BeginMenu(m_label.c_str(), m_enabled)) + { + + // set other menus's value false on same level + for (auto sibling : m_parentPtr->m_children[1]) + { + // ensure sibling + if (sibling->getType() == mvAppItemType::mvMenu) + *((mvMenu*)sibling.get())->m_value = false; + } + + // set current menu value true + *m_value = true; + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + registerWindowFocusing(); + + ImGui::EndMenu(); + } + + } + + void mvMenu::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "enabled")) m_enabled = ToBool(item); + + } + + void mvMenu::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "enabled", ToPyBool(m_enabled)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvMenu.h b/DearPyGui/src/core/AppItems/containers/mvMenu.h new file mode 100644 index 000000000..31fdb1487 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvMenu.h @@ -0,0 +1,64 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvMenu, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvMenu : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvMenu, add_menu) + + MV_CREATE_CONSTANT(mvThemeCol_Menu_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Menu_Bg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Menu_BgHovered , ImGuiCol_HeaderHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Menu_BgActive , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Menu_Border , ImGuiCol_Border , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Menu_BorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Menu_Rounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Menu_PaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Menu_PaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Menu_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Menu_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Menu_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Menu_Bg, mvColor( 20, 20, 20, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Menu_BgHovered, mvColor( 66, 150, 250, 204)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Menu_BgActive, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Menu_Border, mvColor(110, 110, 128, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Menu_BorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Menu_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Menu_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Menu_PaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Menu_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Menu_ItemSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvMenu(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvMenuBar.cpp b/DearPyGui/src/core/AppItems/containers/mvMenuBar.cpp new file mode 100644 index 000000000..8d3e1ea72 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvMenuBar.cpp @@ -0,0 +1,74 @@ +#include "mvMenuBar.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "containers/mvWindowAppItem.h" +#include "containers/mvChild.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvMenuBar::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a menu bar to a window. Must be followed by a call to end.", "None", "Containers") }); + } + + mvMenuBar::mvMenuBar(const std::string& name) + : mvBoolPtrBase(name) + { + + // TODO use code below to set item height when font and scale systems are done + //float FontSize = ImGui::GetFontSize(); // = Base Font Size * Current Window Scale + //ImGuiStyle currentStyle = ImGui::GetStyle(); // = Padding for the Top and Bottom + //m_height = int(currentStyle.FramePadding.y * 2 + FontSize); + m_height = 21; + } + + void mvMenuBar::draw(ImDrawList* drawlist, float x, float y) + { + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::BeginMenuBar()) + { + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + ImGui::EndMenuBar(); + } + } + + bool mvMenuBar::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvWindowAppItem) return true; + if (type == mvAppItemType::mvChild) return true; + + mvThrowPythonError(1000, "Menubar parent must be a window or child."); + MV_ITEM_REGISTRY_ERROR("Menubar parent must be a window or child."); + assert(false); + return false; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvMenuBar.h b/DearPyGui/src/core/AppItems/containers/mvMenuBar.h new file mode 100644 index 000000000..269d934ee --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvMenuBar.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvAppItem.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvMenuBar, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvMenuBar : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvMenuBar, add_menu_bar) + + MV_CREATE_CONSTANT(mvThemeStyle_MenuBar_ItemSpacingX, ImGuiStyleVar_ItemSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_MenuBar_ItemSpacingY, ImGuiStyleVar_ItemSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_MenuBar_ItemSpacingX, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_MenuBar_ItemSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + explicit mvMenuBar(const std::string& name); + + bool isParentCompatible(mvAppItemType type) override; + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvPopup.cpp b/DearPyGui/src/core/AppItems/containers/mvPopup.cpp new file mode 100644 index 000000000..dea0c7e2e --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvPopup.cpp @@ -0,0 +1,170 @@ +#include "mvPopup.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvPopup::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "mousebutton", "The mouse code that will trigger the popup.", "1"}, + {mvPythonDataType::Bool, "modal", "", "False"}, + {mvPythonDataType::String, "parent", "Parent that the popup will be assigned to.", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width", "", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a popup window for an item. This command must come immediately after the item the popup is for. Must be followed by a call to end.", + "None", "Containers") }); + + parsers->insert({ "close_popup", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Closes a popup.") }); + } + + mvPopup::mvPopup(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvPopup::closePopup() + { + m_close = true; + } + + void mvPopup::draw(ImDrawList* drawlist, float x, float y) + { + + ScopedID id(m_parentAddress); + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_modal) + { + if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(m_button)) + ImGui::OpenPopup(m_name.c_str()); + + if (ImGui::BeginPopupModal(m_name.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + { + + if (m_close) + { + ImGui::CloseCurrentPopup(); + m_close = false; + } + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (mvRef item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + ImGui::EndPopup(); + } + } + + else + { + if (ImGui::BeginPopupContextItem(m_name.c_str(), m_button)) + { + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (mvRef item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width > 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, x, y); + + item->getState().update(); + } + + // allows this item to have a render callback + registerWindowFocusing(); + + ImGui::EndPopup(); + } + } + } + + void mvPopup::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "parent")) + { + auto parentName = ToString(item); + auto parent = mvApp::GetApp()->getItemRegistry().getItem(parentName); + m_parentAddress = parent.get(); + } + if (PyObject* item = PyDict_GetItemString(dict, "modal")) m_modal = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "mousebutton")) m_button = ToInt(item); + + } + + void mvPopup::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "modal", ToPyBool(m_modal)); + PyDict_SetItemString(dict, "mousebutton", ToPyInt(m_button)); + } + + PyObject* mvPopup::close_popup(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* popup; + + if (!(mvApp::GetApp()->getParsers())["close_popup"].parse(args, kwargs, __FUNCTION__, &popup)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + auto item = mvApp::GetApp()->getItemRegistry().getItem(popup); + + if (item == nullptr) + { + std::string message = popup; + ThrowPythonException(message + " popup does not exist."); + return GetPyNone(); + } + + mvPopup* pop; + if (item->getType() == mvAppItemType::mvPopup) + pop = static_cast(item.get()); + else + { + ThrowPythonException(std::string(popup) + " is not a popup."); + return GetPyNone(); + } + + pop->closePopup(); + + return GetPyNone(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvPopup.h b/DearPyGui/src/core/AppItems/containers/mvPopup.h new file mode 100644 index 000000000..f38b3ddbd --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvPopup.h @@ -0,0 +1,100 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvPopup, MV_ITEM_DESC_CONTAINER | MV_ITEM_DESC_AFTER, StorageValueTypes::Bool, 1); + class mvPopup : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvPopup, add_popup) + + MV_CREATE_EXTRA_COMMAND(close_popup); + + MV_CREATE_CONSTANT(mvThemeCol_Popup_TitleText , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_TitleBg , ImGuiCol_TitleBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_Bg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_ModalDimBg , ImGuiCol_ModalWindowDimBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Popup_Border , ImGuiCol_Border , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Popup_BorderSize , ImGuiStyleVar_PopupBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_Rounding , ImGuiStyleVar_PopupRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_PaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_PaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalRounding , ImGuiStyleVar_WindowRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalBorderSize , ImGuiStyleVar_WindowBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalTitleAlignX , ImGuiStyleVar_WindowTitleAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalTitleAlignY , ImGuiStyleVar_WindowTitleAlign , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalMinSizeX , ImGuiStyleVar_WindowMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalMinSizeY , ImGuiStyleVar_WindowMinSize , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalScrollbarSize , ImGuiStyleVar_ScrollbarSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Popup_ModalScrollbarRounding, ImGuiStyleVar_ScrollbarRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(close_popup); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_TitleText, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_TitleBg, mvColor( 10, 10, 10, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_Bg, mvColor( 20, 20, 20, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_ModalDimBg, mvColor(204, 204, 204, 89)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_Scrollbar, mvColor( 5, 5, 5, 135)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_ScrollbarGrab, mvColor( 79, 79, 79, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_ScrollbarGrabHovered, mvColor(105, 105, 105, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_ScrollbarGrabActive, mvColor(130, 130, 130, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Popup_Border, mvColor(110, 110, 128, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Popup_BorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Popup_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Popup_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Popup_PaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalRounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalTitleAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalTitleAlignY , 0.5, 1), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalMinSizeX ,32, 50), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalMinSizeY ,32, 50), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalScrollbarSize ,14, 20), + MV_ADD_CONSTANT(mvThemeStyle_Popup_ModalScrollbarRounding , 9, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvPopup(const std::string& name); + + void closePopup(); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_modal = false; + int m_button = 1; + mvAppItem* m_parentAddress = nullptr; + bool m_close = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTab.cpp b/DearPyGui/src/core/AppItems/containers/mvTab.cpp new file mode 100644 index 000000000..784f41178 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTab.cpp @@ -0,0 +1,147 @@ +#include "mvTab.h" +#include "mvTabBar.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + void mvTab::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "closable", "creates a button on the tab that can hide the tab", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "no_reorder", "Disable reordering this tab or having another tab cross over this tab", "False"}, + {mvPythonDataType::Bool, "leading", "Enforce the tab position to the left of the tab bar (after the tab list popup button)", "False"}, + {mvPythonDataType::Bool, "trailing", "Enforce the tab position to the right of the tab bar (before the scrolling buttons)", "False"}, + {mvPythonDataType::Bool, "no_tooltip", "Disable tooltip for the given tab", "False"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a tab to a tab bar. Must be closed with the end command.", "None", "Containers") }); + } + mvTab::mvTab(const std::string& name) + : + mvBoolPtrBase(name) + { + } + + void mvTab::addFlag(ImGuiTabItemFlags flag) + { + m_flags |= flag; + } + + void mvTab::removeFlag(ImGuiTabItemFlags flag) + { + m_flags &= ~flag; + } + + void mvTab::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + // cast parent to mvTabBar + auto parent = (mvTabBar*)m_parentPtr; + + // check if this is first tab + if (parent->getSpecificValue().empty()) + { + // set mvTabBar value to the first tab name + parent->setValue(m_name); + *m_value = true; + } + + // create tab item and see if it is selected + if (ImGui::BeginTabItem(m_label.c_str(), m_closable ? &m_show : nullptr, m_flags)) + { + + // set other tab's value false + for (auto child : parent->m_children[1]) + { + if (child->getType() == mvAppItemType::mvTab) + *((mvTab*)child.get())->m_value = false; + } + + // set current tab value true + *m_value = true; + + // run call back if it exists + if (parent->getSpecificValue() != m_name) + mvApp::GetApp()->getCallbackRegistry().addCallback(parent->getCallback(), m_name, parent->getCallbackData()); + + parent->setValue(m_name); + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + ImGui::EndTabItem(); + } + + } + + void mvTab::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "closable")) m_closable = ToBool(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("no_reorder", ImGuiTabItemFlags_NoReorder, m_flags); + flagop("leading", ImGuiTabItemFlags_Leading, m_flags); + flagop("trailing", ImGuiTabItemFlags_Trailing, m_flags); + flagop("no_tooltip", ImGuiTabItemFlags_NoTooltip, m_flags); + + if (m_flags & ImGuiTabItemFlags_Leading && m_flags & ImGuiTabItemFlags_Trailing) + m_flags &= ~ImGuiTabItemFlags_Leading; + + } + + void mvTab::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "closable", ToPyBool(m_closable)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("no_reorder", ImGuiTabBarFlags_Reorderable, m_flags); + checkbitset("leading", ImGuiTabItemFlags_Leading, m_flags); + checkbitset("trailing", ImGuiTabItemFlags_Trailing, m_flags); + checkbitset("no_tooltip", ImGuiTabItemFlags_NoTooltip, m_flags); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTab.h b/DearPyGui/src/core/AppItems/containers/mvTab.h new file mode 100644 index 000000000..21ef0b530 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTab.h @@ -0,0 +1,71 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTab, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvTab : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTab, add_tab) + + MV_CREATE_CONSTANT(mvThemeCol_Tab_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tab_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tab_Bg , ImGuiCol_Tab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tab_BgHovered , ImGuiCol_TabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tab_BgActive , ImGuiCol_TabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tab_PopupBg , ImGuiCol_PopupBg , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Tab_Rounding , ImGuiStyleVar_TabRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tab_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tab_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Tab_InnerSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tab_InnerSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_Bg, mvColor( 46, 89, 148, 220)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_BgHovered, mvColor( 66, 150, 250, 204)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_BgActive, mvColor( 51, 105, 173, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tab_PopupBg, mvColor( 20, 20, 20, 240)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Tab_Rounding , 4, 12), + MV_ADD_CONSTANT(mvThemeStyle_Tab_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tab_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tab_InnerSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tab_InnerSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvTab(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + void addFlag (ImGuiTabItemFlags flag); + void removeFlag(ImGuiTabItemFlags flag); + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_closable = false; + ImGuiTabItemFlags m_flags = ImGuiTabItemFlags_None; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTabBar.cpp b/DearPyGui/src/core/AppItems/containers/mvTabBar.cpp new file mode 100644 index 000000000..fd34054f7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTabBar.cpp @@ -0,0 +1,129 @@ +#include "mvTabBar.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvTab.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTabBar::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "reorderable", "allows for moveable tabs", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a tab bar.", "None", "Containers") }); + } + + mvTabBar::mvTabBar(const std::string& name) + : + mvStringPtrBase(name) + { + } + + + bool mvTabBar::canChildBeAdded(mvAppItemType type) + { + if (type == mvAppItemType::mvTab)return true; + if (type == mvAppItemType::mvTabButton)return true; + + mvThrowPythonError(1000, "TabBar children must be tabs or tab buttons."); + MV_ITEM_REGISTRY_ERROR("TabBar children must be tabs or tab buttons."); + assert(false); + + return false; + } + + std::string& mvTabBar::getSpecificValue() + { + return m_uiValue; + } + + void mvTabBar::setValue(const std::string& value) + { + m_uiValue = value; + } + + void mvTabBar::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + ImGui::BeginGroup(); + + if (ImGui::BeginTabBar(m_label.c_str(), m_flags)) + { + //we do this so that the children dont get the theme + scope.cleanup(); + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + if (*m_value == item->m_name && m_lastValue != *m_value) + static_cast(item.get())->addFlag(ImGuiTabItemFlags_SetSelected); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + if (*m_value == item->m_name) + static_cast(item.get())->removeFlag(ImGuiTabItemFlags_SetSelected); + + item->getState().update(); + } + + ImGui::EndTabBar(); + } + + ImGui::EndGroup(); + + *m_value = m_uiValue; + m_lastValue = *m_value; + } + + void mvTabBar::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("reorderable", ImGuiTabBarFlags_Reorderable, m_flags); + + } + + void mvTabBar::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("reorderable", ImGuiTabBarFlags_Reorderable, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTabBar.h b/DearPyGui/src/core/AppItems/containers/mvTabBar.h new file mode 100644 index 000000000..e4dcfbfbf --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTabBar.h @@ -0,0 +1,57 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTabBar, MV_ITEM_DESC_CONTAINER, StorageValueTypes::String, 1); + class mvTabBar : public mvStringPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTabBar, add_tab_bar) + + MV_CREATE_CONSTANT(mvThemeCol_TabBar, 35L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TabBar_ItemSpacingX, ImGuiStyleVar_ItemSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TabBar_ItemSpacingY, ImGuiStyleVar_ItemSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TabBar, mvColor(110, 110, 128, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_TabBar_ItemSpacingX, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_TabBar_ItemSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvTabBar(const std::string& name); + + bool canChildBeAdded(mvAppItemType type) override; + + std::string& getSpecificValue(); + void setValue(const std::string& value); + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiTabBarFlags m_flags = ImGuiTabBarFlags_None; + std::string m_lastValue; + std::string m_uiValue; // value suggested from UI + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTooltip.cpp b/DearPyGui/src/core/AppItems/containers/mvTooltip.cpp new file mode 100644 index 000000000..70b86ad3c --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTooltip.cpp @@ -0,0 +1,64 @@ +#include "mvTooltip.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTooltip::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "parent", "Sets the item's tool tip to be the same as the named item's tool tip"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show","Attempt to render", "True"}, + }, "Adds an advanced tool tip for an item. This command must come immediately after the item the tip is for.", + "None", "Containers") }); + } + + mvTooltip::mvTooltip(const std::string& name) + : + mvBoolPtrBase(name) + { + + // has to be showed that way it can check for hovering + // otherwise it will never show + m_show = true; + + } + + void mvTooltip::draw(ImDrawList* drawlist, float x, float y) + { + if (ImGui::IsItemHovered()) + { + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + ImGui::BeginTooltip(); + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + ImGui::EndTooltip(); + } + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTooltip.h b/DearPyGui/src/core/AppItems/containers/mvTooltip.h new file mode 100644 index 000000000..613ba0c1c --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTooltip.h @@ -0,0 +1,54 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTooltip, MV_ITEM_DESC_CONTAINER | MV_ITEM_DESC_AFTER, StorageValueTypes::Bool, 1); + class mvTooltip : public mvBoolPtrBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTooltip, add_tooltip) + + MV_CREATE_CONSTANT(mvThemeCol_Tooltip_Bg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Tooltip_Border , ImGuiCol_Border , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_BorderSize , ImGuiStyleVar_WindowBorderSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_Rounding , ImGuiStyleVar_WindowRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_PaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_PaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Tooltip_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tooltip_Bg, mvColor( 20, 20, 20, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Tooltip_Border, mvColor(110, 110, 128, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_BorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_PaddingY , 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Tooltip_ItemSpacingY , 8, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvTooltip(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTreeNode.cpp b/DearPyGui/src/core/AppItems/containers/mvTreeNode.cpp new file mode 100644 index 000000000..4d0de2622 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTreeNode.cpp @@ -0,0 +1,105 @@ +#include "mvTreeNode.h" +#include "core/mvInput.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + void mvTreeNode::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "default_open", "", "False"}, + {mvPythonDataType::Bool, "open_on_double_click", "Need double-click to open node", "False"}, + {mvPythonDataType::Bool, "open_on_arrow", "Only open when clicking on the arrow part.", "False"}, + {mvPythonDataType::Bool, "leaf", "No collapsing, no arrow (use as a convenience for leaf nodes).", "False"}, + {mvPythonDataType::Bool, "bullet", "Display a bullet instead of arrow", "False"}, + }, "Adds a tree node to add items to. Must be closed with the end command.", + "None", "Containers") }); + } + mvTreeNode::mvTreeNode(const std::string& name) + : mvBoolPtrBase(name) + { + } + + void mvTreeNode::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImGui::BeginGroup(); + if (ImGui::TreeNodeEx(m_label.c_str(), m_flags)) + { + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + ImGui::TreePop(); + } + + ImGui::EndGroup(); + } + + void mvTreeNode::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // flags + flagop("default_open", ImGuiTreeNodeFlags_DefaultOpen, m_flags); + flagop("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, m_flags); + flagop("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, m_flags); + flagop("leaf", ImGuiTreeNodeFlags_Leaf, m_flags); + flagop("bullet", ImGuiTreeNodeFlags_Bullet, m_flags); + } + + void mvTreeNode::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // flags + checkbitset("default_open", ImGuiTreeNodeFlags_DefaultOpen, m_flags); + checkbitset("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, m_flags); + checkbitset("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, m_flags); + checkbitset("leaf", ImGuiTreeNodeFlags_Leaf, m_flags); + checkbitset("bullet", ImGuiTreeNodeFlags_Bullet, m_flags); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvTreeNode.h b/DearPyGui/src/core/AppItems/containers/mvTreeNode.h new file mode 100644 index 000000000..04bc14a0e --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvTreeNode.h @@ -0,0 +1,58 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTreeNode, MV_ITEM_DESC_CONTAINER, StorageValueTypes::Bool, 1); + class mvTreeNode : public mvBoolPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTreeNode, add_tree_node) + + MV_CREATE_CONSTANT(mvThemeCol_TreeNode_Text , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TreeNode_BgHovered , ImGuiCol_HeaderHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_TreeNode_BgActive , ImGuiCol_HeaderActive , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_TreeNode_FramePaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TreeNode_FramePaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_TreeNode_IndentSpacing , ImGuiStyleVar_IndentSpacing , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TreeNode_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TreeNode_BgHovered, mvColor( 66, 150, 250, 204)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TreeNode_BgActive, mvColor( 66, 150, 250, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_TreeNode_FramePaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_TreeNode_FramePaddingY, 3, 20), + MV_ADD_CONSTANT(mvThemeStyle_TreeNode_IndentSpacing,21, 30), + MV_END_STYLE_CONSTANTS + + public: + + mvTreeNode(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiTreeNodeFlags m_flags = ImGuiTreeNodeFlags_None; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.cpp b/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.cpp new file mode 100644 index 000000000..679d5a113 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.cpp @@ -0,0 +1,382 @@ +#include "mvWindowAppItem.h" +#include "mvInput.h" +#include "mvViewport.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvWindowAppItem::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "-1"}, + {mvPythonDataType::Integer, "height", "", "-1"}, + {mvPythonDataType::Integer, "x_pos", "x position the window will start at", "200"}, + {mvPythonDataType::Integer, "y_pos", "y position the window will start at", "200"}, + {mvPythonDataType::Bool, "autosize", "Autosized the window to fit it's items.", "False"}, + {mvPythonDataType::Bool, "no_resize", "Allows for the window size to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_title_bar", "Title name for the title bar of the window", "False"}, + {mvPythonDataType::Bool, "no_move", "Allows for the window's position to be changed or fixed", "False"}, + {mvPythonDataType::Bool, "no_scrollbar" ," Disable scrollbars (window can still scroll with mouse or programmatically)", "False"}, + {mvPythonDataType::Bool, "no_collapse" ,"Disable user collapsing window by double-clicking on it", "False"}, + {mvPythonDataType::Bool, "horizontal_scrollbar" ,"Allow horizontal scrollbar to appear (off by default).", "False"}, + {mvPythonDataType::Bool, "no_focus_on_appearing" ,"Disable taking focus when transitioning from hidden to visible state", "False"}, + {mvPythonDataType::Bool, "no_bring_to_front_on_focus" ,"Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)", "False"}, + {mvPythonDataType::Bool, "menubar", "", "False"}, + {mvPythonDataType::Bool, "no_close", "", "False"}, + {mvPythonDataType::Bool, "no_background", "", "False"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "collapsed", "Collapse the window", "False"}, + {mvPythonDataType::Callable, "on_close", "Callback ran when window is closed", "None"}, + {mvPythonDataType::IntList, "min_size", "Minimum window size.", "[32, 32]"}, + {mvPythonDataType::IntList, "max_size", "Maximum window size.", "[30000, 30000]"}, + }, "Creates a new window for following items to be added to.", + "None", "Containers") }); + } + + mvWindowAppItem::mvWindowAppItem(const std::string& name, bool mainWindow) + : mvAppItem(name), m_mainWindow(mainWindow) + { + + m_width = 500; + m_height = 500; + + m_oldWindowflags = ImGuiWindowFlags_NoSavedSettings; + + if (mainWindow) + { + m_windowflags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings + | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; + } + } + + mvWindowAppItem::~mvWindowAppItem() + { + mvCallable callback = m_on_close; + mvApp::GetApp()->getCallbackRegistry().submitCallback([callback]() { + if (callback) + Py_XDECREF(callback); + }); + + } + + void mvWindowAppItem::setWindowAsMainStatus(bool value) + { + m_mainWindow = value; + if (value) + { + m_oldWindowflags = m_windowflags; + m_windowflags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings + | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; + + if (m_hasMenuBar) + m_windowflags |= ImGuiWindowFlags_MenuBar; + m_oldxpos = m_xpos; + m_oldypos = m_ypos; + m_oldWidth = m_width; + m_oldHeight = m_height; + } + else + { + m_focusNextFrame = true; + m_windowflags = m_oldWindowflags; + if (m_hasMenuBar) + m_windowflags |= ImGuiWindowFlags_MenuBar; + m_xpos = m_oldxpos; + m_ypos = m_oldypos; + m_width = m_oldWidth; + m_height = m_oldHeight; + m_dirty_pos = true; + m_dirty_size = true; + } + + + } + + void mvWindowAppItem::setWindowPos(float x, float y) + { + m_xpos = (int)x; + m_ypos = (int)y; + m_dirty_pos = true; + } + + void mvWindowAppItem::setWidth(int width) + { + m_width = width; + m_dirty_size = true; + } + + void mvWindowAppItem::setHeight(int height) + { + m_height = height; + m_dirty_size = true; + } + + void mvWindowAppItem::setLabel(const std::string& value) + { + m_specificedlabel = value; + m_label = value + "###" + m_name; + m_dirty_pos = true; + m_dirty_size = true; + } + + mvVec2 mvWindowAppItem::getWindowPos() const + { + return { (float)m_xpos, (float)m_ypos }; + } + + void mvWindowAppItem::setResizeCallback(mvCallable callback) + { + m_resize_callback = callback; + } + + void mvWindowAppItem::draw(ImDrawList* drawlist, float x, float y) + { + // shouldn't have to do this but do. Fix later + if (!m_show) + { + m_state.setHovered(false); + m_state.setFocused(false); + m_state.setActivated(false); + m_state.setVisible(false); + if (!m_closing) + { + m_closing = true; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_on_close, m_name, nullptr); + + } + return; + } + m_closing = false; + + if (m_mainWindow) + { + ImGui::SetNextWindowBgAlpha(1.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); // to prevent main window corners from showing + ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); + ImGui::SetNextWindowSize(ImVec2((float)mvApp::GetApp()->getViewport()->getClientWidth(), (float)mvApp::GetApp()->getViewport()->getClientHeight())); + } + + else if (m_dirty_pos) + { + ImGui::SetNextWindowPos(ImVec2((float)m_xpos, (float)m_ypos)); + m_dirty_pos = false; + } + + else if (m_focusNextFrame) + { + ImGui::SetNextWindowFocus(); + m_focusNextFrame = false; + } + + if (m_dirty_size) + { + ImGui::SetNextWindowSize(ImVec2((float)m_width, (float)m_height)); + m_dirty_size = false; + } + + if (m_collapsedDirty) + { + ImGui::SetNextWindowCollapsed(m_collapsed); + m_collapsedDirty = false; + } + + ImGui::SetNextWindowSizeConstraints(m_min_size, m_max_size); + + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (!ImGui::Begin(m_label.c_str(), m_no_close ? nullptr : &m_show, m_windowflags)) + { + if (m_mainWindow) + ImGui::PopStyleVar(); + + ImGui::End(); + return; + } + + ImDrawList* this_drawlist = ImGui::GetWindowDrawList(); + + float startx = (float)ImGui::GetCursorScreenPos().x; + float starty = (float)ImGui::GetCursorScreenPos().y; + + //we do this so that the children dont get the theme + scope.cleanup(); + + if (m_mainWindow) + ImGui::PopStyleVar(); + + for (auto& item : m_children[0]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + item->draw(this_drawlist, startx, starty); + + item->getState().update(); + + } + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(this_drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + + } + + + + + m_state.setVisible(true); + m_state.setHovered(ImGui::IsWindowHovered()); + m_state.setFocused(ImGui::IsWindowFocused()); + m_state.setRectSize({ ImGui::GetWindowSize().x, ImGui::GetWindowSize().y }); + m_state.setActivated(ImGui::IsWindowCollapsed()); + + if (ImGui::GetWindowWidth() != (float)m_width || ImGui::GetWindowHeight() != (float)m_height) + { + m_width = (int)ImGui::GetWindowWidth(); + m_height = (int)ImGui::GetWindowHeight(); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_resize_callback, m_name, nullptr); + } + + m_width = (int)ImGui::GetWindowWidth(); + m_height = (int)ImGui::GetWindowHeight(); + + if (m_state.isItemFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != m_name) + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", m_name) }); + + } + + m_xpos = (int)ImGui::GetWindowPos().x; + m_ypos = (int)ImGui::GetWindowPos().y; + + ImGui::End(); + + m_collapsed = ImGui::IsWindowCollapsed(); + + } + + void mvWindowAppItem::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "x_pos")) setWindowPos((float)ToInt(item), (float)m_ypos); + if (PyObject* item = PyDict_GetItemString(dict, "y_pos")) setWindowPos((float)m_xpos, (float)ToInt(item)); + if (PyObject* item = PyDict_GetItemString(dict, "no_close")) m_no_close = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "collapsed")) + { + m_collapsedDirty = true; + m_collapsed = ToBool(item); + } + + if (PyObject* item = PyDict_GetItemString(dict, "min_size")) + { + auto min_size = ToIntVect(item); + m_min_size = { (float)min_size[0], (float)min_size[1]}; + } + + if (PyObject* item = PyDict_GetItemString(dict, "max_size")) + { + auto max_size = ToIntVect(item); + m_max_size = { (float)max_size[0], (float)max_size[1] }; + } + + if (PyObject* item = PyDict_GetItemString(dict, "on_close")) + { + if (m_on_close) + Py_XDECREF(m_on_close); + item = SanitizeCallback(item); + if (item) + Py_XINCREF(item); + m_on_close = item; + } + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("autosize", ImGuiWindowFlags_AlwaysAutoResize, m_windowflags); + flagop("no_move", ImGuiWindowFlags_NoMove, m_windowflags); + flagop("no_resize", ImGuiWindowFlags_NoResize, m_windowflags); + flagop("no_title_bar", ImGuiWindowFlags_NoTitleBar, m_windowflags); + flagop("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + flagop("no_collapse", ImGuiWindowFlags_NoCollapse, m_windowflags); + flagop("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + flagop("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, m_windowflags); + flagop("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, m_windowflags); + flagop("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + flagop("no_background", ImGuiWindowFlags_NoBackground, m_windowflags); + + m_oldxpos = m_xpos; + m_oldypos = m_ypos; + m_oldWidth = m_width; + m_oldHeight = m_height; + m_oldWindowflags = m_windowflags; + + } + + void mvWindowAppItem::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "x_pos", ToPyInt(m_xpos)); + PyDict_SetItemString(dict, "y_pos", ToPyInt(m_ypos)); + PyDict_SetItemString(dict, "no_close", ToPyBool(m_no_close)); + PyDict_SetItemString(dict, "collapsed", ToPyBool(m_collapsed)); + PyDict_SetItemString(dict, "min_size", ToPyPair(m_min_size.x, m_min_size.y)); + PyDict_SetItemString(dict, "max_size", ToPyPair(m_min_size.x, m_min_size.y)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("autosize", ImGuiWindowFlags_AlwaysAutoResize, m_windowflags); + checkbitset("no_resize", ImGuiWindowFlags_NoResize, m_windowflags); + checkbitset("no_title_bar", ImGuiWindowFlags_NoTitleBar, m_windowflags); + checkbitset("no_move", ImGuiWindowFlags_NoMove, m_windowflags); + checkbitset("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + checkbitset("no_collapse", ImGuiWindowFlags_NoCollapse, m_windowflags); + checkbitset("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + checkbitset("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, m_windowflags); + checkbitset("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, m_windowflags); + checkbitset("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + checkbitset("no_background", ImGuiWindowFlags_NoBackground, m_windowflags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.h b/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.h new file mode 100644 index 000000000..1382d15c4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/containers/mvWindowAppItem.h @@ -0,0 +1,153 @@ +#pragma once + +#include +#include "mvTypeBases.h" +#include "mvApp.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvWindowAppItem, MV_ITEM_DESC_CONTAINER | MV_ITEM_DESC_ROOT, StorageValueTypes::None, 1); + class mvWindowAppItem : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvWindowAppItem, add_window) + + MV_CREATE_CONSTANT(mvThemeCol_Window_TitleText , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_TitleBg , ImGuiCol_TitleBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_TitleBgActive , ImGuiCol_TitleBgActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_TitleBgCollapsed , ImGuiCol_TitleBgCollapsed , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_MenuBar , ImGuiCol_MenuBarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_Bg , ImGuiCol_WindowBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ScrollbarGrabHovered , ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ResizeBorder , ImGuiCol_SeparatorActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ResizeGrip , ImGuiCol_ResizeGrip , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ResizeGripHovered , ImGuiCol_ResizeGripHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_ResizeGripActive , ImGuiCol_ResizeGripActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Window_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Window_BorderSize , ImGuiStyleVar_WindowBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_Rounding , ImGuiStyleVar_WindowRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_MinSizeX , ImGuiStyleVar_WindowMinSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_MinSizeY , ImGuiStyleVar_WindowMinSize , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_TitleAlignX , ImGuiStyleVar_WindowTitleAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_TitleAlignY , ImGuiStyleVar_WindowTitleAlign , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_PaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_PaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_ItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_ItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_ScrollbarSize , ImGuiStyleVar_ScrollbarSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Window_ScrollbarRounding, ImGuiStyleVar_ScrollbarRounding , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_TitleText, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_TitleBg, mvColor( 10, 10, 10, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_TitleBgActive, mvColor( 41, 74, 122, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_TitleBgCollapsed, mvColor( 0, 0, 0, 130)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_MenuBar, mvColor( 36, 36, 36, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_Bg, mvColor( 15, 15, 15, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_Scrollbar, mvColor( 5, 5, 5, 135)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ScrollbarGrab, mvColor( 79, 79, 79, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ScrollbarGrabHovered, mvColor(105, 105, 105, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ScrollbarGrabActive, mvColor(130, 130, 130, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ResizeBorder, mvColor( 26, 102, 191, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ResizeGrip, mvColor( 66, 150, 250, 42)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ResizeGripHovered, mvColor( 66, 150, 250, 171)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_ResizeGripActive, mvColor( 66, 150, 250, 242)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Window_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Window_BorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Window_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_Window_MinSizeX ,32, 50), + MV_ADD_CONSTANT(mvThemeStyle_Window_MinSizeY ,32, 50), + MV_ADD_CONSTANT(mvThemeStyle_Window_TitleAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Window_TitleAlignY , 0.5, 1), + MV_ADD_CONSTANT(mvThemeStyle_Window_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Window_PaddingY , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Window_ItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Window_ItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Window_ScrollbarSize ,14, 20), + MV_ADD_CONSTANT(mvThemeStyle_Window_ScrollbarRounding , 9, 12), + MV_END_STYLE_CONSTANTS + + enum class Status{ Normal, Transition, Dirty}; + + public: + + mvWindowAppItem(const std::string& name, bool mainWindow = false); + + void addMenuBar () { m_hasMenuBar = true; } + void addFlag (ImGuiWindowFlags flag) { m_windowflags |= flag; } + void removeFlag (ImGuiWindowFlags flag) { m_windowflags &= ~flag; } + void setWindowAsMainStatus(bool value); + void setWindowPos (float x, float y); + void setLabel (const std::string& value) override; + void setWidth (int width) override; + void setHeight (int height) override; + mvVec2 getWindowPos () const; + void draw (ImDrawList* drawlist, float x, float y) override; + void setResizeCallback (mvCallable callback); + bool getWindowAsMainStatus() const { return m_mainWindow; } + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + void setFocusedNextFrame () { m_focusNextFrame = true; } + + ~mvWindowAppItem(); + + private: + + ImGuiWindowFlags m_windowflags = ImGuiWindowFlags_NoSavedSettings; + ImGuiWindowFlags m_oldWindowflags = ImGuiWindowFlags_NoSavedSettings; + int m_oldxpos = 200; + int m_oldypos = 200; + int m_oldWidth = 200; + int m_oldHeight = 200; + bool m_mainWindow = false; + mvCallable m_resize_callback = nullptr; + bool m_dirty_pos = true; + bool m_dirty_size = true; + bool m_hasMenuBar = false; + bool m_focusNextFrame = false; + bool m_closing = true; + bool m_collapsedDirty = true; + + int m_xpos = 200; + int m_ypos = 200; + bool m_autosize = false; + bool m_no_resize = false; + bool m_no_title_bar = false; + bool m_no_move = false; + bool m_no_scrollbar = false; + bool m_no_collapse = false; + bool m_horizontal_scrollbar = false; + bool m_no_focus_on_appearing = false; + bool m_no_bring_to_front_on_focus = false; + bool m_menubar = false; + bool m_no_close = false; + bool m_no_background = false; + bool m_collapsed = false; + mvCallable m_on_close = nullptr; + mvVec2 m_min_size = { 32.0f, 32.0f }; + mvVec2 m_max_size = { 30000.0f, 30000.0f }; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvColorMapScale.cpp b/DearPyGui/src/core/AppItems/custom/mvColorMapScale.cpp new file mode 100644 index 000000000..98850c01a --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvColorMapScale.cpp @@ -0,0 +1,63 @@ +#include "mvColorMapScale.h" +#include "mvTypeBases.h" +#include +#include "mvApp.h" +#include "mvModule_Core.h" +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" +#include + +namespace Marvel { + + void mvColorMapScale::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "default_value", "", "0"}, + {mvPythonDataType::Float, "min_scale", "", "0.0"}, + {mvPythonDataType::Float, "max_scale", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds drag for a single int value. CTRL+Click to directly modify the value.", "None", "Adding Widgets") }); + } + + mvColorMapScale::mvColorMapScale(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvColorMapScale::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImPlot::ColormapScale(m_label.c_str(), m_scale_min, m_scale_max, ImVec2(m_width, m_height), *m_value); + } + + void mvColorMapScale::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "min_scale")) m_scale_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_scale")) m_scale_max = ToFloat(item); + } + + void mvColorMapScale::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + } + +} diff --git a/DearPyGui/src/core/AppItems/custom/mvColorMapScale.h b/DearPyGui/src/core/AppItems/custom/mvColorMapScale.h new file mode 100644 index 000000000..057a9cf3d --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvColorMapScale.h @@ -0,0 +1,48 @@ +#pragma once + +#include "mvTypeBases.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvColorMapScale, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvColorMapScale : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvColorMapScale, add_colormap_scale) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvColorMapScale(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + double m_scale_min = 0; + double m_scale_max = 0; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvDatePicker.cpp b/DearPyGui/src/core/AppItems/custom/mvDatePicker.cpp new file mode 100644 index 000000000..e59947009 --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvDatePicker.cpp @@ -0,0 +1,63 @@ +#include "mvDatePicker.h" +#include "mvApp.h" +#include +#include +#include +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDatePicker::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Dict, "default_value", "data dict", "{'month_day': 14, 'year':20, 'month':5}"}, + {mvPythonDataType::Integer, "level", "0-day, 1-month, 2-year", "0"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a data selector widget.", "None", "Adding Widgets") }); + } + + mvDatePicker::mvDatePicker(const std::string& name) + : mvTimePtrBase(name) + { + } + + void mvDatePicker::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImPlot::ShowDatePicker(m_name.c_str(), &m_level, m_imvalue.get(), m_imvalue.get())) + { + ImPlot::GetGmtTime(*m_imvalue, m_value.get()); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + + } + + void mvDatePicker::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "level")) m_level = ToInt(item); + } + + void mvDatePicker::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "level", ToPyInt(m_level)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvDatePicker.h b/DearPyGui/src/core/AppItems/custom/mvDatePicker.h new file mode 100644 index 000000000..48ffccb3f --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvDatePicker.h @@ -0,0 +1,68 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDatePicker, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Time, 1); + class mvDatePicker : public mvTimePtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDatePicker, add_date_picker) + + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_Date , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_DateBg , ImGuiCol_Button , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_DateDisabled , ImGuiCol_TextDisabled , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_DateHovered , ImGuiCol_ButtonHovered, 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_DateActive , ImGuiCol_ButtonActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_DatePicker_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_DatePicker_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DatePicker_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DatePicker_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_DatePicker_PaddingY , ImGuiStyleVar_FramePadding , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_Date, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_DateBg, mvColor( 41, 74, 122, 138)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_DateDisabled, mvColor(128, 128, 128, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_DateHovered, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_DateActive, mvColor( 15, 135, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_DatePicker_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_DatePicker_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_DatePicker_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_DatePicker_PaddingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_DatePicker_PaddingY , 3, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvDatePicker(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_level = 0; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvTextEditor.cpp b/DearPyGui/src/core/AppItems/custom/mvTextEditor.cpp new file mode 100644 index 000000000..41931c1aa --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvTextEditor.cpp @@ -0,0 +1,3238 @@ +#include +#include +#include +#include +#include +#include "mvTextEditor.h" +#include "mvApp.h" +#include "mvModule_Core.h" +#include "mvImGuiThemeScope.h" + +#define IMGUI_DEFINE_MATH_OPERATORS +#include "imgui.h" // for imGui::GetCurrentWindow() + +namespace Marvel{ + +// TODO +// - multiline comments vs single-line: latter is blocking start of a ML + +template +bool equals(InputIt1 first1, InputIt1 last1, + InputIt2 first2, InputIt2 last2, BinaryPredicate p) +{ + for (; first1 != last1 && first2 != last2; ++first1, ++first2) + { + if (!p(*first1, *first2)) + return false; + } + return first1 == last1 && first2 == last2; +} + +mvTextEditor::mvTextEditor() + : mLineSpacing(1.0f) + , mUndoIndex(0) + , mTabSize(4) + , mOverwrite(false) + , mReadOnly(false) + , mWithinRender(false) + , mScrollToCursor(false) + , mScrollToTop(false) + , mTextChanged(false) + , mColorizerEnabled(true) + , mTextStart(20.0f) + , mLeftMargin(10) + , mCursorPositionChanged(false) + , mColorRangeMin(0) + , mColorRangeMax(0) + , mSelectionMode(SelectionMode::Normal) + , mHandleKeyboardInputs(true) + , mHandleMouseInputs(true) + , mIgnoreImGuiChild(false) + , mShowWhitespaces(true) + , mCheckComments(true) + , mStartTime(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()) + , mLastClick(-1.0f) +{ + SetPalette(GetDarkPalette()); + SetLanguageDefinition(LanguageDefinition::HLSL()); + mLines.push_back(Line()); +} + +mvTextEditor::~mvTextEditor() +{ +} + +void mvTextEditor::SetLanguageDefinition(const LanguageDefinition& aLanguageDef) +{ + mLanguageDefinition = aLanguageDef; + mRegexList.clear(); + + for (auto& r : mLanguageDefinition.mTokenRegexStrings) + mRegexList.push_back(std::make_pair(std::regex(r.first, std::regex_constants::optimize), r.second)); + + Colorize(); +} + +void mvTextEditor::SetPalette(const Palette& aValue) +{ + mPaletteBase = aValue; +} + +std::string mvTextEditor::GetText(const Coordinates& aStart, const Coordinates& aEnd) const +{ + std::string result; + + auto lstart = aStart.mLine; + auto lend = aEnd.mLine; + auto istart = GetCharacterIndex(aStart); + auto iend = GetCharacterIndex(aEnd); + size_t s = 0; + + for (int i = lstart; i < lend; i++) + s += mLines[i].size(); + + result.reserve(s + s / 8); + + while (istart < iend || lstart < lend) + { + if (lstart >= (int)mLines.size()) + break; + + auto& line = mLines[lstart]; + if (istart < (int)line.size()) + { + result += line[istart].mChar; + istart++; + } + else + { + istart = 0; + ++lstart; + result += '\n'; + } + } + + return result; +} + +mvTextEditor::Coordinates mvTextEditor::GetActualCursorCoordinates() const +{ + return SanitizeCoordinates(mState.mCursorPosition); +} + +mvTextEditor::Coordinates mvTextEditor::SanitizeCoordinates(const Coordinates& aValue) const +{ + auto line = aValue.mLine; + auto column = aValue.mColumn; + if (line >= (int)mLines.size()) + { + if (mLines.empty()) + { + line = 0; + column = 0; + } + else + { + line = (int)mLines.size() - 1; + column = GetLineMaxColumn(line); + } + return Coordinates(line, column); + } + else + { + column = mLines.empty() ? 0 : std::min(column, GetLineMaxColumn(line)); + return Coordinates(line, column); + } +} + +// https://en.wikipedia.org/wiki/UTF-8 +// We assume that the char is a standalone character (<128) or a leading byte of an UTF-8 code sequence (non-10xxxxxx code) +static int UTF8CharLength(mvTextEditor::Char c) +{ + if ((c & 0xFE) == 0xFC) + return 6; + if ((c & 0xFC) == 0xF8) + return 5; + if ((c & 0xF8) == 0xF0) + return 4; + else if ((c & 0xF0) == 0xE0) + return 3; + else if ((c & 0xE0) == 0xC0) + return 2; + return 1; +} + +// "Borrowed" from ImGui source +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c) & 0x3f)); + return 3; + } +} + +void mvTextEditor::Advance(Coordinates& aCoordinates) const +{ + if (aCoordinates.mLine < (int)mLines.size()) + { + auto& line = mLines[aCoordinates.mLine]; + auto cindex = GetCharacterIndex(aCoordinates); + + if (cindex + 1 < (int)line.size()) + { + auto delta = UTF8CharLength(line[cindex].mChar); + cindex = std::min(cindex + delta, (int)line.size() - 1); + } + else + { + ++aCoordinates.mLine; + cindex = 0; + } + aCoordinates.mColumn = GetCharacterColumn(aCoordinates.mLine, cindex); + } +} + +void mvTextEditor::DeleteRange(const Coordinates& aStart, const Coordinates& aEnd) +{ + assert(aEnd >= aStart); + assert(!mReadOnly); + + //printf("D(%d.%d)-(%d.%d)\n", aStart.mLine, aStart.mColumn, aEnd.mLine, aEnd.mColumn); + + if (aEnd == aStart) + return; + + auto start = GetCharacterIndex(aStart); + auto end = GetCharacterIndex(aEnd); + + if (aStart.mLine == aEnd.mLine) + { + auto& line = mLines[aStart.mLine]; + auto n = GetLineMaxColumn(aStart.mLine); + if (aEnd.mColumn >= n) + line.erase(line.begin() + start, line.end()); + else + line.erase(line.begin() + start, line.begin() + end); + } + else + { + auto& firstLine = mLines[aStart.mLine]; + auto& lastLine = mLines[aEnd.mLine]; + + firstLine.erase(firstLine.begin() + start, firstLine.end()); + lastLine.erase(lastLine.begin(), lastLine.begin() + end); + + if (aStart.mLine < aEnd.mLine) + { + firstLine.insert(firstLine.end(), lastLine.begin(), lastLine.end()); + RemoveLine(aStart.mLine + 1, aEnd.mLine + 1); + } + } + + mTextChanged = true; +} + +int mvTextEditor::InsertTextAt(Coordinates& /* inout */ aWhere, const char* aValue) +{ + assert(!mReadOnly); + + int cindex = GetCharacterIndex(aWhere); + int totalLines = 0; + while (*aValue != '\0') + { + assert(!mLines.empty()); + + if (*aValue == '\r') + { + // skip + ++aValue; + } + else if (*aValue == '\n') + { + if (cindex < (int)mLines[aWhere.mLine].size()) + { + auto& newLine = InsertLine(aWhere.mLine + 1); + auto& line = mLines[aWhere.mLine]; + newLine.insert(newLine.begin(), line.begin() + cindex, line.end()); + line.erase(line.begin() + cindex, line.end()); + } + else + { + InsertLine(aWhere.mLine + 1); + } + ++aWhere.mLine; + aWhere.mColumn = 0; + cindex = 0; + ++totalLines; + ++aValue; + } + else + { + auto& line = mLines[aWhere.mLine]; + auto d = UTF8CharLength(*aValue); + while (d-- > 0 && *aValue != '\0') + line.insert(line.begin() + cindex++, Glyph(*aValue++, PaletteIndex::Default)); + ++aWhere.mColumn; + } + + mTextChanged = true; + } + + return totalLines; +} + +void mvTextEditor::AddUndo(UndoRecord& aValue) +{ + assert(!mReadOnly); + //printf("AddUndo: (@%d.%d) +\'%s' [%d.%d .. %d.%d], -\'%s', [%d.%d .. %d.%d] (@%d.%d)\n", + // aValue.mBefore.mCursorPosition.mLine, aValue.mBefore.mCursorPosition.mColumn, + // aValue.mAdded.c_str(), aValue.mAddedStart.mLine, aValue.mAddedStart.mColumn, aValue.mAddedEnd.mLine, aValue.mAddedEnd.mColumn, + // aValue.mRemoved.c_str(), aValue.mRemovedStart.mLine, aValue.mRemovedStart.mColumn, aValue.mRemovedEnd.mLine, aValue.mRemovedEnd.mColumn, + // aValue.mAfter.mCursorPosition.mLine, aValue.mAfter.mCursorPosition.mColumn + // ); + + mUndoBuffer.resize((size_t)(mUndoIndex + 1)); + mUndoBuffer.back() = aValue; + ++mUndoIndex; +} + +mvTextEditor::Coordinates mvTextEditor::ScreenPosToCoordinates(const ImVec2& aPosition) const +{ + ImVec2 origin = ImGui::GetCursorScreenPos(); + ImVec2 local(aPosition.x - origin.x, aPosition.y - origin.y); + + int lineNo = std::max(0, (int)floor(local.y / mCharAdvance.y)); + + int columnCoord = 0; + + if (lineNo >= 0 && lineNo < (int)mLines.size()) + { + auto& line = mLines.at(lineNo); + + int columnIndex = 0; + float columnX = 0.0f; + + while ((size_t)columnIndex < line.size()) + { + float columnWidth = 0.0f; + + if (line[columnIndex].mChar == '\t') + { + float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ").x; + float oldX = columnX; + float newColumnX = (1.0f + std::floor((1.0f + columnX) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); + columnWidth = newColumnX - oldX; + if (mTextStart + columnX + columnWidth * 0.5f > local.x) + break; + columnX = newColumnX; + columnCoord = (columnCoord / mTabSize) * mTabSize + mTabSize; + columnIndex++; + } + else + { + char buf[7]; + auto d = UTF8CharLength(line[columnIndex].mChar); + int i = 0; + while (i < 6 && d-- > 0) + buf[i++] = line[columnIndex++].mChar; + buf[i] = '\0'; + columnWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf).x; + if (mTextStart + columnX + columnWidth * 0.5f > local.x) + break; + columnX += columnWidth; + columnCoord++; + } + } + } + + return SanitizeCoordinates(Coordinates(lineNo, columnCoord)); +} + +mvTextEditor::Coordinates mvTextEditor::FindWordStart(const Coordinates& aFrom) const +{ + Coordinates at = aFrom; + if (at.mLine >= (int)mLines.size()) + return at; + + auto& line = mLines[at.mLine]; + auto cindex = GetCharacterIndex(at); + + if (cindex >= (int)line.size()) + return at; + + while (cindex > 0 && isspace(line[cindex].mChar)) + --cindex; + + auto cstart = (PaletteIndex)line[cindex].mColorIndex; + while (cindex > 0) + { + auto c = line[cindex].mChar; + if ((c & 0xC0) != 0x80) // not UTF code sequence 10xxxxxx + { + if (c <= 32 && isspace(c)) + { + cindex++; + break; + } + if (cstart != (PaletteIndex)line[size_t(cindex - 1)].mColorIndex) + break; + } + --cindex; + } + return Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex)); +} + +mvTextEditor::Coordinates mvTextEditor::FindWordEnd(const Coordinates& aFrom) const +{ + Coordinates at = aFrom; + if (at.mLine >= (int)mLines.size()) + return at; + + auto& line = mLines[at.mLine]; + auto cindex = GetCharacterIndex(at); + + if (cindex >= (int)line.size()) + return at; + + bool prevspace = (bool)isspace(line[cindex].mChar); + auto cstart = (PaletteIndex)line[cindex].mColorIndex; + while (cindex < (int)line.size()) + { + auto c = line[cindex].mChar; + auto d = UTF8CharLength(c); + if (cstart != (PaletteIndex)line[cindex].mColorIndex) + break; + + if (prevspace != !!isspace(c)) + { + if (isspace(c)) + while (cindex < (int)line.size() && isspace(line[cindex].mChar)) + ++cindex; + break; + } + cindex += d; + } + return Coordinates(aFrom.mLine, GetCharacterColumn(aFrom.mLine, cindex)); +} + +mvTextEditor::Coordinates mvTextEditor::FindNextWord(const Coordinates& aFrom) const +{ + Coordinates at = aFrom; + if (static_cast(at.mLine) >= mLines.size()) + return at; + + // skip to the next non-word character + auto cindex = GetCharacterIndex(aFrom); + bool isword = false; + bool skip = false; + if (static_cast(cindex) < mLines[at.mLine].size()) + { + auto& line = mLines[at.mLine]; + isword = isalnum(line[cindex].mChar); + skip = isword; + } + + while (!isword || skip) + { + if (static_cast(at.mLine) >= mLines.size()) + { + auto l = std::max(0, (int)mLines.size() - 1); + return Coordinates(l, GetLineMaxColumn(l)); + } + + auto& line = mLines[at.mLine]; + if (static_cast(cindex) < line.size()) + { + isword = isalnum(line[cindex].mChar); + + if (isword && !skip) + return Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex)); + + if (!isword) + skip = false; + + cindex++; + } + else + { + cindex = 0; + ++at.mLine; + skip = false; + isword = false; + } + } + + return at; +} + +int mvTextEditor::GetCharacterIndex(const Coordinates& aCoordinates) const +{ + if (static_cast(aCoordinates.mLine) >= mLines.size()) + return -1; + auto& line = mLines[aCoordinates.mLine]; + int c = 0; + size_t i = 0; + for (; i < line.size() && c < aCoordinates.mColumn;) + { + if (line[i].mChar == '\t') + c = (c / mTabSize) * mTabSize + mTabSize; + else + ++c; + i += UTF8CharLength(line[i].mChar); + } + return (int)i; +} + +int mvTextEditor::GetCharacterColumn(int aLine, int aIndex) const +{ + if (static_cast(aLine) >= mLines.size()) + return 0; + auto& line = mLines[aLine]; + int col = 0; + size_t i = 0; + while (i < static_cast(aIndex) && i < line.size()) + { + auto c = line[i].mChar; + i += UTF8CharLength(c); + if (c == '\t') + col = (col / mTabSize) * mTabSize + mTabSize; + else + col++; + } + return col; +} + +int mvTextEditor::GetLineCharacterCount(int aLine) const +{ + if (static_cast(aLine) >= mLines.size()) + return 0; + auto& line = mLines[aLine]; + int c = 0; + for (unsigned i = 0; i < line.size(); c++) + i += UTF8CharLength(line[i].mChar); + return c; +} + +int mvTextEditor::GetLineMaxColumn(int aLine) const +{ + if (static_cast(aLine) >= mLines.size()) + return 0; + auto& line = mLines[aLine]; + int col = 0; + for (unsigned i = 0; i < line.size(); ) + { + auto c = line[i].mChar; + if (c == '\t') + col = (col / mTabSize) * mTabSize + mTabSize; + else + col++; + i += UTF8CharLength(c); + } + return col; +} + +bool mvTextEditor::IsOnWordBoundary(const Coordinates& aAt) const +{ + if (aAt.mLine >= (int)mLines.size() || aAt.mColumn == 0) + return true; + + auto& line = mLines[aAt.mLine]; + auto cindex = GetCharacterIndex(aAt); + if (cindex >= (int)line.size()) + return true; + + if (mColorizerEnabled) + return line[cindex].mColorIndex != line[size_t(cindex - 1)].mColorIndex; + + return isspace(line[cindex].mChar) != isspace(line[cindex - 1].mChar); +} + +void mvTextEditor::RemoveLine(int aStart, int aEnd) +{ + assert(!mReadOnly); + assert(aEnd >= aStart); + assert(mLines.size() > (size_t)(aEnd - aStart)); + + ErrorMarkers etmp; + for (auto& i : mErrorMarkers) + { + ErrorMarkers::value_type e(i.first >= aStart ? i.first - 1 : i.first, i.second); + if (e.first >= aStart && e.first <= aEnd) + continue; + etmp.insert(e); + } + mErrorMarkers = std::move(etmp); + + Breakpoints btmp; + for (auto i : mBreakpoints) + { + if (i >= aStart && i <= aEnd) + continue; + btmp.insert(i >= aStart ? i - 1 : i); + } + mBreakpoints = std::move(btmp); + + mLines.erase(mLines.begin() + aStart, mLines.begin() + aEnd); + assert(!mLines.empty()); + + mTextChanged = true; +} + +void mvTextEditor::RemoveLine(int aIndex) +{ + assert(!mReadOnly); + assert(mLines.size() > 1); + + ErrorMarkers etmp; + for (auto& i : mErrorMarkers) + { + ErrorMarkers::value_type e(i.first > aIndex ? i.first - 1 : i.first, i.second); + if (e.first - 1 == aIndex) + continue; + etmp.insert(e); + } + mErrorMarkers = std::move(etmp); + + Breakpoints btmp; + for (auto i : mBreakpoints) + { + if (i == aIndex) + continue; + btmp.insert(i >= aIndex ? i - 1 : i); + } + mBreakpoints = std::move(btmp); + + mLines.erase(mLines.begin() + aIndex); + assert(!mLines.empty()); + + mTextChanged = true; +} + +mvTextEditor::Line& mvTextEditor::InsertLine(int aIndex) +{ + assert(!mReadOnly); + + auto& result = *mLines.insert(mLines.begin() + aIndex, Line()); + + ErrorMarkers etmp; + for (auto& i : mErrorMarkers) + etmp.insert(ErrorMarkers::value_type(i.first >= aIndex ? i.first + 1 : i.first, i.second)); + mErrorMarkers = std::move(etmp); + + Breakpoints btmp; + for (auto i : mBreakpoints) + btmp.insert(i >= aIndex ? i + 1 : i); + mBreakpoints = std::move(btmp); + + return result; +} + +std::string mvTextEditor::GetWordUnderCursor() const +{ + auto c = GetCursorPosition(); + return GetWordAt(c); +} + +std::string mvTextEditor::GetWordAt(const Coordinates& aCoords) const +{ + auto start = FindWordStart(aCoords); + auto end = FindWordEnd(aCoords); + + std::string r; + + auto istart = GetCharacterIndex(start); + auto iend = GetCharacterIndex(end); + + for (auto it = istart; it < iend; ++it) + r.push_back(mLines[aCoords.mLine][it].mChar); + + return r; +} + +ImU32 mvTextEditor::GetGlyphColor(const Glyph& aGlyph) const +{ + if (!mColorizerEnabled) + return mPalette[(int)PaletteIndex::Default]; + if (aGlyph.mComment) + return mPalette[(int)PaletteIndex::Comment]; + if (aGlyph.mMultiLineComment) + return mPalette[(int)PaletteIndex::MultiLineComment]; + auto const color = mPalette[(int)aGlyph.mColorIndex]; + if (aGlyph.mPreprocessor) + { + const auto ppcolor = mPalette[(int)PaletteIndex::Preprocessor]; + const int c0 = ((ppcolor & 0xff) + (color & 0xff)) / 2; + const int c1 = (((ppcolor >> 8) & 0xff) + ((color >> 8) & 0xff)) / 2; + const int c2 = (((ppcolor >> 16) & 0xff) + ((color >> 16) & 0xff)) / 2; + const int c3 = (((ppcolor >> 24) & 0xff) + ((color >> 24) & 0xff)) / 2; + return ImU32(c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)); + } + return color; +} + +void mvTextEditor::HandleKeyboardInputs() +{ + ImGuiIO& io = ImGui::GetIO(); + auto shift = io.KeyShift; + auto ctrl = io.ConfigMacOSXBehaviors ? io.KeySuper : io.KeyCtrl; + auto alt = io.ConfigMacOSXBehaviors ? io.KeyCtrl : io.KeyAlt; + + if (ImGui::IsWindowFocused()) + { + if (ImGui::IsWindowHovered()) + ImGui::SetMouseCursor(ImGuiMouseCursor_TextInput); + //ImGui::CaptureKeyboardFromApp(true); + + io.WantCaptureKeyboard = true; + io.WantTextInput = true; + + if (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Z))) + Undo(); + else if (!IsReadOnly() && !ctrl && !shift && alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Backspace))) + Undo(); + else if (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Y))) + Redo(); + else if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow))) + MoveUp(1, shift); + else if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow))) + MoveDown(1, shift); + else if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow))) + MoveLeft(1, shift, ctrl); + else if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow))) + MoveRight(1, shift, ctrl); + else if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_PageUp))) + MoveUp(GetPageSize() - 4, shift); + else if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_PageDown))) + MoveDown(GetPageSize() - 4, shift); + else if (!alt && ctrl && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Home))) + MoveTop(shift); + else if (ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_End))) + MoveBottom(shift); + else if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Home))) + MoveHome(shift); + else if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_End))) + MoveEnd(shift); + else if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete))) + Delete(); + else if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Backspace))) + Backspace(); + else if (!ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert))) + mOverwrite ^= true; + else if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert))) + Copy(); + else if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C))) + Copy(); + else if (!IsReadOnly() && !ctrl && shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert))) + Paste(); + else if (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_V))) + Paste(); + else if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_X))) + Cut(); + else if (!ctrl && shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete))) + Cut(); + else if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_A))) + SelectAll(); + else if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Enter))) + EnterCharacter('\n', false); + else if (!IsReadOnly() && !ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Tab))) + EnterCharacter('\t', shift); + + + if (!IsReadOnly() && !io.InputQueueCharacters.empty()) + { + for (int i = 0; i < io.InputQueueCharacters.Size; i++) + { + auto c = io.InputQueueCharacters[i]; + if (c != 0 && (c == '\n' || c >= 32)) + EnterCharacter(c, shift); + } + io.InputQueueCharacters.resize(0); + } + } +} + +void mvTextEditor::HandleMouseInputs() +{ + ImGuiIO& io = ImGui::GetIO(); + auto shift = io.KeyShift; + auto ctrl = io.ConfigMacOSXBehaviors ? io.KeySuper : io.KeyCtrl; + auto alt = io.ConfigMacOSXBehaviors ? io.KeyCtrl : io.KeyAlt; + + if (ImGui::IsWindowHovered()) + { + if (!shift && !alt) + { + auto click = ImGui::IsMouseClicked(0); + auto doubleClick = ImGui::IsMouseDoubleClicked(0); + auto t = ImGui::GetTime(); + auto tripleClick = click && !doubleClick && (mLastClick != -1.0f && (t - mLastClick) < io.MouseDoubleClickTime); + + /* + Left mouse button triple click + */ + + if (tripleClick) + { + if (!ctrl) + { + mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos()); + mSelectionMode = SelectionMode::Line; + SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); + } + + mLastClick = -1.0f; + } + + /* + Left mouse button double click + */ + + else if (doubleClick) + { + if (!ctrl) + { + mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos()); + if (mSelectionMode == SelectionMode::Line) + mSelectionMode = SelectionMode::Normal; + else + mSelectionMode = SelectionMode::Word; + SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); + } + + mLastClick = (float)ImGui::GetTime(); + } + + /* + Left mouse button click + */ + else if (click) + { + mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos()); + if (ctrl) + mSelectionMode = SelectionMode::Word; + else + mSelectionMode = SelectionMode::Normal; + SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); + + mLastClick = (float)ImGui::GetTime(); + } + // Mouse left button dragging (=> update selection) + else if (ImGui::IsMouseDragging(0) && ImGui::IsMouseDown(0)) + { + io.WantCaptureMouse = true; + mState.mCursorPosition = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos()); + SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); + } + } + } +} + +void mvTextEditor::Render() +{ + /* Compute mCharAdvance regarding to scaled font size (Ctrl + mouse wheel)*/ + const float fontSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, "#", nullptr, nullptr).x; + mCharAdvance = ImVec2(fontSize, ImGui::GetTextLineHeightWithSpacing() * mLineSpacing); + + /* Update palette with the current alpha from style */ + for (int i = 0; i < (int)PaletteIndex::Max; ++i) + { + auto color = ImGui::ColorConvertU32ToFloat4(mPaletteBase[i]); + color.w *= ImGui::GetStyle().Alpha; + mPalette[i] = ImGui::ColorConvertFloat4ToU32(color); + } + + assert(mLineBuffer.empty()); + + auto contentSize = ImGui::GetWindowContentRegionMax(); + auto drawList = ImGui::GetWindowDrawList(); + float longest(mTextStart); + + if (mScrollToTop) + { + mScrollToTop = false; + ImGui::SetScrollY(0.f); + } + + ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos(); + auto scrollX = ImGui::GetScrollX(); + auto scrollY = ImGui::GetScrollY(); + + auto lineNo = (int)floor(scrollY / mCharAdvance.y); + auto globalLineMax = (int)mLines.size(); + auto lineMax = std::max(0, std::min((int)mLines.size() - 1, lineNo + (int)floor((scrollY + contentSize.y) / mCharAdvance.y))); + + // Deduce mTextStart by evaluating mLines size (global lineMax) plus two spaces as text width + char buf[16]; + snprintf(buf, 16, " %d ", globalLineMax); + mTextStart = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x + mLeftMargin; + + if (!mLines.empty()) + { + float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ", nullptr, nullptr).x; + + while (lineNo <= lineMax) + { + ImVec2 lineStartScreenPos = ImVec2(cursorScreenPos.x, cursorScreenPos.y + lineNo * mCharAdvance.y); + ImVec2 textScreenPos = ImVec2(lineStartScreenPos.x + mTextStart, lineStartScreenPos.y); + + auto& line = mLines[lineNo]; + longest = std::max(mTextStart + TextDistanceToLineStart(Coordinates(lineNo, GetLineMaxColumn(lineNo))), longest); + auto columnNo = 0; + Coordinates lineStartCoord(lineNo, 0); + Coordinates lineEndCoord(lineNo, GetLineMaxColumn(lineNo)); + + // Draw selection for the current line + float sstart = -1.0f; + float ssend = -1.0f; + + assert(mState.mSelectionStart <= mState.mSelectionEnd); + if (mState.mSelectionStart <= lineEndCoord) + sstart = mState.mSelectionStart > lineStartCoord ? TextDistanceToLineStart(mState.mSelectionStart) : 0.0f; + if (mState.mSelectionEnd > lineStartCoord) + ssend = TextDistanceToLineStart(mState.mSelectionEnd < lineEndCoord ? mState.mSelectionEnd : lineEndCoord); + + if (mState.mSelectionEnd.mLine > lineNo) + ssend += mCharAdvance.x; + + if (sstart != -1 && ssend != -1 && sstart < ssend) + { + ImVec2 vstart(lineStartScreenPos.x + mTextStart + sstart, lineStartScreenPos.y); + ImVec2 vend(lineStartScreenPos.x + mTextStart + ssend, lineStartScreenPos.y + mCharAdvance.y); + drawList->AddRectFilled(vstart, vend, mPalette[(int)PaletteIndex::Selection]); + } + + // Draw breakpoints + auto start = ImVec2(lineStartScreenPos.x + scrollX, lineStartScreenPos.y); + + if (mBreakpoints.count(lineNo + 1) != 0) + { + auto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y); + drawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::Breakpoint]); + } + + // Draw error markers + auto errorIt = mErrorMarkers.find(lineNo + 1); + if (errorIt != mErrorMarkers.end()) + { + auto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y); + drawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::ErrorMarker]); + + if (ImGui::IsMouseHoveringRect(lineStartScreenPos, end)) + { + ImGui::BeginTooltip(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.2f, 0.2f, 1.0f)); + ImGui::Text("Error at line %d:", errorIt->first); + ImGui::PopStyleColor(); + ImGui::Separator(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.2f, 1.0f)); + ImGui::Text("%s", errorIt->second.c_str()); + ImGui::PopStyleColor(); + ImGui::EndTooltip(); + } + } + + // Draw line number (right aligned) + snprintf(buf, 16, "%d ", lineNo + 1); + + auto lineNoWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x; + drawList->AddText(ImVec2(lineStartScreenPos.x + mTextStart - lineNoWidth, lineStartScreenPos.y), mPalette[(int)PaletteIndex::LineNumber], buf); + + if (mState.mCursorPosition.mLine == lineNo) + { + auto focused = ImGui::IsWindowFocused(); + + // Highlight the current line (where the cursor is) + if (!HasSelection()) + { + auto end = ImVec2(start.x + contentSize.x + scrollX, start.y + mCharAdvance.y); + drawList->AddRectFilled(start, end, mPalette[(int)(focused ? PaletteIndex::CurrentLineFill : PaletteIndex::CurrentLineFillInactive)]); + drawList->AddRect(start, end, mPalette[(int)PaletteIndex::CurrentLineEdge], 1.0f); + } + + // Render the cursor + if (focused) + { + auto timeEnd = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto elapsed = timeEnd - mStartTime; + if (elapsed > 400) + { + float width = 1.0f; + auto cindex = GetCharacterIndex(mState.mCursorPosition); + float cx = TextDistanceToLineStart(mState.mCursorPosition); + + if (mOverwrite && cindex < (int)line.size()) + { + auto c = line[cindex].mChar; + if (c == '\t') + { + auto x = (1.0f + std::floor((1.0f + cx) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); + width = x - cx; + } + else + { + char buf2[2]; + buf2[0] = line[cindex].mChar; + buf2[1] = '\0'; + width = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf2).x; + } + } + ImVec2 cstart(textScreenPos.x + cx, lineStartScreenPos.y); + ImVec2 cend(textScreenPos.x + cx + width, lineStartScreenPos.y + mCharAdvance.y); + drawList->AddRectFilled(cstart, cend, mPalette[(int)PaletteIndex::Cursor]); + if (elapsed > 800) + mStartTime = timeEnd; + } + } + } + + // Render colorized text + auto prevColor = line.empty() ? mPalette[(int)PaletteIndex::Default] : GetGlyphColor(line[0]); + ImVec2 bufferOffset; + + for (size_t i = 0; i < line.size();) + { + auto& glyph = line[i]; + auto color = GetGlyphColor(glyph); + + if ((color != prevColor || glyph.mChar == '\t' || glyph.mChar == ' ') && !mLineBuffer.empty()) + { + const ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y); + drawList->AddText(newOffset, prevColor, mLineBuffer.c_str()); + auto textSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, mLineBuffer.c_str(), nullptr, nullptr); + bufferOffset.x += textSize.x; + mLineBuffer.clear(); + } + prevColor = color; + + if (glyph.mChar == '\t') + { + auto oldX = bufferOffset.x; + bufferOffset.x = (1.0f + std::floor((1.0f + bufferOffset.x) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); + ++i; + + if (mShowWhitespaces) + { + const auto s = ImGui::GetFontSize(); + const auto x1 = textScreenPos.x + oldX + 1.0f; + const auto x2 = textScreenPos.x + bufferOffset.x - 1.0f; + const auto y = textScreenPos.y + bufferOffset.y + s * 0.5f; + const ImVec2 p1(x1, y); + const ImVec2 p2(x2, y); + const ImVec2 p3(x2 - s * 0.2f, y - s * 0.2f); + const ImVec2 p4(x2 - s * 0.2f, y + s * 0.2f); + drawList->AddLine(p1, p2, 0x90909090); + drawList->AddLine(p2, p3, 0x90909090); + drawList->AddLine(p2, p4, 0x90909090); + } + } + else if (glyph.mChar == ' ') + { + if (mShowWhitespaces) + { + const auto s = ImGui::GetFontSize(); + const auto x = textScreenPos.x + bufferOffset.x + spaceSize * 0.5f; + const auto y = textScreenPos.y + bufferOffset.y + s * 0.5f; + drawList->AddCircleFilled(ImVec2(x, y), 1.5f, 0x80808080, 4); + } + bufferOffset.x += spaceSize; + i++; + } + else + { + auto l = UTF8CharLength(glyph.mChar); + while (l-- > 0) + mLineBuffer.push_back(line[i++].mChar); + } + ++columnNo; + } + + if (!mLineBuffer.empty()) + { + const ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y); + drawList->AddText(newOffset, prevColor, mLineBuffer.c_str()); + mLineBuffer.clear(); + } + + ++lineNo; + } + + // Draw a tooltip on known identifiers/preprocessor symbols + if (ImGui::IsMousePosValid() && ImGui::IsWindowHovered()) + { + auto id = GetWordAt(ScreenPosToCoordinates(ImGui::GetMousePos())); + if (!id.empty()) + { + auto it = mLanguageDefinition.mIdentifiers.find(id); + if (it != mLanguageDefinition.mIdentifiers.end()) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(it->second.mDeclaration.c_str()); + ImGui::EndTooltip(); + } + else + { + auto pi = mLanguageDefinition.mPreprocIdentifiers.find(id); + if (pi != mLanguageDefinition.mPreprocIdentifiers.end()) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(pi->second.mDeclaration.c_str()); + ImGui::EndTooltip(); + } + } + } + } + } + + + ImGui::Dummy(ImVec2((longest + 2), mLines.size() * mCharAdvance.y)); + + if (mScrollToCursor) + { + EnsureCursorVisible(); + ImGui::SetWindowFocus(); + mScrollToCursor = false; + } +} + +void mvTextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder) +{ + mWithinRender = true; + mTextChanged = false; + mCursorPositionChanged = false; + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background])); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); + if (!mIgnoreImGuiChild) + ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NoMove); + + if (mHandleKeyboardInputs) + { + HandleKeyboardInputs(); + ImGui::PushAllowKeyboardFocus(true); + } + + if (mHandleMouseInputs) + HandleMouseInputs(); + + ColorizeInternal(); + Render(); + + if (mHandleKeyboardInputs) + ImGui::PopAllowKeyboardFocus(); + + if (!mIgnoreImGuiChild) + ImGui::EndChild(); + + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + + mWithinRender = false; +} + +void mvTextEditor::SetText(const std::string& aText) +{ + mLines.clear(); + mLines.emplace_back(Line()); + for (auto chr : aText) + { + if (chr == '\r') + { + // ignore the carriage return character + } + else if (chr == '\n') + mLines.emplace_back(Line()); + else + { + mLines.back().emplace_back(Glyph(chr, PaletteIndex::Default)); + } + } + + mTextChanged = true; + mScrollToTop = true; + + mUndoBuffer.clear(); + mUndoIndex = 0; + + Colorize(); +} + +void mvTextEditor::SetTextLines(const std::vector& aLines) +{ + mLines.clear(); + + if (aLines.empty()) + { + mLines.emplace_back(Line()); + } + else + { + mLines.resize(aLines.size()); + + for (size_t i = 0; i < aLines.size(); ++i) + { + const std::string& aLine = aLines[i]; + + mLines[i].reserve(aLine.size()); + for (size_t j = 0; j < aLine.size(); ++j) + mLines[i].emplace_back(Glyph(aLine[j], PaletteIndex::Default)); + } + } + + mTextChanged = true; + mScrollToTop = true; + + mUndoBuffer.clear(); + mUndoIndex = 0; + + Colorize(); +} + +void mvTextEditor::EnterCharacter(ImWchar aChar, bool aShift) +{ + assert(!mReadOnly); + + UndoRecord u; + + u.mBefore = mState; + + if (HasSelection()) + { + if (aChar == '\t' && mState.mSelectionStart.mLine != mState.mSelectionEnd.mLine) + { + + auto start = mState.mSelectionStart; + auto end = mState.mSelectionEnd; + auto originalEnd = end; + + if (start > end) + std::swap(start, end); + start.mColumn = 0; + // end.mColumn = end.mLine < mLines.size() ? mLines[end.mLine].size() : 0; + if (end.mColumn == 0 && end.mLine > 0) + --end.mLine; + if (end.mLine >= (int)mLines.size()) + end.mLine = mLines.empty() ? 0 : (int)mLines.size() - 1; + end.mColumn = GetLineMaxColumn(end.mLine); + + //if (end.mColumn >= GetLineMaxColumn(end.mLine)) + // end.mColumn = GetLineMaxColumn(end.mLine) - 1; + + u.mRemovedStart = start; + u.mRemovedEnd = end; + u.mRemoved = GetText(start, end); + + bool modified = false; + + for (int i = start.mLine; i <= end.mLine; i++) + { + auto& line = mLines[i]; + if (aShift) + { + if (!line.empty()) + { + if (line.front().mChar == '\t') + { + line.erase(line.begin()); + modified = true; + } + else + { + for (int j = 0; j < mTabSize && !line.empty() && line.front().mChar == ' '; j++) + { + line.erase(line.begin()); + modified = true; + } + } + } + } + else + { + line.insert(line.begin(), Glyph('\t', mvTextEditor::PaletteIndex::Background)); + modified = true; + } + } + + if (modified) + { + start = Coordinates(start.mLine, GetCharacterColumn(start.mLine, 0)); + Coordinates rangeEnd; + if (originalEnd.mColumn != 0) + { + end = Coordinates(end.mLine, GetLineMaxColumn(end.mLine)); + rangeEnd = end; + u.mAdded = GetText(start, end); + } + else + { + end = Coordinates(originalEnd.mLine, 0); + rangeEnd = Coordinates(end.mLine - 1, GetLineMaxColumn(end.mLine - 1)); + u.mAdded = GetText(start, rangeEnd); + } + + u.mAddedStart = start; + u.mAddedEnd = rangeEnd; + u.mAfter = mState; + + mState.mSelectionStart = start; + mState.mSelectionEnd = end; + AddUndo(u); + + mTextChanged = true; + + EnsureCursorVisible(); + } + + return; + } // c == '\t' + else + { + u.mRemoved = GetSelectedText(); + u.mRemovedStart = mState.mSelectionStart; + u.mRemovedEnd = mState.mSelectionEnd; + DeleteSelection(); + } + } // HasSelection + + auto coord = GetActualCursorCoordinates(); + u.mAddedStart = coord; + + assert(!mLines.empty()); + + if (aChar == '\n') + { + InsertLine(coord.mLine + 1); + auto& line = mLines[coord.mLine]; + auto& newLine = mLines[coord.mLine + 1]; + + if (mLanguageDefinition.mAutoIndentation) + for (size_t it = 0; it < line.size() && isascii(line[it].mChar) && isblank(line[it].mChar); ++it) + newLine.push_back(line[it]); + + const size_t whitespaceSize = newLine.size(); + auto cindex = GetCharacterIndex(coord); + newLine.insert(newLine.end(), line.begin() + cindex, line.end()); + line.erase(line.begin() + cindex, line.begin() + line.size()); + SetCursorPosition(Coordinates(coord.mLine + 1, GetCharacterColumn(coord.mLine + 1, (int)whitespaceSize))); + u.mAdded = (char)aChar; + } + else + { + char buf[7]; + int e = ImTextCharToUtf8(buf, 7, aChar); + if (e > 0) + { + buf[e] = '\0'; + auto& line = mLines[coord.mLine]; + auto cindex = GetCharacterIndex(coord); + + if (mOverwrite && cindex < (int)line.size()) + { + auto d = UTF8CharLength(line[cindex].mChar); + + u.mRemovedStart = mState.mCursorPosition; + u.mRemovedEnd = Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex + d)); + + while (d-- > 0 && cindex < (int)line.size()) + { + u.mRemoved += line[cindex].mChar; + line.erase(line.begin() + cindex); + } + } + + for (auto p = buf; *p != '\0'; p++, ++cindex) + line.insert(line.begin() + cindex, Glyph(*p, PaletteIndex::Default)); + u.mAdded = buf; + + SetCursorPosition(Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex))); + } + else + return; + } + + mTextChanged = true; + + u.mAddedEnd = GetActualCursorCoordinates(); + u.mAfter = mState; + + AddUndo(u); + + Colorize(coord.mLine - 1, 3); + EnsureCursorVisible(); +} + +void mvTextEditor::SetReadOnly(bool aValue) +{ + mReadOnly = aValue; +} + +void mvTextEditor::SetColorizerEnable(bool aValue) +{ + mColorizerEnabled = aValue; +} + +void mvTextEditor::SetCursorPosition(const Coordinates& aPosition) +{ + if (mState.mCursorPosition != aPosition) + { + mState.mCursorPosition = aPosition; + mCursorPositionChanged = true; + EnsureCursorVisible(); + } +} + +void mvTextEditor::SetSelectionStart(const Coordinates& aPosition) +{ + mState.mSelectionStart = SanitizeCoordinates(aPosition); + if (mState.mSelectionStart > mState.mSelectionEnd) + std::swap(mState.mSelectionStart, mState.mSelectionEnd); +} + +void mvTextEditor::SetSelectionEnd(const Coordinates& aPosition) +{ + mState.mSelectionEnd = SanitizeCoordinates(aPosition); + if (mState.mSelectionStart > mState.mSelectionEnd) + std::swap(mState.mSelectionStart, mState.mSelectionEnd); +} + +void mvTextEditor::SetSelection(const Coordinates& aStart, const Coordinates& aEnd, SelectionMode aMode) +{ + auto oldSelStart = mState.mSelectionStart; + auto oldSelEnd = mState.mSelectionEnd; + + mState.mSelectionStart = SanitizeCoordinates(aStart); + mState.mSelectionEnd = SanitizeCoordinates(aEnd); + if (mState.mSelectionStart > mState.mSelectionEnd) + std::swap(mState.mSelectionStart, mState.mSelectionEnd); + + switch (aMode) + { + case mvTextEditor::SelectionMode::Normal: + break; + case mvTextEditor::SelectionMode::Word: + { + mState.mSelectionStart = FindWordStart(mState.mSelectionStart); + if (!IsOnWordBoundary(mState.mSelectionEnd)) + mState.mSelectionEnd = FindWordEnd(FindWordStart(mState.mSelectionEnd)); + break; + } + case mvTextEditor::SelectionMode::Line: + { + const auto lineNo = mState.mSelectionEnd.mLine; + //const auto lineSize = static_cast(lineNo) < mLines.size() ? mLines[lineNo].size() : 0; + mState.mSelectionStart = Coordinates(mState.mSelectionStart.mLine, 0); + mState.mSelectionEnd = Coordinates(lineNo, GetLineMaxColumn(lineNo)); + break; + } + default: + break; + } + + if (mState.mSelectionStart != oldSelStart || + mState.mSelectionEnd != oldSelEnd) + mCursorPositionChanged = true; +} + +void mvTextEditor::SetTabSize(int aValue) +{ + mTabSize = std::max(0, std::min(32, aValue)); +} + +void mvTextEditor::InsertText(const std::string& aValue) +{ + InsertText(aValue.c_str()); +} + +void mvTextEditor::InsertText(const char* aValue) +{ + if (aValue == nullptr) + return; + + auto pos = GetActualCursorCoordinates(); + auto start = std::min(pos, mState.mSelectionStart); + int totalLines = pos.mLine - start.mLine; + + totalLines += InsertTextAt(pos, aValue); + + SetSelection(pos, pos); + SetCursorPosition(pos); + Colorize(start.mLine - 1, totalLines + 2); +} + +void mvTextEditor::DeleteSelection() +{ + assert(mState.mSelectionEnd >= mState.mSelectionStart); + + if (mState.mSelectionEnd == mState.mSelectionStart) + return; + + DeleteRange(mState.mSelectionStart, mState.mSelectionEnd); + + SetSelection(mState.mSelectionStart, mState.mSelectionStart); + SetCursorPosition(mState.mSelectionStart); + Colorize(mState.mSelectionStart.mLine, 1); +} + +void mvTextEditor::MoveUp(int aAmount, bool aSelect) +{ + auto oldPos = mState.mCursorPosition; + mState.mCursorPosition.mLine = std::max(0, mState.mCursorPosition.mLine - aAmount); + if (oldPos != mState.mCursorPosition) + { + if (aSelect) + { + if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else if (oldPos == mInteractiveEnd) + mInteractiveEnd = mState.mCursorPosition; + else + { + mInteractiveStart = mState.mCursorPosition; + mInteractiveEnd = oldPos; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd); + + EnsureCursorVisible(); + } +} + +void mvTextEditor::MoveDown(int aAmount, bool aSelect) +{ + assert(mState.mCursorPosition.mColumn >= 0); + auto oldPos = mState.mCursorPosition; + mState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + aAmount)); + + if (mState.mCursorPosition != oldPos) + { + if (aSelect) + { + if (oldPos == mInteractiveEnd) + mInteractiveEnd = mState.mCursorPosition; + else if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else + { + mInteractiveStart = oldPos; + mInteractiveEnd = mState.mCursorPosition; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd); + + EnsureCursorVisible(); + } +} + +static bool IsUTFSequence(char c) +{ + return (c & 0xC0) == 0x80; +} + +void mvTextEditor::MoveLeft(int aAmount, bool aSelect, bool aWordMode) +{ + if (mLines.empty()) + return; + + auto oldPos = mState.mCursorPosition; + mState.mCursorPosition = GetActualCursorCoordinates(); + auto line = mState.mCursorPosition.mLine; + auto cindex = GetCharacterIndex(mState.mCursorPosition); + + while (aAmount-- > 0) + { + if (cindex == 0) + { + if (line > 0) + { + --line; + if ((int)mLines.size() > line) + cindex = (int)mLines[line].size(); + } + } + else + { + --cindex; + if (cindex > 0) + { + if ((int)mLines.size() > line) + { + while (cindex > 0 && IsUTFSequence(mLines[line][cindex].mChar)) + --cindex; + } + } + } + + mState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex)); + if (aWordMode) + { + mState.mCursorPosition = FindWordStart(mState.mCursorPosition); + cindex = GetCharacterIndex(mState.mCursorPosition); + } + } + + mState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex)); + + assert(mState.mCursorPosition.mColumn >= 0); + if (aSelect) + { + if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else if (oldPos == mInteractiveEnd) + mInteractiveEnd = mState.mCursorPosition; + else + { + mInteractiveStart = mState.mCursorPosition; + mInteractiveEnd = oldPos; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal); + + EnsureCursorVisible(); +} + +void mvTextEditor::MoveRight(int aAmount, bool aSelect, bool aWordMode) +{ + auto oldPos = mState.mCursorPosition; + + if (mLines.empty() || static_cast(oldPos.mLine) >= mLines.size()) + return; + + auto cindex = GetCharacterIndex(mState.mCursorPosition); + while (aAmount-- > 0) + { + auto lindex = mState.mCursorPosition.mLine; + auto& line = mLines[lindex]; + + if (static_cast(cindex) >= line.size()) + { + if (static_cast(mState.mCursorPosition.mLine) < mLines.size() - 1) + { + mState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + 1)); + mState.mCursorPosition.mColumn = 0; + } + else + return; + } + else + { + cindex += UTF8CharLength(line[cindex].mChar); + mState.mCursorPosition = Coordinates(lindex, GetCharacterColumn(lindex, cindex)); + if (aWordMode) + mState.mCursorPosition = FindNextWord(mState.mCursorPosition); + } + } + + if (aSelect) + { + if (oldPos == mInteractiveEnd) + mInteractiveEnd = SanitizeCoordinates(mState.mCursorPosition); + else if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else + { + mInteractiveStart = oldPos; + mInteractiveEnd = mState.mCursorPosition; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal); + + EnsureCursorVisible(); +} + +void mvTextEditor::MoveTop(bool aSelect) +{ + auto oldPos = mState.mCursorPosition; + SetCursorPosition(Coordinates(0, 0)); + + if (mState.mCursorPosition != oldPos) + { + if (aSelect) + { + mInteractiveEnd = oldPos; + mInteractiveStart = mState.mCursorPosition; + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd); + } +} + +void mvTextEditor::mvTextEditor::MoveBottom(bool aSelect) +{ + auto oldPos = GetCursorPosition(); + auto newPos = Coordinates((int)mLines.size() - 1, 0); + SetCursorPosition(newPos); + if (aSelect) + { + mInteractiveStart = oldPos; + mInteractiveEnd = newPos; + } + else + mInteractiveStart = mInteractiveEnd = newPos; + SetSelection(mInteractiveStart, mInteractiveEnd); +} + +void mvTextEditor::MoveHome(bool aSelect) +{ + auto oldPos = mState.mCursorPosition; + SetCursorPosition(Coordinates(mState.mCursorPosition.mLine, 0)); + + if (mState.mCursorPosition != oldPos) + { + if (aSelect) + { + if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else if (oldPos == mInteractiveEnd) + mInteractiveEnd = mState.mCursorPosition; + else + { + mInteractiveStart = mState.mCursorPosition; + mInteractiveEnd = oldPos; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd); + } +} + +void mvTextEditor::MoveEnd(bool aSelect) +{ + auto oldPos = mState.mCursorPosition; + SetCursorPosition(Coordinates(mState.mCursorPosition.mLine, GetLineMaxColumn(oldPos.mLine))); + + if (mState.mCursorPosition != oldPos) + { + if (aSelect) + { + if (oldPos == mInteractiveEnd) + mInteractiveEnd = mState.mCursorPosition; + else if (oldPos == mInteractiveStart) + mInteractiveStart = mState.mCursorPosition; + else + { + mInteractiveStart = oldPos; + mInteractiveEnd = mState.mCursorPosition; + } + } + else + mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; + SetSelection(mInteractiveStart, mInteractiveEnd); + } +} + +void mvTextEditor::Delete() +{ + assert(!mReadOnly); + + if (mLines.empty()) + return; + + UndoRecord u; + u.mBefore = mState; + + if (HasSelection()) + { + u.mRemoved = GetSelectedText(); + u.mRemovedStart = mState.mSelectionStart; + u.mRemovedEnd = mState.mSelectionEnd; + + DeleteSelection(); + } + else + { + auto pos = GetActualCursorCoordinates(); + SetCursorPosition(pos); + auto& line = mLines[pos.mLine]; + + if (pos.mColumn == GetLineMaxColumn(pos.mLine)) + { + if (pos.mLine == (int)mLines.size() - 1) + return; + + u.mRemoved = '\n'; + u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); + Advance(u.mRemovedEnd); + + auto& nextLine = mLines[pos.mLine + 1]; + line.insert(line.end(), nextLine.begin(), nextLine.end()); + RemoveLine(pos.mLine + 1); + } + else + { + auto cindex = GetCharacterIndex(pos); + u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); + u.mRemovedEnd.mColumn++; + u.mRemoved = GetText(u.mRemovedStart, u.mRemovedEnd); + + auto d = UTF8CharLength(line[cindex].mChar); + while (d-- > 0 && cindex < (int)line.size()) + line.erase(line.begin() + cindex); + } + + mTextChanged = true; + + Colorize(pos.mLine, 1); + } + + u.mAfter = mState; + AddUndo(u); +} + +void mvTextEditor::Backspace() +{ + assert(!mReadOnly); + + if (mLines.empty()) + return; + + UndoRecord u; + u.mBefore = mState; + + if (HasSelection()) + { + u.mRemoved = GetSelectedText(); + u.mRemovedStart = mState.mSelectionStart; + u.mRemovedEnd = mState.mSelectionEnd; + + DeleteSelection(); + } + else + { + auto pos = GetActualCursorCoordinates(); + SetCursorPosition(pos); + + if (mState.mCursorPosition.mColumn == 0) + { + if (mState.mCursorPosition.mLine == 0) + return; + + u.mRemoved = '\n'; + u.mRemovedStart = u.mRemovedEnd = Coordinates(pos.mLine - 1, GetLineMaxColumn(pos.mLine - 1)); + Advance(u.mRemovedEnd); + + auto& line = mLines[mState.mCursorPosition.mLine]; + auto& prevLine = mLines[mState.mCursorPosition.mLine - 1]; + auto prevSize = GetLineMaxColumn(mState.mCursorPosition.mLine - 1); + prevLine.insert(prevLine.end(), line.begin(), line.end()); + + ErrorMarkers etmp; + for (auto& i : mErrorMarkers) + etmp.insert(ErrorMarkers::value_type(i.first - 1 == mState.mCursorPosition.mLine ? i.first - 1 : i.first, i.second)); + mErrorMarkers = std::move(etmp); + + RemoveLine(mState.mCursorPosition.mLine); + --mState.mCursorPosition.mLine; + mState.mCursorPosition.mColumn = prevSize; + } + else + { + auto& line = mLines[mState.mCursorPosition.mLine]; + size_t cindex = GetCharacterIndex(pos) - 1; + auto cend = cindex + 1; + while (cindex > 0 && IsUTFSequence(line[cindex].mChar)) + --cindex; + + //if (cindex > 0 && UTF8CharLength(line[cindex].mChar) > 1) + // --cindex; + + u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); + --u.mRemovedStart.mColumn; + --mState.mCursorPosition.mColumn; + + while (cindex < line.size() && cend-- > cindex) + { + u.mRemoved += line[cindex].mChar; + line.erase(line.begin() + cindex); + } + } + + mTextChanged = true; + + EnsureCursorVisible(); + Colorize(mState.mCursorPosition.mLine, 1); + } + + u.mAfter = mState; + AddUndo(u); +} + +void mvTextEditor::SelectWordUnderCursor() +{ + auto c = GetCursorPosition(); + SetSelection(FindWordStart(c), FindWordEnd(c)); +} + +void mvTextEditor::SelectAll() +{ + SetSelection(Coordinates(0, 0), Coordinates((int)mLines.size(), 0)); +} + +bool mvTextEditor::HasSelection() const +{ + return mState.mSelectionEnd > mState.mSelectionStart; +} + +void mvTextEditor::Copy() +{ + if (HasSelection()) + { + ImGui::SetClipboardText(GetSelectedText().c_str()); + } + else + { + if (!mLines.empty()) + { + std::string str; + auto& line = mLines[GetActualCursorCoordinates().mLine]; + for (auto& g : line) + str.push_back(g.mChar); + ImGui::SetClipboardText(str.c_str()); + } + } +} + +void mvTextEditor::Cut() +{ + if (IsReadOnly()) + { + Copy(); + } + else + { + if (HasSelection()) + { + UndoRecord u; + u.mBefore = mState; + u.mRemoved = GetSelectedText(); + u.mRemovedStart = mState.mSelectionStart; + u.mRemovedEnd = mState.mSelectionEnd; + + Copy(); + DeleteSelection(); + + u.mAfter = mState; + AddUndo(u); + } + } +} + +void mvTextEditor::Paste() +{ + if (IsReadOnly()) + return; + + auto clipText = ImGui::GetClipboardText(); + if (clipText != nullptr && strlen(clipText) > 0) + { + UndoRecord u; + u.mBefore = mState; + + if (HasSelection()) + { + u.mRemoved = GetSelectedText(); + u.mRemovedStart = mState.mSelectionStart; + u.mRemovedEnd = mState.mSelectionEnd; + DeleteSelection(); + } + + u.mAdded = clipText; + u.mAddedStart = GetActualCursorCoordinates(); + + InsertText(clipText); + + u.mAddedEnd = GetActualCursorCoordinates(); + u.mAfter = mState; + AddUndo(u); + } +} + +bool mvTextEditor::CanUndo() const +{ + return !mReadOnly && mUndoIndex > 0; +} + +bool mvTextEditor::CanRedo() const +{ + return !mReadOnly && mUndoIndex < (int)mUndoBuffer.size(); +} + +void mvTextEditor::Undo(int aSteps) +{ + while (CanUndo() && aSteps-- > 0) + mUndoBuffer[--mUndoIndex].Undo(this); +} + +void mvTextEditor::Redo(int aSteps) +{ + while (CanRedo() && aSteps-- > 0) + mUndoBuffer[mUndoIndex++].Redo(this); +} + +const mvTextEditor::Palette& mvTextEditor::GetDarkPalette() +{ + const static Palette p = { { + 0xff7f7f7f, // Default + 0xffd69c56, // Keyword + 0xff00ff00, // Number + 0xff7070e0, // String + 0xff70a0e0, // Char literal + 0xffffffff, // Punctuation + 0xff408080, // Preprocessor + 0xffaaaaaa, // Identifier + 0xff9bc64d, // Known identifier + 0xffc040a0, // Preproc identifier + 0xff206020, // Comment (single line) + 0xff406020, // Comment (multi line) + 0xff101010, // Background + 0xffe0e0e0, // Cursor + 0x80a06020, // Selection + 0x800020ff, // ErrorMarker + 0x40f08000, // Breakpoint + 0xff2b91af, // Line number + 0x40000000, // Current line fill + 0x40808080, // Current line fill (inactive) + 0x40a0a0a0, // Current line edge + } }; + return p; +} + +const mvTextEditor::Palette& mvTextEditor::GetLightPalette() +{ + const static Palette p = { { + 0xff7f7f7f, // None + 0xffff0c06, // Keyword + 0xff008000, // Number + 0xff2020a0, // String + 0xff304070, // Char literal + 0xff000000, // Punctuation + 0xff406060, // Preprocessor + 0xff404040, // Identifier + 0xff606010, // Known identifier + 0xffc040a0, // Preproc identifier + 0xff205020, // Comment (single line) + 0xff405020, // Comment (multi line) + 0xffffffff, // Background + 0xff000000, // Cursor + 0x80600000, // Selection + 0xa00010ff, // ErrorMarker + 0x80f08000, // Breakpoint + 0xff505000, // Line number + 0x40000000, // Current line fill + 0x40808080, // Current line fill (inactive) + 0x40000000, // Current line edge + } }; + return p; +} + +const mvTextEditor::Palette& mvTextEditor::GetRetroBluePalette() +{ + const static Palette p = { { + 0xff00ffff, // None + 0xffffff00, // Keyword + 0xff00ff00, // Number + 0xff808000, // String + 0xff808000, // Char literal + 0xffffffff, // Punctuation + 0xff008000, // Preprocessor + 0xff00ffff, // Identifier + 0xffffffff, // Known identifier + 0xffff00ff, // Preproc identifier + 0xff808080, // Comment (single line) + 0xff404040, // Comment (multi line) + 0xff800000, // Background + 0xff0080ff, // Cursor + 0x80ffff00, // Selection + 0xa00000ff, // ErrorMarker + 0x80ff8000, // Breakpoint + 0xff808000, // Line number + 0x40000000, // Current line fill + 0x40808080, // Current line fill (inactive) + 0x40000000, // Current line edge + } }; + return p; +} + +std::string mvTextEditor::GetText() const +{ + return GetText(Coordinates(), Coordinates((int)mLines.size(), 0)); +} + +std::vector mvTextEditor::GetTextLines() const +{ + std::vector result; + + result.reserve(mLines.size()); + + for (auto& line : mLines) + { + std::string text; + + text.resize(line.size()); + + for (size_t i = 0; i < line.size(); ++i) + text[i] = line[i].mChar; + + result.emplace_back(std::move(text)); + } + + return result; +} + +std::string mvTextEditor::GetSelectedText() const +{ + return GetText(mState.mSelectionStart, mState.mSelectionEnd); +} + +std::string mvTextEditor::GetCurrentLineText()const +{ + auto lineLength = GetLineMaxColumn(mState.mCursorPosition.mLine); + return GetText( + Coordinates(mState.mCursorPosition.mLine, 0), + Coordinates(mState.mCursorPosition.mLine, lineLength)); +} + +void mvTextEditor::ProcessInputs() +{ +} + +void mvTextEditor::Colorize(int aFromLine, int aLines) +{ + int toLine = aLines == -1 ? (int)mLines.size() : std::min((int)mLines.size(), aFromLine + aLines); + mColorRangeMin = std::min(mColorRangeMin, aFromLine); + mColorRangeMax = std::max(mColorRangeMax, toLine); + mColorRangeMin = std::max(0, mColorRangeMin); + mColorRangeMax = std::max(mColorRangeMin, mColorRangeMax); + mCheckComments = true; +} + +void mvTextEditor::ColorizeRange(int aFromLine, int aToLine) +{ + if (mLines.empty() || aFromLine >= aToLine) + return; + + std::string buffer; + std::cmatch results; + std::string id; + + int endLine = std::max(0, std::min((int)mLines.size(), aToLine)); + for (int i = aFromLine; i < endLine; ++i) + { + auto& line = mLines[i]; + + if (line.empty()) + continue; + + buffer.resize(line.size()); + for (size_t j = 0; j < line.size(); ++j) + { + auto& col = line[j]; + buffer[j] = col.mChar; + col.mColorIndex = PaletteIndex::Default; + } + + const char* bufferBegin = &buffer.front(); + const char* bufferEnd = bufferBegin + buffer.size(); + + auto last = bufferEnd; + + for (auto first = bufferBegin; first != last; ) + { + const char* token_begin = nullptr; + const char* token_end = nullptr; + PaletteIndex token_color = PaletteIndex::Default; + + bool hasTokenizeResult = false; + + if (mLanguageDefinition.mTokenize != nullptr) + { + if (mLanguageDefinition.mTokenize(first, last, token_begin, token_end, token_color)) + hasTokenizeResult = true; + } + + if (hasTokenizeResult == false) + { + // todo : remove + //printf("using regex for %.*s\n", first + 10 < last ? 10 : int(last - first), first); + + for (auto& p : mRegexList) + { + if (std::regex_search(first, last, results, p.first, std::regex_constants::match_continuous)) + { + hasTokenizeResult = true; + + auto& v = *results.begin(); + token_begin = v.first; + token_end = v.second; + token_color = p.second; + break; + } + } + } + + if (hasTokenizeResult == false) + { + first++; + } + else + { + const size_t token_length = token_end - token_begin; + + if (token_color == PaletteIndex::Identifier) + { + id.assign(token_begin, token_end); + + // todo : allmost all language definitions use lower case to specify keywords, so shouldn't this use ::tolower ? + if (!mLanguageDefinition.mCaseSensitive) + std::transform(id.begin(), id.end(), id.begin(), ::toupper); + + if (!line[first - bufferBegin].mPreprocessor) + { + if (mLanguageDefinition.mKeywords.count(id) != 0) + token_color = PaletteIndex::Keyword; + else if (mLanguageDefinition.mIdentifiers.count(id) != 0) + token_color = PaletteIndex::KnownIdentifier; + else if (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0) + token_color = PaletteIndex::PreprocIdentifier; + } + else + { + if (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0) + token_color = PaletteIndex::PreprocIdentifier; + } + } + + for (size_t j = 0; j < token_length; ++j) + line[(token_begin - bufferBegin) + j].mColorIndex = token_color; + + first = token_end; + } + } + } +} + +void mvTextEditor::ColorizeInternal() +{ + if (mLines.empty() || !mColorizerEnabled) + return; + + if (mCheckComments) + { + auto endLine = mLines.size(); + auto endIndex = 0; + auto commentStartLine = endLine; + auto commentStartIndex = endIndex; + auto withinString = false; + auto withinSingleLineComment = false; + auto withinPreproc = false; + auto firstChar = true; // there is no other non-whitespace characters in the line before + auto concatenate = false; // '\' on the very end of the line + size_t currentLine = 0; + auto currentIndex = 0; + while (currentLine < endLine || currentIndex < endIndex) + { + auto& line = mLines[currentLine]; + + if (currentIndex == 0 && !concatenate) + { + withinSingleLineComment = false; + withinPreproc = false; + firstChar = true; + } + + concatenate = false; + + if (!line.empty()) + { + auto& g = line[currentIndex]; + auto c = g.mChar; + + if (c != mLanguageDefinition.mPreprocChar && !isspace(c)) + firstChar = false; + + if (currentIndex == (int)line.size() - 1 && line[line.size() - 1].mChar == '\\') + concatenate = true; + + bool inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex)); + + if (withinString) + { + line[currentIndex].mMultiLineComment = inComment; + + if (c == '\"') + { + if (currentIndex + 1 < (int)line.size() && line[currentIndex + 1].mChar == '\"') + { + currentIndex += 1; + if (currentIndex < (int)line.size()) + line[currentIndex].mMultiLineComment = inComment; + } + else + withinString = false; + } + else if (c == '\\') + { + currentIndex += 1; + if (currentIndex < (int)line.size()) + line[currentIndex].mMultiLineComment = inComment; + } + } + else + { + if (firstChar && c == mLanguageDefinition.mPreprocChar) + withinPreproc = true; + + if (c == '\"') + { + withinString = true; + line[currentIndex].mMultiLineComment = inComment; + } + else + { + auto pred = [](const char& a, const Glyph& b) { return a == b.mChar; }; + auto from = line.begin() + currentIndex; + auto& startStr = mLanguageDefinition.mCommentStart; + auto& singleStartStr = mLanguageDefinition.mSingleLineComment; + + if (singleStartStr.size() > 0 && + currentIndex + singleStartStr.size() <= line.size() && + equals(singleStartStr.begin(), singleStartStr.end(), from, from + singleStartStr.size(), pred)) + { + withinSingleLineComment = true; + } + else if (!withinSingleLineComment && currentIndex + startStr.size() <= line.size() && + equals(startStr.begin(), startStr.end(), from, from + startStr.size(), pred)) + { + commentStartLine = currentLine; + commentStartIndex = currentIndex; + } + + inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex)); + + line[currentIndex].mMultiLineComment = inComment; + line[currentIndex].mComment = withinSingleLineComment; + + auto& endStr = mLanguageDefinition.mCommentEnd; + if (currentIndex + 1 >= (int)endStr.size() && + equals(endStr.begin(), endStr.end(), from + 1 - endStr.size(), from + 1, pred)) + { + commentStartIndex = endIndex; + commentStartLine = endLine; + } + } + } + line[currentIndex].mPreprocessor = withinPreproc; + currentIndex += UTF8CharLength(c); + if (currentIndex >= (int)line.size()) + { + currentIndex = 0; + ++currentLine; + } + } + else + { + currentIndex = 0; + ++currentLine; + } + } + mCheckComments = false; + } + + if (mColorRangeMin < mColorRangeMax) + { + const int increment = (mLanguageDefinition.mTokenize == nullptr) ? 10 : 10000; + const int to = std::min(mColorRangeMin + increment, mColorRangeMax); + ColorizeRange(mColorRangeMin, to); + mColorRangeMin = to; + + if (mColorRangeMax == mColorRangeMin) + { + mColorRangeMin = std::numeric_limits::max(); + mColorRangeMax = 0; + } + return; + } +} + +float mvTextEditor::TextDistanceToLineStart(const Coordinates& aFrom) const +{ + auto& line = mLines[aFrom.mLine]; + float distance = 0.0f; + float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ", nullptr, nullptr).x; + size_t colIndex = GetCharacterIndex(aFrom); + for (size_t it = 0u; it < line.size() && it < colIndex; ) + { + if (line[it].mChar == '\t') + { + distance = (1.0f + std::floor((1.0f + distance) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); + ++it; + } + else + { + auto d = UTF8CharLength(line[it].mChar); + char tempCString[7]; + int i = 0; + for (; i < 6 && d-- > 0 && it < line.size(); i++, it++) + tempCString[i] = line[it].mChar; + + tempCString[i] = '\0'; + distance += ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, tempCString, nullptr, nullptr).x; + } + } + + return distance; +} + +void mvTextEditor::EnsureCursorVisible() +{ + if (!mWithinRender) + { + mScrollToCursor = true; + return; + } + + float scrollX = ImGui::GetScrollX(); + float scrollY = ImGui::GetScrollY(); + + auto height = ImGui::GetWindowHeight(); + auto width = ImGui::GetWindowWidth(); + + auto top = 1 + (int)ceil(scrollY / mCharAdvance.y); + auto bottom = (int)ceil((scrollY + height) / mCharAdvance.y); + + auto left = (int)ceil(scrollX / mCharAdvance.x); + auto right = (int)ceil((scrollX + width) / mCharAdvance.x); + + auto pos = GetActualCursorCoordinates(); + auto len = TextDistanceToLineStart(pos); + + if (pos.mLine < top) + ImGui::SetScrollY(std::max(0.0f, (pos.mLine - 1) * mCharAdvance.y)); + if (pos.mLine > bottom - 4) + ImGui::SetScrollY(std::max(0.0f, (pos.mLine + 4) * mCharAdvance.y - height)); + if (len + mTextStart < left + 4) + ImGui::SetScrollX(std::max(0.0f, len + mTextStart - 4)); + if (len + mTextStart > right - 4) + ImGui::SetScrollX(std::max(0.0f, len + mTextStart + 4 - width)); +} + +int mvTextEditor::GetPageSize() const +{ + auto height = ImGui::GetWindowHeight() - 20.0f; + return (int)floor(height / mCharAdvance.y); +} + +mvTextEditor::UndoRecord::UndoRecord( + const std::string& aAdded, + const mvTextEditor::Coordinates aAddedStart, + const mvTextEditor::Coordinates aAddedEnd, + const std::string& aRemoved, + const mvTextEditor::Coordinates aRemovedStart, + const mvTextEditor::Coordinates aRemovedEnd, + mvTextEditor::EditorState& aBefore, + mvTextEditor::EditorState& aAfter) + : mAdded(aAdded) + , mAddedStart(aAddedStart) + , mAddedEnd(aAddedEnd) + , mRemoved(aRemoved) + , mRemovedStart(aRemovedStart) + , mRemovedEnd(aRemovedEnd) + , mBefore(aBefore) + , mAfter(aAfter) +{ + assert(mAddedStart <= mAddedEnd); + assert(mRemovedStart <= mRemovedEnd); +} + +void mvTextEditor::UndoRecord::Undo(mvTextEditor* aEditor) +{ + if (!mAdded.empty()) + { + aEditor->DeleteRange(mAddedStart, mAddedEnd); + aEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 2); + } + + if (!mRemoved.empty()) + { + auto start = mRemovedStart; + aEditor->InsertTextAt(start, mRemoved.c_str()); + aEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 2); + } + + aEditor->mState = mBefore; + aEditor->EnsureCursorVisible(); + +} + +void mvTextEditor::UndoRecord::Redo(mvTextEditor* aEditor) +{ + if (!mRemoved.empty()) + { + aEditor->DeleteRange(mRemovedStart, mRemovedEnd); + aEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 1); + } + + if (!mAdded.empty()) + { + auto start = mAddedStart; + aEditor->InsertTextAt(start, mAdded.c_str()); + aEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 1); + } + + aEditor->mState = mAfter; + aEditor->EnsureCursorVisible(); +} + +static bool TokenizeCStyleString(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end) +{ + const char* p = in_begin; + + if (*p == '"') + { + p++; + + while (p < in_end) + { + // handle end of string + if (*p == '"') + { + out_begin = in_begin; + out_end = p + 1; + return true; + } + + // handle escape character for " + if (*p == '\\' && p + 1 < in_end && p[1] == '"') + p++; + + p++; + } + } + + return false; +} + +static bool TokenizeCStyleCharacterLiteral(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end) +{ + const char* p = in_begin; + + if (*p == '\'') + { + p++; + + // handle escape characters + if (p < in_end && *p == '\\') + p++; + + if (p < in_end) + p++; + + // handle end of character literal + if (p < in_end && *p == '\'') + { + out_begin = in_begin; + out_end = p + 1; + return true; + } + } + + return false; +} + +static bool TokenizeCStyleIdentifier(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end) +{ + const char* p = in_begin; + + if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_') + { + p++; + + while ((p < in_end) && ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_')) + p++; + + out_begin = in_begin; + out_end = p; + return true; + } + + return false; +} + +static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end) +{ + const char* p = in_begin; + + const bool startsWithNumber = *p >= '0' && *p <= '9'; + + if (*p != '+' && *p != '-' && !startsWithNumber) + return false; + + p++; + + bool hasNumber = startsWithNumber; + + while (p < in_end && (*p >= '0' && *p <= '9')) + { + hasNumber = true; + + p++; + } + + if (hasNumber == false) + return false; + + bool isFloat = false; + bool isHex = false; + bool isBinary = false; + + if (p < in_end) + { + if (*p == '.') + { + isFloat = true; + + p++; + + while (p < in_end && (*p >= '0' && *p <= '9')) + p++; + } + else if (*p == 'x' || *p == 'X') + { + // hex formatted integer of the type 0xef80 + + isHex = true; + + p++; + + while (p < in_end && ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F'))) + p++; + } + else if (*p == 'b' || *p == 'B') + { + // binary formatted integer of the type 0b01011101 + + isBinary = true; + + p++; + + while (p < in_end && (*p >= '0' && *p <= '1')) + p++; + } + } + + if (isHex == false && isBinary == false) + { + // floating point exponent + if (p < in_end && (*p == 'e' || *p == 'E')) + { + isFloat = true; + + p++; + + if (p < in_end && (*p == '+' || *p == '-')) + p++; + + bool hasDigits = false; + + while (p < in_end && (*p >= '0' && *p <= '9')) + { + hasDigits = true; + + p++; + } + + if (hasDigits == false) + return false; + } + + // single precision floating point type + if (p < in_end && *p == 'f') + p++; + } + + if (isFloat == false) + { + // integer size type + while (p < in_end && (*p == 'u' || *p == 'U' || *p == 'l' || *p == 'L')) + p++; + } + + out_begin = in_begin; + out_end = p; + return true; +} + +static bool TokenizeCStylePunctuation(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end) +{ + (void)in_end; + + switch (*in_begin) + { + case '[': + case ']': + case '{': + case '}': + case '!': + case '%': + case '^': + case '&': + case '*': + case '(': + case ')': + case '-': + case '+': + case '=': + case '~': + case '|': + case '<': + case '>': + case '?': + case ':': + case '/': + case ';': + case ',': + case '.': + out_begin = in_begin; + out_end = in_begin + 1; + return true; + } + + return false; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::CPlusPlus() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const cppKeywords[] = { + "alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", + "compl", "concept", "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", + "for", "friend", "goto", "if", "import", "inline", "int", "long", "module", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", + "register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "synchronized", "template", "this", "thread_local", + "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq" + }; + for (auto& k : cppKeywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", + "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "printf", "sprintf", "snprintf", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper", + "std", "string", "vector", "map", "unordered_map", "set", "unordered_set", "min", "max" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenize = [](const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PaletteIndex& paletteIndex) -> bool + { + paletteIndex = PaletteIndex::Max; + + while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) + in_begin++; + + if (in_begin == in_end) + { + out_begin = in_end; + out_end = in_end; + paletteIndex = PaletteIndex::Default; + } + else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::String; + else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::CharLiteral; + else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Identifier; + else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Number; + else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Punctuation; + + return paletteIndex != PaletteIndex::Max; + }; + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "C++"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::HLSL() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "AppendStructuredBuffer", "asm", "asm_fragment", "BlendState", "bool", "break", "Buffer", "ByteAddressBuffer", "case", "cbuffer", "centroid", "class", "column_major", "compile", "compile_fragment", + "CompileShader", "const", "continue", "ComputeShader", "ConsumeStructuredBuffer", "default", "DepthStencilState", "DepthStencilView", "discard", "do", "double", "DomainShader", "dword", "else", + "export", "extern", "false", "float", "for", "fxgroup", "GeometryShader", "groupshared", "half", "Hullshader", "if", "in", "inline", "inout", "InputPatch", "int", "interface", "line", "lineadj", + "linear", "LineStream", "matrix", "min16float", "min10float", "min16int", "min12int", "min16uint", "namespace", "nointerpolation", "noperspective", "NULL", "out", "OutputPatch", "packoffset", + "pass", "pixelfragment", "PixelShader", "point", "PointStream", "precise", "RasterizerState", "RenderTargetView", "return", "register", "row_major", "RWBuffer", "RWByteAddressBuffer", "RWStructuredBuffer", + "RWTexture1D", "RWTexture1DArray", "RWTexture2D", "RWTexture2DArray", "RWTexture3D", "sample", "sampler", "SamplerState", "SamplerComparisonState", "shared", "snorm", "stateblock", "stateblock_state", + "static", "string", "struct", "switch", "StructuredBuffer", "tbuffer", "technique", "technique10", "technique11", "texture", "Texture1D", "Texture1DArray", "Texture2D", "Texture2DArray", "Texture2DMS", + "Texture2DMSArray", "Texture3D", "TextureCube", "TextureCubeArray", "true", "typedef", "triangle", "triangleadj", "TriangleStream", "uint", "uniform", "unorm", "unsigned", "vector", "vertexfragment", + "VertexShader", "void", "volatile", "while", + "bool1","bool2","bool3","bool4","double1","double2","double3","double4", "float1", "float2", "float3", "float4", "int1", "int2", "int3", "int4", "in", "out", "inout", + "uint1", "uint2", "uint3", "uint4", "dword1", "dword2", "dword3", "dword4", "half1", "half2", "half3", "half4", + "float1x1","float2x1","float3x1","float4x1","float1x2","float2x2","float3x2","float4x2", + "float1x3","float2x3","float3x3","float4x3","float1x4","float2x4","float3x4","float4x4", + "half1x1","half2x1","half3x1","half4x1","half1x2","half2x2","half3x2","half4x2", + "half1x3","half2x3","half3x3","half4x3","half1x4","half2x4","half3x4","half4x4", + }; + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "abort", "abs", "acos", "all", "AllMemoryBarrier", "AllMemoryBarrierWithGroupSync", "any", "asdouble", "asfloat", "asin", "asint", "asint", "asuint", + "asuint", "atan", "atan2", "ceil", "CheckAccessFullyMapped", "clamp", "clip", "cos", "cosh", "countbits", "cross", "D3DCOLORtoUBYTE4", "ddx", + "ddx_coarse", "ddx_fine", "ddy", "ddy_coarse", "ddy_fine", "degrees", "determinant", "DeviceMemoryBarrier", "DeviceMemoryBarrierWithGroupSync", + "distance", "dot", "dst", "errorf", "EvaluateAttributeAtCentroid", "EvaluateAttributeAtSample", "EvaluateAttributeSnapped", "exp", "exp2", + "f16tof32", "f32tof16", "faceforward", "firstbithigh", "firstbitlow", "floor", "fma", "fmod", "frac", "frexp", "fwidth", "GetRenderTargetSampleCount", + "GetRenderTargetSamplePosition", "GroupMemoryBarrier", "GroupMemoryBarrierWithGroupSync", "InterlockedAdd", "InterlockedAnd", "InterlockedCompareExchange", + "InterlockedCompareStore", "InterlockedExchange", "InterlockedMax", "InterlockedMin", "InterlockedOr", "InterlockedXor", "isfinite", "isinf", "isnan", + "ldexp", "length", "lerp", "lit", "log", "log10", "log2", "mad", "max", "min", "modf", "msad4", "mul", "noise", "normalize", "pow", "printf", + "Process2DQuadTessFactorsAvg", "Process2DQuadTessFactorsMax", "Process2DQuadTessFactorsMin", "ProcessIsolineTessFactors", "ProcessQuadTessFactorsAvg", + "ProcessQuadTessFactorsMax", "ProcessQuadTessFactorsMin", "ProcessTriTessFactorsAvg", "ProcessTriTessFactorsMax", "ProcessTriTessFactorsMin", + "radians", "rcp", "reflect", "refract", "reversebits", "round", "rsqrt", "saturate", "sign", "sin", "sincos", "sinh", "smoothstep", "sqrt", "step", + "tan", "tanh", "tex1D", "tex1D", "tex1Dbias", "tex1Dgrad", "tex1Dlod", "tex1Dproj", "tex2D", "tex2D", "tex2Dbias", "tex2Dgrad", "tex2Dlod", "tex2Dproj", + "tex3D", "tex3D", "tex3Dbias", "tex3Dgrad", "tex3Dlod", "tex3Dproj", "texCUBE", "texCUBE", "texCUBEbias", "texCUBEgrad", "texCUBElod", "texCUBEproj", "transpose", "trunc" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Preprocessor)); + langDef.mTokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "HLSL"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::GLSL() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", + "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", + "_Noreturn", "_Static_assert", "_Thread_local" + }; + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", + "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Preprocessor)); + langDef.mTokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "GLSL"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::C() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", + "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", + "_Noreturn", "_Static_assert", "_Thread_local" + }; + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", + "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenize = [](const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PaletteIndex& paletteIndex) -> bool + { + paletteIndex = PaletteIndex::Max; + + while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) + in_begin++; + + if (in_begin == in_end) + { + out_begin = in_end; + out_end = in_end; + paletteIndex = PaletteIndex::Default; + } + else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::String; + else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::CharLiteral; + else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Identifier; + else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Number; + else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Punctuation; + + return paletteIndex != PaletteIndex::Max; + }; + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "C"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::SQL() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "ADD", "EXCEPT", "PERCENT", "ALL", "EXEC", "PLAN", "ALTER", "EXECUTE", "PRECISION", "AND", "EXISTS", "PRIMARY", "ANY", "EXIT", "PRINT", "AS", "FETCH", "PROC", "ASC", "FILE", "PROCEDURE", + "AUTHORIZATION", "FILLFACTOR", "PUBLIC", "BACKUP", "FOR", "RAISERROR", "BEGIN", "FOREIGN", "READ", "BETWEEN", "FREETEXT", "READTEXT", "BREAK", "FREETEXTTABLE", "RECONFIGURE", + "BROWSE", "FROM", "REFERENCES", "BULK", "FULL", "REPLICATION", "BY", "FUNCTION", "RESTORE", "CASCADE", "GOTO", "RESTRICT", "CASE", "GRANT", "RETURN", "CHECK", "GROUP", "REVOKE", + "CHECKPOINT", "HAVING", "RIGHT", "CLOSE", "HOLDLOCK", "ROLLBACK", "CLUSTERED", "IDENTITY", "ROWCOUNT", "COALESCE", "IDENTITY_INSERT", "ROWGUIDCOL", "COLLATE", "IDENTITYCOL", "RULE", + "COLUMN", "IF", "SAVE", "COMMIT", "IN", "SCHEMA", "COMPUTE", "INDEX", "SELECT", "CONSTRAINT", "INNER", "SESSION_USER", "CONTAINS", "INSERT", "SET", "CONTAINSTABLE", "INTERSECT", "SETUSER", + "CONTINUE", "INTO", "SHUTDOWN", "CONVERT", "IS", "SOME", "CREATE", "JOIN", "STATISTICS", "CROSS", "KEY", "SYSTEM_USER", "CURRENT", "KILL", "TABLE", "CURRENT_DATE", "LEFT", "TEXTSIZE", + "CURRENT_TIME", "LIKE", "THEN", "CURRENT_TIMESTAMP", "LINENO", "TO", "CURRENT_USER", "LOAD", "TOP", "CURSOR", "NATIONAL", "TRAN", "DATABASE", "NOCHECK", "TRANSACTION", + "DBCC", "NONCLUSTERED", "TRIGGER", "DEALLOCATE", "NOT", "TRUNCATE", "DECLARE", "NULL", "TSEQUAL", "DEFAULT", "NULLIF", "UNION", "DELETE", "OF", "UNIQUE", "DENY", "OFF", "UPDATE", + "DESC", "OFFSETS", "UPDATETEXT", "DISK", "ON", "USE", "DISTINCT", "OPEN", "USER", "DISTRIBUTED", "OPENDATASOURCE", "VALUES", "DOUBLE", "OPENQUERY", "VARYING","DROP", "OPENROWSET", "VIEW", + "DUMMY", "OPENXML", "WAITFOR", "DUMP", "OPTION", "WHEN", "ELSE", "OR", "WHERE", "END", "ORDER", "WHILE", "ERRLVL", "OUTER", "WITH", "ESCAPE", "OVER", "WRITETEXT" + }; + + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "ABS", "ACOS", "ADD_MONTHS", "ASCII", "ASCIISTR", "ASIN", "ATAN", "ATAN2", "AVG", "BFILENAME", "BIN_TO_NUM", "BITAND", "CARDINALITY", "CASE", "CAST", "CEIL", + "CHARTOROWID", "CHR", "COALESCE", "COMPOSE", "CONCAT", "CONVERT", "CORR", "COS", "COSH", "COUNT", "COVAR_POP", "COVAR_SAMP", "CUME_DIST", "CURRENT_DATE", + "CURRENT_TIMESTAMP", "DBTIMEZONE", "DECODE", "DECOMPOSE", "DENSE_RANK", "DUMP", "EMPTY_BLOB", "EMPTY_CLOB", "EXP", "EXTRACT", "FIRST_VALUE", "FLOOR", "FROM_TZ", "GREATEST", + "GROUP_ID", "HEXTORAW", "INITCAP", "INSTR", "INSTR2", "INSTR4", "INSTRB", "INSTRC", "LAG", "LAST_DAY", "LAST_VALUE", "LEAD", "LEAST", "LENGTH", "LENGTH2", "LENGTH4", + "LENGTHB", "LENGTHC", "LISTAGG", "LN", "LNNVL", "LOCALTIMESTAMP", "LOG", "LOWER", "LPAD", "LTRIM", "MAX", "MEDIAN", "MIN", "MOD", "MONTHS_BETWEEN", "NANVL", "NCHR", + "NEW_TIME", "NEXT_DAY", "NTH_VALUE", "NULLIF", "NUMTODSINTERVAL", "NUMTOYMINTERVAL", "NVL", "NVL2", "POWER", "RANK", "RAWTOHEX", "REGEXP_COUNT", "REGEXP_INSTR", + "REGEXP_REPLACE", "REGEXP_SUBSTR", "REMAINDER", "REPLACE", "ROUND", "ROWNUM", "RPAD", "RTRIM", "SESSIONTIMEZONE", "SIGN", "SIN", "SINH", + "SOUNDEX", "SQRT", "STDDEV", "SUBSTR", "SUM", "SYS_CONTEXT", "SYSDATE", "SYSTIMESTAMP", "TAN", "TANH", "TO_CHAR", "TO_CLOB", "TO_DATE", "TO_DSINTERVAL", "TO_LOB", + "TO_MULTI_BYTE", "TO_NCLOB", "TO_NUMBER", "TO_SINGLE_BYTE", "TO_TIMESTAMP", "TO_TIMESTAMP_TZ", "TO_YMINTERVAL", "TRANSLATE", "TRIM", "TRUNC", "TZ_OFFSET", "UID", "UPPER", + "USER", "USERENV", "VAR_POP", "VAR_SAMP", "VARIANCE", "VSIZE " + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("\\\'[^\\\']*\\\'", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = false; + langDef.mAutoIndentation = false; + + langDef.mName = "SQL"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::AngelScript() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "and", "abstract", "auto", "bool", "break", "case", "cast", "class", "const", "continue", "default", "do", "double", "else", "enum", "false", "final", "float", "for", + "from", "funcdef", "function", "get", "if", "import", "in", "inout", "int", "interface", "int8", "int16", "int32", "int64", "is", "mixin", "namespace", "not", + "null", "or", "out", "override", "private", "protected", "return", "set", "shared", "super", "switch", "this ", "true", "typedef", "uint", "uint8", "uint16", "uint32", + "uint64", "void", "while", "xor" + }; + + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "cos", "sin", "tab", "acos", "asin", "atan", "atan2", "cosh", "sinh", "tanh", "log", "log10", "pow", "sqrt", "abs", "ceil", "floor", "fraction", "closeTo", "fpFromIEEE", "fpToIEEE", + "complex", "opEquals", "opAddAssign", "opSubAssign", "opMulAssign", "opDivAssign", "opAdd", "opSub", "opMul", "opDiv" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); + + langDef.mCommentStart = "/*"; + langDef.mCommentEnd = "*/"; + langDef.mSingleLineComment = "//"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "AngelScript"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::Lua() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const keywords[] = { + "and", "break", "do", "", "else", "elseif", "end", "false", "for", "function", "if", "in", "", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" + }; + + for (auto& k : keywords) + langDef.mKeywords.insert(k); + + static const char* const identifiers[] = { + "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "loadfile", "load", "loadstring", "next", "pairs", "pcall", "print", "rawequal", "rawlen", "rawget", "rawset", + "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", "_G", "_VERSION","arshift", "band", "bnot", "bor", "bxor", "btest", "extract", "lrotate", "lshift", "replace", + "rrotate", "rshift", "create", "resume", "running", "status", "wrap", "yield", "isyieldable", "debug","getuservalue", "gethook", "getinfo", "getlocal", "getregistry", "getmetatable", + "getupvalue", "upvaluejoin", "upvalueid", "setuservalue", "sethook", "setlocal", "setmetatable", "setupvalue", "traceback", "close", "flush", "input", "lines", "open", "output", "popen", + "read", "tmpfile", "type", "write", "close", "flush", "lines", "read", "seek", "setvbuf", "write", "__gc", "__tostring", "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "tointeger", + "floor", "fmod", "ult", "log", "max", "min", "modf", "rad", "random", "randomseed", "sin", "sqrt", "string", "tan", "type", "atan2", "cosh", "sinh", "tanh", + "pow", "frexp", "ldexp", "log10", "pi", "huge", "maxinteger", "mininteger", "loadlib", "searchpath", "seeall", "preload", "cpath", "path", "searchers", "loaded", "module", "require", "clock", + "date", "difftime", "execute", "exit", "getenv", "remove", "rename", "setlocale", "time", "tmpname", "byte", "char", "dump", "find", "format", "gmatch", "gsub", "len", "lower", "match", "rep", + "reverse", "sub", "upper", "pack", "packsize", "unpack", "concat", "maxn", "insert", "pack", "unpack", "remove", "move", "sort", "offset", "codepoint", "char", "len", "codes", "charpattern", + "coroutine", "table", "io", "os", "string", "utf8", "bit32", "math", "debug", "package" + }; + for (auto& k : identifiers) + { + Identifier id; + id.mDeclaration = "Built-in function"; + langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); + } + + langDef.mTokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("\\\'[^\\\']*\\\'", PaletteIndex::String)); + langDef.mTokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); + langDef.mTokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); + + langDef.mCommentStart = "--[["; + langDef.mCommentEnd = "]]"; + langDef.mSingleLineComment = "--"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = false; + + langDef.mName = "Lua"; + + inited = true; + } + return langDef; +} + +const mvTextEditor::LanguageDefinition& mvTextEditor::LanguageDefinition::Python() +{ + static bool inited = false; + static LanguageDefinition langDef; + if (!inited) + { + static const char* const cppKeywords[] = { + "False", "class", "finally", "is","return","None","continue","for", + "lambda","try","True","def","from","nonlocal","while","and","del", + "global","not","with","as","elif","if","or","yield","assert","else", + "import","pass","break","except","in","raise","self","print","__init__", + "append","int","float","complex","str","list","tuple","range","len", + "abs","sin","cos","tan","atan","asin","acos","bytes","bytearray", + "memoryview","set","frozenset","dict","Boolean" + }; + for (auto& k : cppKeywords) + langDef.mKeywords.insert(k); + + const auto& docmap = mvModule_Core::GetModuleParsers(); + + for (auto& k : docmap) + { + Identifier id; + id.mDeclaration = k.second.getDocumentation(); + langDef.mIdentifiers.insert(std::make_pair(k.first, id)); + } + + for (auto& k : mvModule_Core::GetModuleConstants()) + { + Identifier id; + id.mDeclaration = "Constant with value " + std::to_string(k.second); + langDef.mPreprocIdentifiers.insert(std::make_pair(k.first, id)); + } + + langDef.mTokenize = [](const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PaletteIndex& paletteIndex) -> bool + { + paletteIndex = PaletteIndex::Max; + + while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) + in_begin++; + + if (in_begin == in_end) + { + out_begin = in_end; + out_end = in_end; + paletteIndex = PaletteIndex::Default; + } + else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::String; + else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::CharLiteral; + else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Identifier; + else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Number; + else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) + paletteIndex = PaletteIndex::Punctuation; + + return paletteIndex != PaletteIndex::Max; + }; + + langDef.mCommentStart = "##"; + langDef.mCommentEnd = "##"; + langDef.mSingleLineComment = "#"; + + langDef.mCaseSensitive = true; + langDef.mAutoIndentation = true; + + langDef.mName = "Python"; + + inited = true; + } + return langDef; +} +} diff --git a/DearPyGui/src/core/AppItems/custom/mvTextEditor.h b/DearPyGui/src/core/AppItems/custom/mvTextEditor.h new file mode 100644 index 000000000..718222213 --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvTextEditor.h @@ -0,0 +1,410 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvTextEditor +// +// - This was forked and modified from the now abandoned +// ImGuiColorTextEditor. +// +// - Eventually this should be rewritten and improved to make it +// more extendable and customizable (i.e. key mappings) +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include "imgui.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvTextEditor + //----------------------------------------------------------------------------- + class mvTextEditor + { + public: + enum class PaletteIndex + { + Default, + Keyword, + Number, + String, + CharLiteral, + Punctuation, + Preprocessor, + Identifier, + KnownIdentifier, + PreprocIdentifier, + Comment, + MultiLineComment, + Background, + Cursor, + Selection, + ErrorMarker, + Breakpoint, + LineNumber, + CurrentLineFill, + CurrentLineFillInactive, + CurrentLineEdge, + Max + }; + + enum class SelectionMode + { + Normal, + Word, + Line + }; + + struct Breakpoint + { + int mLine; + bool mEnabled; + std::string mCondition; + + Breakpoint() + : mLine(-1) + , mEnabled(false) + {} + }; + + // Represents a character coordinate from the user's point of view, + // i. e. consider an uniform grid (assuming fixed-width font) on the + // screen as it is rendered, and each cell has its own coordinate, starting from 0. + // Tabs are counted as [1..mTabSize] count empty spaces, depending on + // how many space is necessary to reach the next tab stop. + // For example, coordinate (1, 5) represents the character 'B' in a line "\tABC", when mTabSize = 4, + // because it is rendered as " ABC" on the screen. + struct Coordinates + { + int mLine, mColumn; + Coordinates() : mLine(0), mColumn(0) {} + Coordinates(int aLine, int aColumn) : mLine(aLine), mColumn(aColumn) + { + assert(aLine >= 0); + assert(aColumn >= 0); + } + static Coordinates Invalid() { static Coordinates invalid(-1, -1); return invalid; } + + bool operator ==(const Coordinates& o) const + { + return + mLine == o.mLine && + mColumn == o.mColumn; + } + + bool operator !=(const Coordinates& o) const + { + return + mLine != o.mLine || + mColumn != o.mColumn; + } + + bool operator <(const Coordinates& o) const + { + if (mLine != o.mLine) + return mLine < o.mLine; + return mColumn < o.mColumn; + } + + bool operator >(const Coordinates& o) const + { + if (mLine != o.mLine) + return mLine > o.mLine; + return mColumn > o.mColumn; + } + + bool operator <=(const Coordinates& o) const + { + if (mLine != o.mLine) + return mLine < o.mLine; + return mColumn <= o.mColumn; + } + + bool operator >=(const Coordinates& o) const + { + if (mLine != o.mLine) + return mLine > o.mLine; + return mColumn >= o.mColumn; + } + }; + + struct Identifier + { + Coordinates mLocation; + std::string mDeclaration; + }; + + typedef std::string String; + typedef std::unordered_map Identifiers; + typedef std::unordered_set Keywords; + typedef std::map ErrorMarkers; + typedef std::unordered_set Breakpoints; + typedef std::array Palette; + typedef uint8_t Char; + + struct Glyph + { + Char mChar; + PaletteIndex mColorIndex = PaletteIndex::Default; + bool mComment : 1; + bool mMultiLineComment : 1; + bool mPreprocessor : 1; + + Glyph(Char aChar, PaletteIndex aColorIndex) : mChar(aChar), mColorIndex(aColorIndex), + mComment(false), mMultiLineComment(false), mPreprocessor(false) {} + }; + + typedef std::vector Line; + typedef std::vector Lines; + + struct LanguageDefinition + { + typedef std::pair TokenRegexString; + typedef std::vector TokenRegexStrings; + typedef bool(*TokenizeCallback)(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PaletteIndex& paletteIndex); + + std::string mName; + Keywords mKeywords; + Identifiers mIdentifiers; + Identifiers mPreprocIdentifiers; + std::string mCommentStart, mCommentEnd, mSingleLineComment; + char mPreprocChar; + bool mAutoIndentation; + + TokenizeCallback mTokenize; + + TokenRegexStrings mTokenRegexStrings; + + bool mCaseSensitive; + + LanguageDefinition() + : mPreprocChar('#'), mAutoIndentation(true), mTokenize(nullptr), mCaseSensitive(true) + { + } + + static const LanguageDefinition& CPlusPlus(); + static const LanguageDefinition& HLSL(); + static const LanguageDefinition& GLSL(); + static const LanguageDefinition& C(); + static const LanguageDefinition& SQL(); + static const LanguageDefinition& AngelScript(); + static const LanguageDefinition& Lua(); + static const LanguageDefinition& Python(); + }; + + mvTextEditor(); + ~mvTextEditor(); + + void ClearUndo() { mUndoBuffer.clear(); mUndoIndex = 0; } + + void SetLanguageDefinition(const LanguageDefinition& aLanguageDef); + const LanguageDefinition& GetLanguageDefinition() const { return mLanguageDefinition; } + + const Palette& GetPalette() const { return mPaletteBase; } + void SetPalette(const Palette& aValue); + + void SetErrorMarkers(const ErrorMarkers& aMarkers) { mErrorMarkers = aMarkers; } + void SetBreakpoints(const Breakpoints& aMarkers) { mBreakpoints = aMarkers; } + + void Render(const char* aTitle, const ImVec2& aSize = ImVec2(), bool aBorder = false); + void SetText(const std::string& aText); + std::string GetText() const; + + void SetTextLines(const std::vector& aLines); + std::vector GetTextLines() const; + + std::string GetSelectedText() const; + std::string GetCurrentLineText()const; + + int GetTotalLines() const { return (int)mLines.size(); } + bool IsOverwrite() const { return mOverwrite; } + + void SetReadOnly(bool aValue); + bool IsReadOnly() const { return mReadOnly; } + bool IsTextChanged() const { return mTextChanged; } + bool IsCursorPositionChanged() const { return mCursorPositionChanged; } + + bool IsColorizerEnabled() const { return mColorizerEnabled; } + void SetColorizerEnable(bool aValue); + + Coordinates GetCursorPosition() const { return GetActualCursorCoordinates(); } + void SetCursorPosition(const Coordinates& aPosition); + + inline void SetHandleMouseInputs(bool aValue) { mHandleMouseInputs = aValue; } + inline bool IsHandleMouseInputsEnabled() const { return mHandleKeyboardInputs; } + + inline void SetHandleKeyboardInputs(bool aValue) { mHandleKeyboardInputs = aValue; } + inline bool IsHandleKeyboardInputsEnabled() const { return mHandleKeyboardInputs; } + + inline void SetImGuiChildIgnored(bool aValue) { mIgnoreImGuiChild = aValue; } + inline bool IsImGuiChildIgnored() const { return mIgnoreImGuiChild; } + + inline void SetShowWhitespaces(bool aValue) { mShowWhitespaces = aValue; } + inline bool IsShowingWhitespaces() const { return mShowWhitespaces; } + + void SetTabSize(int aValue); + inline int GetTabSize() const { return mTabSize; } + + void InsertText(const std::string& aValue); + void InsertText(const char* aValue); + + void MoveUp(int aAmount = 1, bool aSelect = false); + void MoveDown(int aAmount = 1, bool aSelect = false); + void MoveLeft(int aAmount = 1, bool aSelect = false, bool aWordMode = false); + void MoveRight(int aAmount = 1, bool aSelect = false, bool aWordMode = false); + void MoveTop(bool aSelect = false); + void MoveBottom(bool aSelect = false); + void MoveHome(bool aSelect = false); + void MoveEnd(bool aSelect = false); + + void SetSelectionStart(const Coordinates& aPosition); + void SetSelectionEnd(const Coordinates& aPosition); + void SetSelection(const Coordinates& aStart, const Coordinates& aEnd, SelectionMode aMode = SelectionMode::Normal); + void SelectWordUnderCursor(); + void SelectAll(); + bool HasSelection() const; + + void Copy(); + void Cut(); + void Paste(); + void Delete(); + + bool CanUndo() const; + bool CanRedo() const; + void Undo(int aSteps = 1); + void Redo(int aSteps = 1); + + static const Palette& GetDarkPalette(); + static const Palette& GetLightPalette(); + static const Palette& GetRetroBluePalette(); + + private: + + typedef std::vector> RegexList; + + struct EditorState + { + Coordinates mSelectionStart; + Coordinates mSelectionEnd; + Coordinates mCursorPosition; + }; + + class UndoRecord + { + public: + UndoRecord() {} + ~UndoRecord() {} + + UndoRecord( + const std::string& aAdded, + const mvTextEditor::Coordinates aAddedStart, + const mvTextEditor::Coordinates aAddedEnd, + + const std::string& aRemoved, + const mvTextEditor::Coordinates aRemovedStart, + const mvTextEditor::Coordinates aRemovedEnd, + + mvTextEditor::EditorState& aBefore, + mvTextEditor::EditorState& aAfter); + + void Undo(mvTextEditor* aEditor); + void Redo(mvTextEditor* aEditor); + + std::string mAdded; + Coordinates mAddedStart; + Coordinates mAddedEnd; + + std::string mRemoved; + Coordinates mRemovedStart; + Coordinates mRemovedEnd; + + EditorState mBefore; + EditorState mAfter; + }; + + typedef std::vector UndoBuffer; + + void ProcessInputs(); + void Colorize(int aFromLine = 0, int aCount = -1); + void ColorizeRange(int aFromLine = 0, int aToLine = 0); + void ColorizeInternal(); + float TextDistanceToLineStart(const Coordinates& aFrom) const; + void EnsureCursorVisible(); + int GetPageSize() const; + std::string GetText(const Coordinates& aStart, const Coordinates& aEnd) const; + Coordinates GetActualCursorCoordinates() const; + Coordinates SanitizeCoordinates(const Coordinates& aValue) const; + void Advance(Coordinates& aCoordinates) const; + void DeleteRange(const Coordinates& aStart, const Coordinates& aEnd); + int InsertTextAt(Coordinates& aWhere, const char* aValue); + void AddUndo(UndoRecord& aValue); + Coordinates ScreenPosToCoordinates(const ImVec2& aPosition) const; + Coordinates FindWordStart(const Coordinates& aFrom) const; + Coordinates FindWordEnd(const Coordinates& aFrom) const; + Coordinates FindNextWord(const Coordinates& aFrom) const; + int GetCharacterIndex(const Coordinates& aCoordinates) const; + int GetCharacterColumn(int aLine, int aIndex) const; + int GetLineCharacterCount(int aLine) const; + int GetLineMaxColumn(int aLine) const; + bool IsOnWordBoundary(const Coordinates& aAt) const; + void RemoveLine(int aStart, int aEnd); + void RemoveLine(int aIndex); + Line& InsertLine(int aIndex); + void EnterCharacter(ImWchar aChar, bool aShift); + void Backspace(); + void DeleteSelection(); + std::string GetWordUnderCursor() const; + std::string GetWordAt(const Coordinates& aCoords) const; + ImU32 GetGlyphColor(const Glyph& aGlyph) const; + + void HandleKeyboardInputs(); + void HandleMouseInputs(); + void Render(); + + float mLineSpacing; + Lines mLines; + EditorState mState; + UndoBuffer mUndoBuffer; + int mUndoIndex; + + int mTabSize; + bool mOverwrite; + bool mReadOnly; + bool mWithinRender; + bool mScrollToCursor; + bool mScrollToTop; + bool mTextChanged; + bool mColorizerEnabled; + float mTextStart; // position (in pixels) where a code line starts relative to the left of the TextEditor. + int mLeftMargin; + bool mCursorPositionChanged; + int mColorRangeMin, mColorRangeMax; + SelectionMode mSelectionMode; + bool mHandleKeyboardInputs; + bool mHandleMouseInputs; + bool mIgnoreImGuiChild; + bool mShowWhitespaces; + + Palette mPaletteBase; + Palette mPalette; + LanguageDefinition mLanguageDefinition; + RegexList mRegexList; + + bool mCheckComments; + Breakpoints mBreakpoints; + ErrorMarkers mErrorMarkers; + ImVec2 mCharAdvance; + Coordinates mInteractiveStart, mInteractiveEnd; + std::string mLineBuffer; + uint64_t mStartTime; + + float mLastClick; + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvTimePicker.cpp b/DearPyGui/src/core/AppItems/custom/mvTimePicker.cpp new file mode 100644 index 000000000..7956dfc13 --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvTimePicker.cpp @@ -0,0 +1,67 @@ +#include "mvTimePicker.h" +#include +#include +#include +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTimePicker::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Dict, "default_value", "time dict", "{'hour': 14, 'min': 32, 'sec': 23}"}, + {mvPythonDataType::Bool, "hour24", "show 24 hour clock", "False"}, + {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a time selector widget.", "None", "Adding Widgets") }); + } + + mvTimePicker::mvTimePicker(const std::string& name) + : + mvTimePtrBase(name) + { + } + + void mvTimePicker::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImPlot::GetStyle().Use24HourClock = m_hour24; + + if (ImPlot::ShowTimePicker(m_name.c_str(), m_imvalue.get())) + { + ImPlot::GetGmtTime(*m_imvalue, m_value.get()); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, m_callback_data); + } + + } + + void mvTimePicker::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "hour24")) m_hour24 = ToBool(item); + } + + void mvTimePicker::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "hour24", ToPyBool(m_hour24)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/custom/mvTimePicker.h b/DearPyGui/src/core/AppItems/custom/mvTimePicker.h new file mode 100644 index 000000000..a708dda45 --- /dev/null +++ b/DearPyGui/src/core/AppItems/custom/mvTimePicker.h @@ -0,0 +1,96 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTimePicker, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Time, 1); + class mvTimePicker : public mvTimePtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTimePicker, add_time_picker) + + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_Time , ImGuiCol_Text , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_TimeHovered , ImGuiCol_ButtonHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_DropSelected , ImGuiCol_Header , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_DropHovered , ImGuiCol_HeaderHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_DropActive , ImGuiCol_HeaderActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_DropBg , ImGuiCol_PopupBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_Scrollbar , ImGuiCol_ScrollbarBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_ScrollbarGrab , ImGuiCol_ScrollbarGrab , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_ScrollbarGrabHovered , ImGuiCol_ScrollbarGrabHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_ScrollbarGrabActive , ImGuiCol_ScrollbarGrabActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_Border , ImGuiCol_Border , 0L); + MV_CREATE_CONSTANT(mvThemeCol_TimePicker_BorderShadow , ImGuiCol_BorderShadow , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_TextAlignX , ImGuiStyleVar_ButtonTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_TextAlignY , ImGuiStyleVar_ButtonTextAlign , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropPaddingX , ImGuiStyleVar_WindowPadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropPaddingY , ImGuiStyleVar_WindowPadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropBorderSize , ImGuiStyleVar_PopupBorderSize , 0L) + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropItemSpacingX , ImGuiStyleVar_ItemSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropItemSpacingY , ImGuiStyleVar_ItemSpacing , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropTextAlignX , ImGuiStyleVar_SelectableTextAlign , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_TimePicker_DropTextAlignY , ImGuiStyleVar_SelectableTextAlign , 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_Time, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_TimeHovered, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_DropSelected, mvColor( 66, 150, 250, 79)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_DropHovered, mvColor( 66, 150, 250, 102)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_DropActive, mvColor( 66, 150, 250, 171)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_DropBg, mvColor( 20, 20, 20, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_Scrollbar, mvColor( 5, 5, 5, 135)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_ScrollbarGrab, mvColor( 79, 79, 79, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_ScrollbarGrabHovered, mvColor(105, 105, 105, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_ScrollbarGrabActive, mvColor(130, 130, 130, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_TimePicker_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_PaddingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_TextAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_TextAlignY , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropPaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropPaddingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropBorderSize , 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropItemSpacingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropItemSpacingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropTextAlignX , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_TimePicker_DropTextAlignY , 0, 1), + MV_END_STYLE_CONSTANTS + + public: + + mvTimePicker(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y)override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_hour24 = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.cpp new file mode 100644 index 000000000..455eb6b4e --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.cpp @@ -0,0 +1,116 @@ +#include "mvDrawArrow.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawArrow::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "p1"}, + {mvPythonDataType::FloatList, "p2"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::Integer, "thickness"}, + {mvPythonDataType::Integer, "size"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws an arrow on a drawing.", "None", "Drawing") }); + + } + + mvDrawArrow::mvDrawArrow(const std::string& name) + : + mvAppItem(name) + { + updatePoints(); + } + + void mvDrawArrow::updatePoints() + { + float xsi = m_p1.x; + float xfi = m_p2.x; + float ysi = m_p1.y; + float yfi = m_p2.y; + + // length of arrow head + double xoffset = m_size; + double yoffset = m_size; + + // get pointer angle w.r.t +X (in radians) + double angle = 0.0; + if (xsi >= xfi && ysi >= yfi) { + angle = atan((ysi - yfi) / (xsi - xfi)); + } + else if (xsi < xfi && ysi >= yfi) { + angle = M_PI + atan((ysi - yfi) / (xsi - xfi)); + } + else if (xsi < xfi && ysi < yfi) { + angle = -M_PI + atan((ysi - yfi) / (xsi - xfi)); + } + else if (xsi >= xfi && ysi < yfi) { + angle = atan((ysi - yfi) / (xsi - xfi)); + } + + // arrow head points + auto x1 = (float)(xsi - xoffset * cos(angle)); + auto y1 = (float)(ysi - yoffset * sin(angle)); + + m_points.clear(); + m_points.push_back({ xsi, ysi }); + m_points.push_back({ (float)(x1 - 0.5 * m_size * sin(angle)), (float)(y1 + 0.5 * m_size * cos(angle)) }); + m_points.push_back({ (float)(x1 + 0.5 * m_size * cos((M_PI / 2.0) - angle)), (float)(y1 - 0.5 * m_size * sin((M_PI / 2.0) - angle)) }); + + } + + bool mvDrawArrow::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawArrow::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + drawlist->AddLine(m_p1 + start, m_p2 + start, m_color, m_thickness); + drawlist->AddTriangle(m_points[0] + start, m_points[1] + start, m_points[2] + start, m_color, m_thickness); + drawlist->AddTriangleFilled(m_points[0] + start, m_points[1] + start, m_points[2] + start, m_color); + } + + void mvDrawArrow::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + if (PyObject* item = PyDict_GetItemString(dict, "p1")) m_p1 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p2")) m_p2 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToFloat(item); + + updatePoints(); + + } + + void mvDrawArrow::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + PyDict_SetItemString(dict, "p1", ToPyPair(m_p1.x, m_p1.y)); + PyDict_SetItemString(dict, "p2", ToPyPair(m_p2.x, m_p2.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + PyDict_SetItemString(dict, "size", ToPyFloat(m_size)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.h b/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.h new file mode 100644 index 000000000..2d1a6f79c --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawArrow.h @@ -0,0 +1,55 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawArrow, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawArrow : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawArrow, draw_arrow) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawArrow(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + void updatePoints(); + + private: + + mvVec2 m_p1; + mvVec2 m_p2; + mvColor m_color; + float m_thickness; + float m_size; + std::vector m_points; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.cpp new file mode 100644 index 000000000..a53ff26db --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.cpp @@ -0,0 +1,78 @@ +#include "mvDrawBezierCurve.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawBezierCurve::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "p1"}, + {mvPythonDataType::FloatList, "p2"}, + {mvPythonDataType::FloatList, "p3"}, + {mvPythonDataType::FloatList, "p4"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::Integer, "segments", "", "0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a bezier curve on a drawing.", "None", "Drawing") }); + } + + mvDrawBezierCurve::mvDrawBezierCurve(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawBezierCurve::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawBezierCurve::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + drawlist->AddBezierCubic(m_p1 + start, m_p2 + start, m_p3 + start, m_p4 + start, m_color, m_thickness); + } + + void mvDrawBezierCurve::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "p1")) m_p1 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p2")) m_p2 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p3")) m_p3 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p4")) m_p4 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "segments")) m_segments = ToInt(item); + } + + void mvDrawBezierCurve::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "p1", ToPyPair(m_p1.x, m_p1.y)); + PyDict_SetItemString(dict, "p2", ToPyPair(m_p2.x, m_p2.y)); + PyDict_SetItemString(dict, "p3", ToPyPair(m_p3.x, m_p3.y)); + PyDict_SetItemString(dict, "p4", ToPyPair(m_p4.x, m_p4.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + PyDict_SetItemString(dict, "segments", ToPyInt(m_segments)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.h b/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.h new file mode 100644 index 000000000..a34c544c4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawBezierCurve.h @@ -0,0 +1,52 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawBezierCurve, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawBezierCurve : public mvAppItem + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawBezierCurve, draw_bezier_curve) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawBezierCurve(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_p1; + mvVec2 m_p2; + mvVec2 m_p3; + mvVec2 m_p4; + mvColor m_color; + float m_thickness; + int m_segments; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.cpp new file mode 100644 index 000000000..df42ee5b7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.cpp @@ -0,0 +1,82 @@ +#include "mvDrawCircle.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawCircle::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "center"}, + {mvPythonDataType::Float, "radius"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::Integer, "segments", "", "0"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a circle on a drawing.", "None", "Drawing") }); + } + + mvDrawCircle::mvDrawCircle(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawCircle::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawCircle::draw(ImDrawList* drawlist, float x, float y) + { + + mvVec2 start = { x, y }; + if (m_fill.r > 0.0f) + drawlist->AddCircleFilled(m_center + start, m_radius, m_fill, m_segments); + + drawlist->AddCircle(m_center + start, m_radius, m_color, m_segments, m_thickness); + + } + + void mvDrawCircle::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + if (PyObject* item = PyDict_GetItemString(dict, "center")) m_center = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "radius")) m_radius = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "segments")) m_segments = ToInt(item); + + } + + void mvDrawCircle::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "center", ToPyPair(m_center.x, m_center.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "fill", ToPyColor(m_fill)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + PyDict_SetItemString(dict, "radius", ToPyFloat(m_radius)); + PyDict_SetItemString(dict, "segments", ToPyInt(m_segments)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.h b/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.h new file mode 100644 index 000000000..45c042da7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawCircle.h @@ -0,0 +1,51 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawCircle, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawCircle : public mvAppItem + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawCircle, draw_circle) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawCircle(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_center; + float m_radius; + int m_segments; + mvColor m_color; + mvColor m_fill; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawImage.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawImage.cpp new file mode 100644 index 000000000..ab483e0d9 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawImage.cpp @@ -0,0 +1,147 @@ +#include "mvDrawImage.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvTextureStorage.h" +#include "mvApp.h" + +namespace Marvel { + + void mvDrawImage::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "file"}, + {mvPythonDataType::FloatList, "pmin", "top left coordinate"}, + {mvPythonDataType::FloatList, "pmax", "bottom right coordinate"}, + {mvPythonDataType::FloatList, "uv_min", "normalized texture coordinates", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "uv_max", "normalized texture coordinates", "(1.0, 1.0)"}, + {mvPythonDataType::IntList, "color", "", "(255, 255, 255, 255)"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, ("Draws an image on a drawing. p_min (bottom-left) and p_max (upper-right) represent corners of the rectangle the image will be drawn to." + "Setting the p_min equal to the p_max will sraw the image to with 1:1 scale." + "uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using (0,0)->(1,1) texture" + "coordinates will generally display the entire texture."), "None", "Drawing") }); + } + + mvDrawImage::mvDrawImage(const std::string& name) + : + mvAppItem(name) + { + mvEventBus::Subscribe(this, mvEVT_DELETE_TEXTURE); + } + + mvDrawImage::~mvDrawImage() + { + mvEventBus::Publish(mvEVT_CATEGORY_TEXTURE, mvEVT_DEC_TEXTURE, { CreateEventArgument("NAME", m_file) }); + mvEventBus::UnSubscribe(this); + } + + bool mvDrawImage::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvDrawImage::onTextureDeleted), mvEVT_DELETE_TEXTURE); + + return event.handled; + } + + bool mvDrawImage::onTextureDeleted(mvEvent& event) + { + std::string name = GetEString(event, "NAME"); + + if (name == m_file) + { + m_texture = nullptr; + return false; + } + + return false; + } + + bool mvDrawImage::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawImage::draw(ImDrawList* drawlist, float x, float y) + { + + if (m_texture == nullptr && !m_file.empty()) + { + + mvApp::GetApp()->getTextureStorage().addTexture(m_file); + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_file); + if (texture == nullptr) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([&]() + { + PyErr_Format(PyExc_Exception, + "Image %s could not be found for draw_image. Check the path to the image " + "you provided.", m_file.c_str()); + PyErr_Print(); + m_file = ""; + }); + return; + } + + m_texture = texture->texture; + + if (m_width == 0) m_width = (int)((float)texture->width * (m_uv_max.x - m_uv_min.x)); + if (m_height == 0) m_height = (int)((float)texture->height * (m_uv_max.y - m_uv_min.y)); + + } + + mvVec2 start = { x, y }; + + if (m_texture) + drawlist->AddImage(m_texture, m_pmin + start, m_pmax + start, m_uv_min, m_uv_max, m_color); + } + + void mvDrawImage::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "pmax")) m_pmax = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "pmin")) m_pmin = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) m_uv_min = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) m_uv_max = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + + if (PyObject* item = PyDict_GetItemString(dict, "file")) + { + if (m_file != ToString(item)) + { + mvApp::GetApp()->getTextureStorage().decrementTexture(m_file); + m_texture = nullptr; + } + m_file = ToString(item); + + } + + } + + void mvDrawImage::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "pmax", ToPyPair(m_pmax.x, m_pmax.y)); + PyDict_SetItemString(dict, "pmin", ToPyPair(m_pmin.x, m_pmin.y)); + PyDict_SetItemString(dict, "uv_min", ToPyPair(m_uv_min.x, m_uv_min.y)); + PyDict_SetItemString(dict, "uv_max", ToPyPair(m_uv_max.x, m_uv_max.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "file", ToPyString(m_file)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawImage.h b/DearPyGui/src/core/AppItems/drawing/mvDrawImage.h new file mode 100644 index 000000000..3d9f11415 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawImage.h @@ -0,0 +1,57 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawImage, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawImage : public mvAppItem, public mvEventHandler + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawImage, draw_image) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawImage(const std::string& name); + ~mvDrawImage() override; + + bool onEvent(mvEvent& event) override; + bool onTextureDeleted(mvEvent& event); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + + std::string m_file; + mvVec2 m_pmax; + mvVec2 m_pmin; + mvVec2 m_uv_min; + mvVec2 m_uv_max; + mvColor m_color; + void* m_texture = nullptr; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawLine.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawLine.cpp new file mode 100644 index 000000000..ea8edbedf --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawLine.cpp @@ -0,0 +1,73 @@ +#include "mvDrawLine.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawLine::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "p1"}, + {mvPythonDataType::FloatList, "p2"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::Integer, "thickness"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a line on a drawing.", "None", "Drawing") }); + } + + mvDrawLine::mvDrawLine(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawLine::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawLine::draw(ImDrawList* drawlist, float x, float y) + { + + mvVec2 start = { x, y }; + drawlist->AddLine(m_p1 + start, m_p2 + start, m_color, m_thickness); + + } + + void mvDrawLine::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + + if (PyObject* item = PyDict_GetItemString(dict, "p1")) m_p1 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p2")) m_p2 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + + } + + void mvDrawLine::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "p1", ToPyPair(m_p1.x, m_p1.y)); + PyDict_SetItemString(dict, "p2", ToPyPair(m_p2.x, m_p2.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawLine.h b/DearPyGui/src/core/AppItems/drawing/mvDrawLine.h new file mode 100644 index 000000000..44fbfebce --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawLine.h @@ -0,0 +1,49 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawLine, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawLine : public mvAppItem + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawLine, draw_line) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawLine(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_p1; + mvVec2 m_p2; + mvColor m_color; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.cpp new file mode 100644 index 000000000..22f36e256 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.cpp @@ -0,0 +1,148 @@ +#include "mvDrawPolygon.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawPolygon::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::ListFloatList, "points"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a polygon on a drawing.", "None", "Drawing") }); + } + + mvDrawPolygon::mvDrawPolygon(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawPolygon::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawPolygon::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + std::vector points = m_points; + for (auto& point : points) + point = point + start; + + if (m_fill.r > 0.0f) + { + size_t i; + int y; + int miny, maxy; + int x1, y1; + int x2, y2; + int ind1, ind2; + size_t ints; + size_t n = m_points.size(); + int* polyints = new int[n]; + + /* Determine Y maxima */ + miny = (int)m_points[0].y; + maxy = (int)m_points[0].y; + for (i = 1; i < n; i++) + { + miny = std::min(miny, (int)m_points[i].y); + maxy = std::max(maxy, (int)m_points[i].y); + } + + /* Draw, scanning y */ + for (y = miny; y <= maxy; y++) { + ints = 0; + for (i = 0; (i < n); i++) { + if (!i) + { + ind1 = (int)n - 1; + ind2 = 0; + } + else + { + ind1 = (int)i - 1; + ind2 = (int)i; + } + y1 = (int)m_points[ind1].y; + y2 = (int)m_points[ind2].y; + if (y1 < y2) + { + x1 = (int)m_points[ind1].x; + x2 = (int)m_points[ind2].x; + } + else if (y1 > y2) + { + y2 = (int)m_points[ind1].y; + y1 = (int)m_points[ind2].y; + x2 = (int)m_points[ind1].x; + x1 = (int)m_points[ind2].x; + } + else + continue; + + if (((y >= y1) && (y < y2)) || ((y == maxy) && (y > y1) && (y <= y2))) + polyints[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; + + } + + auto compare_int = [](const void* a, const void* b) + { + return (*(const int*)a) - (*(const int*)b); + }; + + qsort(polyints, ints, sizeof(int), compare_int); + + for (i = 0; i < ints; i += 2) + { + drawlist->AddLine({ (float)polyints[i] + start.x, (float)y + start.y }, + { (float)polyints[i + 1] + start.x, (float)y + start.y }, m_fill, m_thickness); + } + } + delete[] polyints; + } + + drawlist->AddPolyline((const ImVec2*)const_cast(points.data()), (int)m_points.size(), m_color, false, m_thickness); + } + + void mvDrawPolygon::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "points")) m_points = ToVectVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + + } + + void mvDrawPolygon::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "points", ToPyList(m_points)); + PyDict_SetItemString(dict, "fill", ToPyColor(m_fill)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.h b/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.h new file mode 100644 index 000000000..9475440ce --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawPolygon.h @@ -0,0 +1,49 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawPolygon, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawPolygon : public mvAppItem + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawPolygon, draw_polygon) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawPolygon(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + std::vector m_points; + mvColor m_color; + mvColor m_fill; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.cpp new file mode 100644 index 000000000..d5a6ab1b2 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.cpp @@ -0,0 +1,74 @@ +#include "mvDrawPolyline.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawPolyline::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::ListFloatList, "points"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::Bool, "closed", "", "False"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws lines on a drawing.", "None", "Drawing") }); + } + + mvDrawPolyline::mvDrawPolyline(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawPolyline::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawPolyline::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + + std::vector points = m_points; + + for (auto& point : points) + point = point + start; + + drawlist->AddPolyline((const ImVec2*)const_cast(points.data()), (int)m_points.size(), m_color, m_closed, m_thickness); + } + + void mvDrawPolyline::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "points")) m_points = ToVectVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "closed")) m_closed = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + } + + void mvDrawPolyline::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "points", ToPyList(m_points)); + PyDict_SetItemString(dict, "closed", ToPyBool(m_closed)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.h b/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.h new file mode 100644 index 000000000..fe65583a6 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawPolyline.h @@ -0,0 +1,50 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawPolyline, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawPolyline : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawPolyline, draw_polyline) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawPolyline(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + std::vector m_points; + mvColor m_color; + bool m_closed; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.cpp new file mode 100644 index 000000000..0850f5332 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.cpp @@ -0,0 +1,82 @@ +#include "mvDrawQuad.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawQuad::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "p1"}, + {mvPythonDataType::FloatList, "p2"}, + {mvPythonDataType::FloatList, "p3"}, + {mvPythonDataType::FloatList, "p4"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a quad on a drawing.", "None", "Drawing") }); + } + + mvDrawQuad::mvDrawQuad(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawQuad::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawQuad::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + if (m_fill.r > 0.0f) + drawlist->AddQuadFilled(m_p1 + start, m_p2 + start, m_p3 + start, m_p4 + start, m_fill); + drawlist->AddQuad(m_p1 + start, m_p2 + start, m_p3 + start, m_p4 + start, m_color, m_thickness); + } + + void mvDrawQuad::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "p1")) m_p1 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p2")) m_p2 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p3")) m_p3 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p4")) m_p4 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + + + } + + void mvDrawQuad::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "p1", ToPyPair(m_p1.x, m_p1.y)); + PyDict_SetItemString(dict, "p2", ToPyPair(m_p2.x, m_p2.y)); + PyDict_SetItemString(dict, "p3", ToPyPair(m_p3.x, m_p3.y)); + PyDict_SetItemString(dict, "p4", ToPyPair(m_p4.x, m_p4.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "fill", ToPyColor(m_fill)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.h b/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.h new file mode 100644 index 000000000..381499f25 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawQuad.h @@ -0,0 +1,53 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawQuad, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawQuad : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawQuad, draw_quad) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawQuad(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_p1; + mvVec2 m_p2; + mvVec2 m_p3; + mvVec2 m_p4; + mvColor m_color; + mvColor m_fill; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawRect.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawRect.cpp new file mode 100644 index 000000000..01fa666df --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawRect.cpp @@ -0,0 +1,77 @@ +#include "mvDrawRect.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawRect::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "pmin", "top left coordinate"}, + {mvPythonDataType::FloatList, "pmax", "bottom right coordinate"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "rounding", "", "0.0"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a line on a drawing.", "None", "Drawing") }); + } + + mvDrawRect::mvDrawRect(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawRect::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawRect::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + if (m_fill.r > 0.0f) + drawlist->AddRectFilled(m_pmin + start, m_pmax + start, m_fill, m_rounding, ImDrawCornerFlags_All); + drawlist->AddRect(m_pmin + start, m_pmax + start, m_color, m_rounding, ImDrawCornerFlags_All, m_thickness); + } + + void mvDrawRect::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "pmax")) m_pmax = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "pmin")) m_pmin = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "rounding")) m_rounding = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + } + + void mvDrawRect::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "pmax", ToPyPair(m_pmax.x, m_pmax.y)); + PyDict_SetItemString(dict, "pmin", ToPyPair(m_pmin.x, m_pmin.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "fill", ToPyColor(m_fill)); + PyDict_SetItemString(dict, "rounding", ToPyFloat(m_rounding)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawRect.h b/DearPyGui/src/core/AppItems/drawing/mvDrawRect.h new file mode 100644 index 000000000..1b3bd9ddc --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawRect.h @@ -0,0 +1,52 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawRect, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawRect : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawRect, draw_rectangle) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawRect(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_pmin; + mvVec2 m_pmax; + float m_rounding; + mvColor m_color; + mvColor m_fill; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawText.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawText.cpp new file mode 100644 index 000000000..8532e7402 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawText.cpp @@ -0,0 +1,69 @@ +#include "mvDrawText.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawText::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "pos"}, + {mvPythonDataType::String, "text"}, + {mvPythonDataType::IntList, "color", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Integer, "size", "", "10"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws text on a drawing.", "None", "Drawing") }); + } + + mvDrawText::mvDrawText(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawText::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawText::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + drawlist->AddText(ImGui::GetFont(), (float)m_size, m_pos + start, m_color, m_text.c_str()); + } + + void mvDrawText::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "text")) m_text = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "pos")) m_pos = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "size")) m_size = ToInt(item); + + } + + void mvDrawText::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "text", ToPyString(m_text)); + PyDict_SetItemString(dict, "pos", ToPyPair(m_pos.x, m_pos.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "size", ToPyInt(m_size)); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawText.h b/DearPyGui/src/core/AppItems/drawing/mvDrawText.h new file mode 100644 index 000000000..940bc2937 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawText.h @@ -0,0 +1,50 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawText : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawText, draw_text) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawText(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_pos; + std::string m_text; + mvColor m_color; + int m_size; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.cpp new file mode 100644 index 000000000..31ffc6761 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.cpp @@ -0,0 +1,80 @@ +#include "mvDrawTriangle.h" +#include "mvLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvDrawTriangle::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "p1"}, + {mvPythonDataType::FloatList, "p2"}, + {mvPythonDataType::FloatList, "p3"}, + {mvPythonDataType::IntList, "color"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Draws a triangle on a drawing.", "None", "Drawing") }); + + } + + mvDrawTriangle::mvDrawTriangle(const std::string& name) + : + mvAppItem(name) + { + } + + bool mvDrawTriangle::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawing) return true; + if (type == mvAppItemType::mvWindowAppItem) return true; + + mvThrowPythonError(1000, "Drawing item parent must be a drawing."); + MV_ITEM_REGISTRY_ERROR("Drawing item parent must be a drawing."); + assert(false); + return false; + } + + void mvDrawTriangle::draw(ImDrawList* drawlist, float x, float y) + { + mvVec2 start = { x, y }; + if (m_fill.r > 0.0f) + drawlist->AddTriangleFilled(m_p1 + start, m_p2 + start, m_p3 + start, m_fill); + + drawlist->AddTriangle(m_p1 + start, m_p2 + start, m_p3 + start, m_color, m_thickness); + } + + void mvDrawTriangle::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "p1")) m_p1 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p2")) m_p2 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "p3")) m_p3 = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + + } + + void mvDrawTriangle::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "p1", ToPyPair(m_p1.x, m_p1.y)); + PyDict_SetItemString(dict, "p2", ToPyPair(m_p2.x, m_p2.y)); + PyDict_SetItemString(dict, "p3", ToPyPair(m_p3.x, m_p3.y)); + PyDict_SetItemString(dict, "color", ToPyColor(m_color)); + PyDict_SetItemString(dict, "thickness", ToPyColor(m_fill)); + PyDict_SetItemString(dict, "thickness", ToPyFloat(m_thickness)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.h b/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.h new file mode 100644 index 000000000..b369b191e --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawTriangle.h @@ -0,0 +1,52 @@ +#pragma once + +#include "mvAppItem.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawTriangle, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvDrawTriangle : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawTriangle, draw_triangle) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDrawTriangle(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + + private: + + mvVec2 m_p1; + mvVec2 m_p2; + mvVec2 m_p3; + mvColor m_color; + mvColor m_fill; + float m_thickness; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawing.cpp b/DearPyGui/src/core/AppItems/drawing/mvDrawing.cpp new file mode 100644 index 000000000..eac48ac76 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawing.cpp @@ -0,0 +1,85 @@ +#include "mvDrawing.h" +#include "mvApp.h" +#include "mvInput.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" +#include "mvViewport.h" +#include "mvAppItemCommons.h" +#include "mvLog.h" + +namespace Marvel { + + void mvDrawing::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::Bool, "show","Attempt to render", "True"}, + }, "Adds a drawing widget.", "None", "Drawing") }); + + } + + mvDrawing::mvDrawing(const std::string& name) + : mvAppItem(name) + { + } + + bool mvDrawing::canChildBeAdded(mvAppItemType type) + { + if (type == mvAppItemType::mvDrawLine) return true; + if (type == mvAppItemType::mvDrawArrow) return true; + if (type == mvAppItemType::mvDrawTriangle) return true; + if (type == mvAppItemType::mvDrawCircle) return true; + if (type == mvAppItemType::mvDrawBezierCurve) return true; + if (type == mvAppItemType::mvDrawQuad) return true; + if (type == mvAppItemType::mvDrawRect) return true; + if (type == mvAppItemType::mvDrawText) return true; + if (type == mvAppItemType::mvDrawPolygon) return true; + if (type == mvAppItemType::mvDrawPolyline) return true; + if (type == mvAppItemType::mvDrawImage) return true; + + mvThrowPythonError(1000, "Drawing children must be draw commands only."); + MV_ITEM_REGISTRY_ERROR("Drawing children must be draw commands only."); + assert(false); + + return false; + } + + void mvDrawing::draw(ImDrawList* drawlist, float x, float y) + { + mvFontScope fscope(this); + + m_startx = (float)ImGui::GetCursorScreenPos().x; + m_starty = (float)ImGui::GetCursorScreenPos().y; + + ImGui::PushClipRect({ m_startx, m_starty }, { m_startx + (float)m_width, m_starty + (float)m_height }, true); + + for (auto& item : m_children[0]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + item->draw(drawlist, m_startx, m_starty); + + item->getState().update(); + } + + ImGui::PopClipRect(); + ImGui::Dummy(ImVec2((float)m_width, (float)m_height)); + + + if (ImGui::IsItemHovered()) + { + ImVec2 mousepos = ImGui::GetMousePos(); + mvInput::setDrawingMousePosition((float)mousepos.x- m_startx, (float)mousepos.y - m_starty); + } + } + +} diff --git a/DearPyGui/src/core/AppItems/drawing/mvDrawing.h b/DearPyGui/src/core/AppItems/drawing/mvDrawing.h new file mode 100644 index 000000000..f1fd8fef5 --- /dev/null +++ b/DearPyGui/src/core/AppItems/drawing/mvDrawing.h @@ -0,0 +1,40 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDrawing, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvDrawing : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDrawing, add_drawing) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvDrawing(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool canChildBeAdded(mvAppItemType type) override; + + private: + + float m_startx = 0.0f; + float m_starty = 0.0f; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvDummy.cpp b/DearPyGui/src/core/AppItems/misc/mvDummy.cpp new file mode 100644 index 000000000..d6f765289 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvDummy.cpp @@ -0,0 +1,34 @@ +#include "mvDummy.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + + + void mvDummy::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'dummy'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "width", "", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"} + }, "Adds a spacer or 'dummy' object.", "None", "Adding Widgets") }); + } + + + mvDummy::mvDummy(const std::string& name) + : mvAppItem(name) + { + } + + void mvDummy::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::Dummy({ (float)m_width, (float)m_height }); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvDummy.h b/DearPyGui/src/core/AppItems/misc/mvDummy.h new file mode 100644 index 000000000..bc2446e03 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvDummy.h @@ -0,0 +1,35 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDummy, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvDummy : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDummy, add_dummy) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvDummy(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvIndent.cpp b/DearPyGui/src/core/AppItems/misc/mvIndent.cpp new file mode 100644 index 000000000..a0a09cdb3 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvIndent.cpp @@ -0,0 +1,32 @@ +#include "mvIndent.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + + void mvIndent::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'indent'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "offset", "", "0.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds an indent to following items. Must be closed with the unindent command.", "None", "Adding Widgets") }); + } + + + mvIndent::mvIndent(const std::string& name) + : mvFloatPtrBase(name) + { + } + + void mvIndent::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::Indent(*m_value); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvIndent.h b/DearPyGui/src/core/AppItems/misc/mvIndent.h new file mode 100644 index 000000000..de69adc42 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvIndent.h @@ -0,0 +1,38 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvIndent, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvIndent : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvIndent, add_indent) + + MV_CREATE_CONSTANT(mvThemeStyle_Indent_Spacing, 11L, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Indent_Spacing, 21, 30), + MV_END_STYLE_CONSTANTS + + mvIndent(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvProgressBar.cpp b/DearPyGui/src/core/AppItems/misc/mvProgressBar.cpp new file mode 100644 index 000000000..6874faa92 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvProgressBar.cpp @@ -0,0 +1,59 @@ +#include +#include "mvProgressBar.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvProgressBar::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "default_value", "value from 0 to 1", "0.0"}, + {mvPythonDataType::String, "overlay", "overlayed text", "''"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::String, "source", "data source for shared data", "''"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a progress bar.", "None", "Adding Widgets") }); + } + + mvProgressBar::mvProgressBar(const std::string& name) + : mvFloatPtrBase(name) + { + } + + void mvProgressBar::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + ImGui::ProgressBar(*m_value, ImVec2((float)m_width, (float)m_height), m_overlay.c_str()); + + } + + void mvProgressBar::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "overlay")) m_overlay = ToString(item); + } + + void mvProgressBar::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "overlay", ToPyString(m_overlay)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvProgressBar.h b/DearPyGui/src/core/AppItems/misc/mvProgressBar.h new file mode 100644 index 000000000..c4d0abcb5 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvProgressBar.h @@ -0,0 +1,68 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvProgressBar, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvProgressBar : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvProgressBar, add_progress_bar) + + MV_CREATE_CONSTANT(mvThemeCol_ProgressBar_Text , ImGuiCol_Text, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ProgressBar_Bar , ImGuiCol_PlotHistogram, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ProgressBar_Bg , ImGuiCol_FrameBg, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ProgressBar_Border , ImGuiCol_Border, 0L); + MV_CREATE_CONSTANT(mvThemeCol_ProgressBar_BorderShadow , ImGuiCol_BorderShadow, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_Rounding , ImGuiStyleVar_FrameRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_BorderSize , ImGuiStyleVar_FrameBorderSize , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_PaddingX , ImGuiStyleVar_FramePadding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_PaddingY , ImGuiStyleVar_FramePadding , 1L); + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_InnerItemSpacingX , ImGuiStyleVar_ItemInnerSpacing, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_ProgressBar_InnerItemSpacingY , ImGuiStyleVar_ItemInnerSpacing, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_ProgressBar_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_ProgressBar_Bar, mvColor(230, 179, 0, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_ProgressBar_Bg, mvColor( 41, 74, 122, 138)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_ProgressBar_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_ProgressBar_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_BorderSize, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_Rounding, 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_PaddingX, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_PaddingY, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_InnerItemSpacingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_ProgressBar_InnerItemSpacingY, 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvProgressBar(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::string m_overlay; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/misc/mvSameLine.cpp b/DearPyGui/src/core/AppItems/misc/mvSameLine.cpp new file mode 100644 index 000000000..908c65da5 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSameLine.cpp @@ -0,0 +1,52 @@ +#include "mvSameLine.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + void mvSameLine::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'sameline'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "xoffset", "offset from containing window", "0.0"}, + {mvPythonDataType::Float, "spacing", "offset from previous widget", "-1.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Places a widget on the same line as the previous widget. Can also be used for horizontal spacing.", + "None", "Adding Widgets") }); + } + + + mvSameLine::mvSameLine(const std::string& name) + : mvAppItem(name) + { + } + + void mvSameLine::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::SameLine(m_xoffset, m_spacing); + } + + void mvSameLine::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "xoffset")) m_xoffset = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "spacing")) m_spacing = ToFloat(item); + + } + + void mvSameLine::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "xoffset", ToPyFloat(m_xoffset)); + PyDict_SetItemString(dict, "spacing", ToPyFloat(m_spacing)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvSameLine.h b/DearPyGui/src/core/AppItems/misc/mvSameLine.h new file mode 100644 index 000000000..65c0d7455 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSameLine.h @@ -0,0 +1,43 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvSameLine, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvSameLine : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSameLine, add_same_line) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvSameLine(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_xoffset = 0.0f; + float m_spacing = -1.0f; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvSeparator.cpp b/DearPyGui/src/core/AppItems/misc/mvSeparator.cpp new file mode 100644 index 000000000..ea583cc59 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSeparator.cpp @@ -0,0 +1,33 @@ +#include "mvSeparator.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + void mvSeparator::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'separator'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a horizontal line.", "None", "Adding Widgets") }); + } + + + mvSeparator::mvSeparator(const std::string& name) + : mvAppItem(name) + { + } + + void mvSeparator::draw(ImDrawList* drawlist, float x, float y) + { + mvImGuiThemeScope scope(this); + + ImGui::Separator(); + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvSeparator.h b/DearPyGui/src/core/AppItems/misc/mvSeparator.h new file mode 100644 index 000000000..aec36edef --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSeparator.h @@ -0,0 +1,40 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvSeparator, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvSeparator : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSeparator, add_separator) + + MV_CREATE_CONSTANT(mvThemeCol_Separator, ImGuiCol_Separator, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Separator, mvColor(110, 110, 128, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvSeparator(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvSpacing.cpp b/DearPyGui/src/core/AppItems/misc/mvSpacing.cpp new file mode 100644 index 000000000..979c95eb1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSpacing.cpp @@ -0,0 +1,31 @@ +#include "mvSpacing.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + void mvSpacing::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'spacing'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "count", "", "1"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds vertical spacing.", "None", "Adding Widgets") }); + } + + + mvSpacing::mvSpacing(const std::string& name) + : mvIntPtrBase(name) + { + } + + void mvSpacing::draw(ImDrawList* drawlist, float x, float y) + { + for (int i = 0; i < *m_value; i++) + ImGui::Spacing(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvSpacing.h b/DearPyGui/src/core/AppItems/misc/mvSpacing.h new file mode 100644 index 000000000..ef7d89016 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvSpacing.h @@ -0,0 +1,35 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvSpacing, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Int, 1); + class mvSpacing : public mvIntPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSpacing, add_spacing) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvSpacing(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvUnindent.cpp b/DearPyGui/src/core/AppItems/misc/mvUnindent.cpp new file mode 100644 index 000000000..eab04c4e4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvUnindent.cpp @@ -0,0 +1,32 @@ +#include "mvUnindent.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" + +namespace Marvel { + + + void mvUnindent::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'unindent'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "offset", "", "0.0"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Unindents following items.", "None", "Adding Widgets") }); + } + + + mvUnindent::mvUnindent(const std::string& name) + : mvFloatPtrBase(name) + { + } + + void mvUnindent::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::Unindent(*m_value); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/misc/mvUnindent.h b/DearPyGui/src/core/AppItems/misc/mvUnindent.h new file mode 100644 index 000000000..eeb10b605 --- /dev/null +++ b/DearPyGui/src/core/AppItems/misc/mvUnindent.h @@ -0,0 +1,35 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvUnindent, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvUnindent : public mvFloatPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvUnindent, unindent) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvUnindent(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvAppItem.cpp b/DearPyGui/src/core/AppItems/mvAppItem.cpp new file mode 100644 index 000000000..b66957a4a --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvAppItem.cpp @@ -0,0 +1,1236 @@ +#include "mvAppItem.h" +#include "mvApp.h" +#include "mvInput.h" +#include "mvItemRegistry.h" +#include "mvCore.h" +#include "mvAppItemCommons.h" + +namespace Marvel{ + + void mvAppItem::InsertParser(std::map* parsers) + { + parsers->insert({ "get_item_callback_data", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns an item' callback data", "Any", "Widget Commands") }); + + parsers->insert({ "set_item_callback_data", mvPythonParser({ + {mvPythonDataType::String, "item"}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + }, "Sets an item's callback data if applicable.", "None", "Widget Commands") }); + + parsers->insert({ "get_item_type", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns an item's type", "str", "Widget Commands") }); + + parsers->insert({ "get_item_configuration", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns an items configuration", "dict", "Widget Commands") }); + + parsers->insert({ "configure_item", mvPythonParser({ + {mvPythonDataType::String, "item"}, + {mvPythonDataType::Kwargs, "**Kwargs"}, + }, "Configures an item", "None", "Widget Commands") }); + + parsers->insert({ "get_item_children[1]", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns a list of an item's children.", "List[str]", "Widget Commands") }); + + parsers->insert({ "get_item_callback", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns an item' callback", "Callable", "Widget Commands") }); + + parsers->insert({ "get_item_parent", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Returns an item's parent.", "str", "Widget Commands") }); + + parsers->insert({ "is_item_hovered", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is hovered.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_shown", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is shown.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_active", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is active.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_focused", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is focused.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_clicked", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is clicked.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_container", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is container.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_visible", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is visible on screen.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_edited", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item has been edited.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_activated", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item has been activated.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_deactivated", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item has been deactivated.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_deactivated_after_edit", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item has been deactivated after editing.", "bool", "Widget Commands") }); + + parsers->insert({ "is_item_toggled_open", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if an item is toggled.", "bool", "Widget Commands") }); + + parsers->insert({ "get_item_rect_min", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Returns an item's minimum allowable size. [width, height]", "[float, float]", "Widget Commands") }); + + parsers->insert({ "get_item_rect_max", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Returns an item's maximum allowable size. [width, height]", "[float, float]", "Widget Commands") }); + + parsers->insert({ "get_item_rect_size", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Returns an item's current size. [width, height]", "[float, float]", "Widget Commands") }); + + parsers->insert({ "get_value", mvPythonParser({ + {mvPythonDataType::String, "name"} + }, "Returns an item's value or None if there is none.", "Any", "Widget Commands") }); + + parsers->insert({ "set_value", mvPythonParser({ + {mvPythonDataType::String, "name"}, + {mvPythonDataType::Object, "value"} + }, "Sets an item's value if applicable.", "bool", "Widget Commands") }); + + parsers->insert({ "set_item_callback", mvPythonParser({ + {mvPythonDataType::String, "item"}, + {mvPythonDataType::Callable, "callback", "Registers a callback"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, + }, "Sets an item's callback if applicable.", "None", "Widget Commands") }); + + } + + bool mvAppItem::DoesItemHaveFlag(mvAppItem* item, int flag) + { + return item->getDescFlags() & flag; + } + + mvAppItem::mvAppItem(const std::string& name) + { + m_name = name; + m_label = name + " ###" + name; + m_specificedlabel = name; + m_state.setParent(this); + } + + void mvAppItem::registerWindowFocusing() + { + if (ImGui::IsWindowFocused()) + { + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y; + mvInput::setMousePosition(x, y); + + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != m_name) + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", m_name) }); + + } + } + + void mvAppItem::setCallback(mvCallable callback) + { + + if (callback == Py_None) + { + m_callback = nullptr; + return; + } + + m_callback = callback; + } + + void mvAppItem::setCallbackData(mvCallableData data) + { + if (data == Py_None) + { + m_callback_data = nullptr; + return; + } + m_callback_data = data; + } + + void mvAppItem::resetState() + { + m_state.reset(); + for (auto& childset : m_children) + { + for (auto& child : childset) + child->resetState(); + } + } + + bool mvAppItem::moveChildUp(const std::string& name) + { + bool found = false; + int index = 0; + + auto operation = [&](std::vector>& children) + { + // check children + for (size_t i = 0; i < children.size(); i++) + { + + if (children[i]->m_name == name) + { + found = true; + index = (int)i; + break; + } + + if (mvAppItem::DoesItemHaveFlag(children[i].get(), MV_ITEM_DESC_CONTAINER)) + { + found = children[i]->moveChildUp(name); + if (found) + return true; + } + + } + + if (found) + { + if (index > 0) + { + auto upperitem = children[index - 1]; + auto loweritem = children[index]; + + children[index] = upperitem; + children[index - 1] = loweritem; + } + + return true; + } + + return false; + }; + + for (auto& childset : m_children) + { + if (operation(childset)) + return true; + } + + return false; + + + } + + bool mvAppItem::moveChildDown(const std::string& name) + { + bool found = false; + size_t index = 0; + + auto operation = [&](std::vector>& children) + { + // check children + for (size_t i = 0; i < children.size(); i++) + { + + if (children[i]->m_name == name) + { + found = true; + index = i; + break; + } + + if (mvAppItem::DoesItemHaveFlag(children[i].get(), MV_ITEM_DESC_CONTAINER)) + { + found = children[i]->moveChildDown(name); + if (found) + return true; + } + + } + + if (found) + { + if (index < children.size() - 1) + { + auto upperitem = children[index]; + auto loweritem = children[index + 1]; + + children[index] = loweritem; + children[index + 1] = upperitem; + } + + return true; + } + + return false; + }; + + for (auto& childset : m_children) + { + if (operation(childset)) + return true; + } + + return false; + + } + + bool mvAppItem::addRuntimeChild(const std::string& parent, const std::string& before, mvRef item) + { + if (before.empty() && parent.empty()) + return false; + + + auto operation = [&](std::vector>& children) + { + //this is the container, add item to beginning. + if (before.empty()) + { + if (parent == m_name) + { + children.push_back(item); + onChildAdd(item); + item->m_parentPtr = this; + return true; + } + + else + { + // check children + for (auto& child : children) + { + if (mvAppItem::DoesItemHaveFlag(child.get(), MV_ITEM_DESC_CONTAINER)) + { + // parent found + if (child->addRuntimeChild(parent, before, item)) + return true; + } + } + } + } + + else + { + bool beforeFound = false; + + // check children + for (auto& child : children) + { + + if (child->m_name == before) + { + beforeFound = true; + break; + } + + } + + // after item is in this container + if (beforeFound) + { + item->m_parentPtr = this; + + std::vector> oldchildren = children; + children.clear(); + + for (auto child : oldchildren) + { + if (child->m_name == before) + { + children.push_back(item); + onChildAdd(item); + } + children.push_back(child); + + } + + return true; + } + } + + // check children + for (auto& child : children) + { + if (mvAppItem::DoesItemHaveFlag(child.get(), MV_ITEM_DESC_CONTAINER)) + { + // parent found + if (child->addRuntimeChild(parent, before, item)) + return true; + } + } + + return false; + }; + + return operation(m_children[item->getTarget()]); + } + + bool mvAppItem::addItem(mvRef item) + { + + m_children[item->getTarget()].push_back(item); + onChildAdd(item); + + return true; + } + + bool mvAppItem::addChildAfter(const std::string& prev, mvRef item) + { + if (prev.empty()) + return false; + + + auto operation = [&](std::vector>& children) + { + bool prevFound = false; + + // check children + for (auto& child : children) + { + + if (child->m_name == prev) + { + item->m_parentPtr = this; + prevFound = true; + break; + } + + } + + // prev item is in this container + if (prevFound) + { + //item->setParent(this); + + std::vector> oldchildren = children; + children.clear(); + + for (auto& child : oldchildren) + { + children.push_back(child); + if (child->m_name == prev) + { + children.push_back(item); + onChildAdd(item); + } + } + + return true; + } + + + // check children + for (auto& child : children) + { + if (DoesItemHaveFlag(child.get(), MV_ITEM_DESC_CONTAINER)) + { + // parent found + if (child->addChildAfter(prev, item)) + return true; + } + } + + return false; + }; + + return operation(m_children[item->getTarget()]); + } + + bool mvAppItem::deleteChild(const std::string& name) + { + + auto operation = [&](std::vector>& children) + { + bool childfound = false; + bool itemDeleted = false; + + for (auto& item : children) + { + if (item->m_name == name) + { + childfound = true; + break; + } + + if (DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER)) + { + itemDeleted = item->deleteChild(name); + if (itemDeleted) + break; + } + } + + if (childfound) + { + std::vector> oldchildren = children; + + children.clear(); + + for (auto& item : oldchildren) + { + if (item->m_name == name) + { + itemDeleted = true; + onChildRemoved(item); + continue; + } + + children.push_back(item); + } + } + + return itemDeleted; + }; + + for (auto& childset : m_children) + { + if (operation(childset)) + return true; + } + + return false; + } + + void mvAppItem::deleteChildren() + { + for (auto& childset : m_children) + childset.clear(); + onChildrenRemoved(); + } + + void mvAppItem::setLabel(const std::string& value) + { + m_specificedlabel = value; + m_label = value + " ###" + m_name; + } + + mvRef mvAppItem::stealChild(const std::string& name) + { + mvRef stolenChild = nullptr; + + auto operation = [&](std::vector>& children) + { + bool childfound = false; + + for (auto& item : children) + { + if (item->m_name == name) + { + childfound = true; + break; + } + + if (DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER)) + { + stolenChild = item->stealChild(name); + if (stolenChild) + return stolenChild; + } + } + + if (childfound) + { + std::vector> oldchildren = children; + + children.clear(); + + for (auto& item : oldchildren) + { + if (item->m_name == name) + { + stolenChild = item; + onChildRemoved(item); + continue; + } + + children.push_back(item); + } + } + + + }; + + + for (auto& childset : m_children) + { + if (operation(childset)) + return stolenChild; + } + + return stolenChild; + } + + mvRef mvAppItem::getChild(const std::string& name) + { + for (auto& childset : m_children) + { + for (auto& item : childset) + { + if (item->m_name == name) + return item; + + if (DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER)) + { + auto child = item->getChild(name); + if (child) + return child; + } + } + } + + return nullptr; + } + + mvAppItem::~mvAppItem() + { + deleteChildren(); + + mvGlobalIntepreterLock gil; + if (m_callback) + Py_DECREF(m_callback); + if (m_callback_data) + Py_DECREF(m_callback_data); + } + + mvCallable mvAppItem::getCallback(bool ignore_enabled) + { + if (m_enabled) + return m_callback; + + return ignore_enabled ? m_callback : nullptr; + + } + + bool mvAppItem::isThemeColorCacheValid() const + { + return !m_theme_color_dirty; + } + + bool mvAppItem::isThemeStyleCacheValid() const + { + return !m_theme_style_dirty; + } + + bool mvAppItem::isThemeFontCacheValid() const + { + return !m_theme_font_dirty; + } + + void mvAppItem::inValidateThemeColorCache() + { + m_theme_color_dirty = true; + m_cached_colors.clear(); + + for (auto& child : m_children[1]) + child->inValidateThemeColorCache(); + } + + void mvAppItem::inValidateThemeStyleCache() + { + m_theme_style_dirty = true; + m_cached_styles.clear(); + m_cached_styles2.clear(); + + for (auto& child : m_children[1]) + child->inValidateThemeStyleCache(); + } + + void mvAppItem::inValidateThemeFontCache() + { + m_theme_font_dirty = true; + m_cached_font = nullptr; + + for (auto& child : m_children[1]) + child->inValidateThemeFontCache(); + } + + void mvAppItem::setThemeColorCacheValid() + { + m_theme_color_dirty = false; + } + + void mvAppItem::setThemeStyleCacheValid() + { + m_theme_style_dirty = false; + } + + void mvAppItem::setThemeFontCacheValid() + { + m_theme_font_dirty = false; + } + + ImFont* mvAppItem::getCachedFont() + { + return m_cached_font; + } + + mvThemeColors& mvAppItem::getCachedThemeColors() + { + return m_cached_colors; + } + + std::unordered_map& mvAppItem::getCachedThemeStyles() + { + return m_cached_styles; + } + + std::unordered_map& mvAppItem::getCachedThemeStyles1() + { + return m_cached_styles1; + } + + std::unordered_map& mvAppItem::getCachedThemeStyles2() + { + return m_cached_styles2; + } + + void mvAppItem::checkConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + auto configKeys = ToStringVect(PyDict_Keys(dict)); + + static std::string base_keyword1 = "name"; + static std::string base_keyword2 = "label"; + static std::string base_keyword3 = "source"; + static std::string base_keyword4 = "tip"; + static std::string base_keyword5 = "show"; + static std::string base_keyword6 = "enabled"; + static std::string base_keyword7 = "width"; + static std::string base_keyword8 = "height"; + static std::string base_keyword9 = "callback"; + static std::string base_keyword10 = "callback_data"; + + std::string parserCommand; + + constexpr_for<1, (int)mvAppItemType::ItemTypeCount, 1>( + [&](auto i) { + using item_type = typename mvItemTypeMap::type; + mvAppItemType ait = mvItemTypeReverseMap::type; + if (getType() == ait) + { + parserCommand = item_type::s_command; + return; + } + }); + + const auto& parserKeywordsOrig = mvApp::GetApp()->getParsers()[parserCommand].getKeywords(); + std::vector parserKeywords; + parserKeywords.reserve(parserKeywordsOrig.size() + 10); + for (int i = 0; i < parserKeywordsOrig.size(); i++) + if(parserKeywordsOrig[i]) + parserKeywords.push_back(std::string(parserKeywordsOrig[i])); + + parserKeywords.push_back(base_keyword1); + parserKeywords.push_back(base_keyword2); + parserKeywords.push_back(base_keyword3); + parserKeywords.push_back(base_keyword4); + parserKeywords.push_back(base_keyword5); + parserKeywords.push_back(base_keyword6); + parserKeywords.push_back(base_keyword7); + parserKeywords.push_back(base_keyword8); + parserKeywords.push_back(base_keyword9); + parserKeywords.push_back(base_keyword10); + + for (const auto& key : configKeys) + { + size_t i = 0; + while (i < parserKeywords.size()) + { + if (key == parserKeywords[i]) + { + break; + } + i++; + } + if (i == parserKeywords.size()) + { + ThrowPythonException("\"" + key + "\" configuration does not exist in \"" + m_name + "\"."); + } + } + } + + void mvAppItem::setConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "name")) m_name = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "label")) setLabel(ToString(item)); + if (PyObject* item = PyDict_GetItemString(dict, "width")) setWidth(ToInt(item)); + if (PyObject* item = PyDict_GetItemString(dict, "height")) setHeight(ToInt(item)); + if (PyObject* item = PyDict_GetItemString(dict, "show")) m_show = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "source")) setDataSource(ToString(item)); + if (PyObject* item = PyDict_GetItemString(dict, "enabled")) setEnabled(ToBool(item)); + if (PyObject* item = PyDict_GetItemString(dict, "default_value")) setPyValue(item); + + if (PyObject* item = PyDict_GetItemString(dict, "callback")) + { + if (m_callback) + Py_XDECREF(m_callback); + + if (item) + Py_XINCREF(item); + setCallback(item); + } + + if (PyObject* item = PyDict_GetItemString(dict, "callback_data")) + { + if (m_callback_data) + Py_XDECREF(m_callback_data); + if (item) + Py_XINCREF(item); + setCallbackData(item); + } + + } + + std::pair mvAppItem::GetNameFromArgs(std::string& name, PyObject* args, PyObject* kwargs) + { + if (args) + { + if (PyTuple_GET_SIZE(args) > 0) + { + PyObject* pyname = nullptr; + pyname = PyTuple_GetItem(args, 0); + + name = ToString(pyname); + } + } + + std::string parent; + std::string before; + + if (kwargs) + { + if (PyObject* item = PyDict_GetItemString(kwargs, "parent")) parent = ToString(item); + if (PyObject* item = PyDict_GetItemString(kwargs, "before")) before = ToString(item); + } + + return std::make_pair(parent, before); + } + + void mvAppItem::getConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "name", ToPyString(m_name)); + PyDict_SetItemString(dict, "label", ToPyString(m_specificedlabel)); + PyDict_SetItemString(dict, "source", ToPyString(m_source)); + PyDict_SetItemString(dict, "show", ToPyBool(m_show)); + PyDict_SetItemString(dict, "enabled", ToPyBool(m_enabled)); + PyDict_SetItemString(dict, "width", ToPyInt(m_width)); + PyDict_SetItemString(dict, "height", ToPyInt(m_height)); + + if (m_callback) + { + Py_XINCREF(m_callback); + PyDict_SetItemString(dict, "callback", m_callback); + } + else + PyDict_SetItemString(dict, "callback", GetPyNone()); + + if (m_callback_data) + { + Py_XINCREF(m_callback_data); + PyDict_SetItemString(dict, "callback_data", m_callback_data); + } + else + PyDict_SetItemString(dict, "callback_data", GetPyNone()); + } + + PyObject* mvAppItem::get_item_configuration(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_configuration"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + + PyObject* pdict = PyDict_New(); + + if (std::string(item) == "logger##standard") + mvAppLog::GetConfigDict(pdict); + + if (appitem) + { + appitem->getConfigDict(pdict); + appitem->getExtraConfigDict(pdict); + } + else + ThrowPythonException(item + std::string(" item was not found")); + + return pdict; + } + + PyObject* mvAppItem::configure_item(PyObject* self, PyObject* args, PyObject* kwargs) + { + + std::string item = ToString(PyTuple_GetItem(args, 0)); + + if (std::string(item) == "logger##standard") + { + mvAppLog::SetConfigDict(kwargs); + return GetPyNone(); + } + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + + if (appitem) + { + appitem->checkConfigDict(kwargs); + appitem->setConfigDict(kwargs); + appitem->setExtraConfigDict(kwargs); + } + else + ThrowPythonException(item + std::string(" item was not found")); + + return GetPyNone(); + } + + PyObject* mvAppItem::get_item_children(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_children[1]"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto children = mvApp::GetApp()->getItemRegistry().getItemChildren(item); + + if (!children.empty()) + return ToPyList(children); + + return GetPyNone(); + } + + PyObject* mvAppItem::get_item_parent(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_parent"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + std::string parent = mvApp::GetApp()->getItemRegistry().getItemParentName(item); + + if (!parent.empty()) + return ToPyString(parent); + + return GetPyNone(); + } + + PyObject* mvAppItem::is_item_hovered(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_hovered"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemHovered()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_shown(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_shown"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->isShown()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_active(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_active"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemActive()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_focused(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_focused"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemFocused()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_clicked(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_clicked"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemClicked()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_container(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_container"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(DoesItemHaveFlag(appitem.get(), MV_ITEM_DESC_CONTAINER)); + return ToPyBool(false); + + } + + PyObject* mvAppItem::is_item_visible(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_visible"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemVisible()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_edited(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_edited"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemEdited()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_activated(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_activated"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemActivated()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_deactivated(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_deactivated"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemDeactivated()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_deactivated_after_edit(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_deactivated_after_edit"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + return ToPyBool(appitem->getState().isItemDeactivatedAfterEdit()); + return ToPyBool(false); + } + + PyObject* mvAppItem::is_item_toggled_open(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["is_item_toggled_open"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + + if (appitem) + return ToPyBool(appitem->getState().isItemToogledOpen()); + + + return ToPyBool(false); + } + + PyObject* mvAppItem::get_item_rect_min(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_rect_min"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + { + mvVec2 value = appitem->getState().getItemRectMin(); + return ToPyPair(value.x, value.y); + } + return ToPyPair(0.0f, 0.0f); + } + + PyObject* mvAppItem::get_item_rect_max(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_rect_max"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + if (appitem) + { + mvVec2 value = appitem->getState().getItemRectMax(); + return ToPyPair(value.x, value.y); + } + return ToPyPair(0.0f, 0.0f); + } + + PyObject* mvAppItem::get_item_rect_size(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + + if (!(mvApp::GetApp()->getParsers())["get_item_rect_size"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(item); + + if (appitem) + { + mvVec2 value = appitem->getState().getItemRectSize(); + return ToPyPair(value.x, value.y); + } + return ToPyPair(0.0f, 0.0f); + } + + PyObject* mvAppItem::get_value(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* name; + + if (!(mvApp::GetApp()->getParsers())["get_value"].parse(args, kwargs, __FUNCTION__, &name)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto item = mvApp::GetApp()->getItemRegistry().getItem(name); + if (item) + return item->getPyValue(); + + return GetPyNone(); + + } + + PyObject* mvAppItem::set_value(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* name; + PyObject* value; + + if (!(mvApp::GetApp()->getParsers())["set_value"].parse(args, kwargs, __FUNCTION__, &name, &value)) + return GetPyNone(); + + if (value) + Py_XINCREF(value); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + auto item = mvApp::GetApp()->getItemRegistry().getItem(name); + if (item) + item->setPyValue(value); + + Py_XDECREF(value); + + return GetPyNone(); + } + + PyObject* mvAppItem::get_item_type(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* name; + + if (!(mvApp::GetApp()->getParsers())["get_item_type"].parse(args, kwargs, __FUNCTION__, &name)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto appitem = mvApp::GetApp()->getItemRegistry().getItem(name); + + std::string parserCommand; + + constexpr_for<1, (int)mvAppItemType::ItemTypeCount, 1>( + [&](auto i) { + using item_type = typename mvItemTypeMap::type; + mvAppItemType ait = mvItemTypeReverseMap::type; + if (appitem->getType() == ait) + { + parserCommand = item_type::s_internal_id; + return; + } + }); + + return ToPyString(parserCommand); + } + +} diff --git a/DearPyGui/src/core/AppItems/mvAppItem.h b/DearPyGui/src/core/AppItems/mvAppItem.h new file mode 100644 index 000000000..aff82ad36 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvAppItem.h @@ -0,0 +1,356 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvAppItem +// +// - mvAppItem is the abstract base class for all DearPygui widgets. +// +//----------------------------------------------------------------------------- + +#include "mvPython.h" +#include +#include +#include +#include +#include "mvAppItemState.h" +#include "mvCallbackRegistry.h" + +// forward declarations +struct ImPlotTime; + +//----------------------------------------------------------------------------- +// Helper Macros +//----------------------------------------------------------------------------- +#include "cpp.hint" + +namespace Marvel { + + // forward declarations + class mvThemeManager; + + //----------------------------------------------------------------------------- + // mvAppItemType + //----------------------------------------------------------------------------- + enum class mvAppItemType + { + None = 0, mvSpacing, mvSameLine, mvInputText, mvButton, + mvRadioButton, mvTabBar, mvTab, mvImage, mvMenuBar, + mvMenu, mvMenuItem, mvGroup, mvChild, + mvSliderFloat, mvSliderInt, + mvDragFloat, mvDragInt, mvInputFloat, + mvInputInt, mvColorEdit3, mvColorEdit4, + mvColorPicker3, mvColorPicker4, mvTooltip, mvCollapsingHeader, + mvSeparator, mvCheckbox, mvListbox, mvText, mvLabelText, mvCombo, + mvPlot, mvSimplePlot, mvIndent, mvUnindent, mvDrawing, mvWindowAppItem, + mvPopup, mvSelectable, mvTreeNode, mvProgressBar, mvDataGrid, mvDummy, + mvImageButton, mvTimePicker, mvDatePicker, mvColorButton, + mvAboutWindow, mvDocWindow, mvDebugWindow, mvMetricsWindow, + mvStyleWindow, mvFileDialog, mvTabButton, mvLoggerItem, + mvNodeEditor, mvNode, mvNodeAttribute, + mvTable, mvTableColumn, mvTableNextColumn, + mvDrawLine, mvDrawArrow, mvDrawTriangle, mvDrawCircle, mvDrawBezierCurve, + mvDrawQuad, mvDrawRect, mvDrawText, mvDrawPolygon, mvDrawPolyline, + mvDrawImage, mvDragFloatMulti, mvDragIntMulti, mvSliderFloatMulti, + mvSliderIntMulti, mvInputIntMulti, mvInputFloatMulti, + mvDragPoint, mvDragLine, mvAnnotation, mvLineSeries, + mvScatterSeries, mvStemSeries, mvStairSeries, mvBarSeries, + mvErrorSeries, mvVLineSeries, mvHLineSeries, mvHeatSeries, + mvImageSeries, mvPieSeries, mvShadeSeries, mvLabelSeries, + mvCandleSeries, mvAreaSeries, mvColorMapScale, + ItemTypeCount + }; + + enum class StorageValueTypes + { + None = 0, + Int, Int4, + Float, Float4, FloatVect, + Series, + Bool, + String, + Time, Color + }; + + enum ItemDescriptionFlags + { + MV_ITEM_DESC_DEFAULT = 0, + MV_ITEM_DESC_ROOT = 1 << 1, + MV_ITEM_DESC_CONTAINER = 1 << 2, + MV_ITEM_DESC_AFTER = 1 << 3, + }; + + using mvValueVariant = std::variant< + std::shared_ptr, + std::shared_ptr>, + std::shared_ptr, + std::shared_ptr>, + std::shared_ptr>, + std::shared_ptr>>, + std::shared_ptr, + std::shared_ptr, + std::shared_ptr, + std::shared_ptr, + void*>; + + template + struct mvItemTypeMap {}; + + template + struct mvItemTypeReverseMap{}; + + //----------------------------------------------------------------------------- + // mvAppItem + //----------------------------------------------------------------------------- + class mvAppItem + { + + friend class mvApp; + friend class mvItemRegistry; + friend class mvAppItemState; + friend class mvDebugWindow; + + // items that need access to other items + friend class mvMenuItem; + friend class mvCollapsingHeader; + friend class mvChild; + friend class mvGroup; + friend class mvTabBar; + friend class mvTab; + friend class mvMenuBar; + friend class mvMenu; + friend class mvWindow; + friend class mvTooltip; + friend class mvPopup; + friend class mvTreeNode; + friend class mvWindowAppItem; + friend class mvTable; + friend class mvNodeEditor; + friend class mvNode; + friend class mvNodeAttribute; + friend class mvFontManager; + friend class mvFontScope; + friend class mvDrawing; + friend class mvPlot; + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(get_item_configuration); + MV_CREATE_EXTRA_COMMAND(configure_item); + MV_CREATE_EXTRA_COMMAND(get_item_type); + MV_CREATE_EXTRA_COMMAND(get_value); + MV_CREATE_EXTRA_COMMAND(set_value); + MV_CREATE_EXTRA_COMMAND(is_item_hovered); + MV_CREATE_EXTRA_COMMAND(is_item_shown); + MV_CREATE_EXTRA_COMMAND(is_item_active); + MV_CREATE_EXTRA_COMMAND(is_item_focused); + MV_CREATE_EXTRA_COMMAND(is_item_clicked); + MV_CREATE_EXTRA_COMMAND(is_item_container); + MV_CREATE_EXTRA_COMMAND(is_item_visible); + MV_CREATE_EXTRA_COMMAND(is_item_edited); + MV_CREATE_EXTRA_COMMAND(is_item_activated); + MV_CREATE_EXTRA_COMMAND(is_item_deactivated); + MV_CREATE_EXTRA_COMMAND(is_item_deactivated_after_edit); + MV_CREATE_EXTRA_COMMAND(is_item_toggled_open); + MV_CREATE_EXTRA_COMMAND(get_item_rect_min); + MV_CREATE_EXTRA_COMMAND(get_item_rect_max); + MV_CREATE_EXTRA_COMMAND(get_item_rect_size); + MV_CREATE_EXTRA_COMMAND(get_item_parent); + MV_CREATE_EXTRA_COMMAND(get_item_children); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(get_item_configuration); + MV_ADD_EXTRA_COMMAND(configure_item); + MV_ADD_EXTRA_COMMAND(get_item_type); + MV_ADD_EXTRA_COMMAND(get_value); + MV_ADD_EXTRA_COMMAND(set_value); + MV_ADD_EXTRA_COMMAND(is_item_hovered); + MV_ADD_EXTRA_COMMAND(is_item_shown); + MV_ADD_EXTRA_COMMAND(is_item_active); + MV_ADD_EXTRA_COMMAND(is_item_focused); + MV_ADD_EXTRA_COMMAND(is_item_clicked); + MV_ADD_EXTRA_COMMAND(is_item_container); + MV_ADD_EXTRA_COMMAND(is_item_visible); + MV_ADD_EXTRA_COMMAND(is_item_edited); + MV_ADD_EXTRA_COMMAND(is_item_activated); + MV_ADD_EXTRA_COMMAND(is_item_deactivated); + MV_ADD_EXTRA_COMMAND(is_item_deactivated_after_edit); + MV_ADD_EXTRA_COMMAND(is_item_toggled_open); + MV_ADD_EXTRA_COMMAND(get_item_rect_min); + MV_ADD_EXTRA_COMMAND(get_item_rect_max); + MV_ADD_EXTRA_COMMAND(get_item_rect_size); + MV_ADD_EXTRA_COMMAND(get_item_parent); + MV_ADD_EXTRA_COMMAND(get_item_children); + MV_END_EXTRA_COMMANDS + + static bool DoesItemHaveFlag(mvAppItem* item, int flag); + static std::pair GetNameFromArgs(std::string& name, PyObject* args, PyObject* kwargs); + + protected: + + struct ScopedID + { + ScopedID() { ImGui::PushID(this); } + ScopedID(void* id) { ImGui::PushID(id); } + ~ScopedID() { ImGui::PopID(); } + }; + + public: + + mvAppItem(const std::string& name); + mvAppItem(const mvAppItem& other) = delete; // copy constructor + mvAppItem(mvAppItem&& other) = delete; // move constructor + + virtual ~mvAppItem(); + + //----------------------------------------------------------------------------- + // These methods are overridden through the use of: + // - MV_REGISTER_WIDGET + // - MV_APPLY_WIDGET_REGISTRATION + //----------------------------------------------------------------------------- + [[nodiscard]] virtual mvAppItemType getType () const = 0; + [[nodiscard]] virtual int getDescFlags () const = 0; + [[nodiscard]] virtual int getTarget () const = 0; // which child slot + [[nodiscard]] virtual StorageValueTypes getValueType () const = 0; + + // actual immediate mode drawing instructions + virtual void draw(ImDrawList* drawlist, float x, float y) = 0; + + //----------------------------------------------------------------------------- + // These methods handle setting the widget's value using PyObject*'s or + // returning the actual value. These are mostly overridden by the + // mvTypeBase classes + //----------------------------------------------------------------------------- + virtual mvValueVariant getValue() { return nullptr; } + virtual PyObject* getPyValue() { return GetPyNone(); } + virtual void setPyValue(PyObject* value) { } + + //----------------------------------------------------------------------------- + // These methods handle are used by the item registry: + // - isParentCompatible -> will the parent accept the current item + // - canChildBeAdded -> will the current item accept the incoming child + //----------------------------------------------------------------------------- + virtual bool isParentCompatible(mvAppItemType type) { return true; } + virtual bool canChildBeAdded (mvAppItemType type) { return true; } + + + void checkConfigDict(PyObject* dict); + void setConfigDict(PyObject* dict); // python dictionary acts as an out parameter + void getConfigDict(PyObject* dict); + virtual void setConfigArgs(PyObject* args) {} + virtual void setExtraConfigDict(PyObject* dict) {} + virtual void getExtraConfigDict(PyObject* dict) {} + + //----------------------------------------------------------------------------- + // These methods can be optionally overridden if your widget needs to be + // notified when children are added/removed (i.e. tables, node editor) + //----------------------------------------------------------------------------- + virtual void onChildAdd (mvRef item) {} + virtual void onChildRemoved(mvRef item) {} + virtual void onChildrenRemoved() {} + + void setCallback (mvCallable callback); + void hide () { m_show = false; } + void show () { m_show = true; } + void setCallbackData(mvCallableData data); + + [[nodiscard]] bool isShown () const { return m_show; } + [[nodiscard]] mvCallable getCallback (bool ignore_enabled = true); // returns the callback. If ignore_enable false and item is disabled then no callback will be returned. + [[nodiscard]] mvCallableData getCallbackData() { return m_callback_data; } + mvAppItemState& getState () { return m_state; } + mvAppItem* getParent() { return m_parentPtr; } + bool isEnabled() const { return m_enabled; } + + // theme get/set + std::unordered_map& getColors() { return m_colors; } + std::unordered_map& getStyles() { return m_styles; } + + // cached theming + bool isThemeColorCacheValid() const; + bool isThemeStyleCacheValid() const; + bool isThemeFontCacheValid() const; + void inValidateThemeColorCache(); + void inValidateThemeStyleCache(); + void inValidateThemeFontCache(); + void setThemeColorCacheValid(); + void setThemeStyleCacheValid(); + void setThemeFontCacheValid(); + void setFont(ImFont* font) { m_cached_font = font; } + ImFont* getCachedFont(); + mvThemeColors& getCachedThemeColors(); + std::unordered_map& getCachedThemeStyles(); + std::unordered_map& getCachedThemeStyles1(); + std::unordered_map& getCachedThemeStyles2(); + + protected: + + virtual void setWidth (int width) { m_width = width; } + virtual void setHeight (int height) { m_height = height; } + virtual void setEnabled (bool value) { m_enabled = value; } + virtual void setDataSource (const std::string& value){ m_source = value; } + virtual void setLabel (const std::string& value); + + private: + + mvRef getChild(const std::string& name); // will return nullptr if not found + + // runtime modifications + bool addItem(mvRef item); + bool addRuntimeChild(const std::string& parent, const std::string& before, mvRef item); + bool addChildAfter(const std::string& prev, mvRef item); + bool deleteChild(const std::string& name); + void deleteChildren(); + bool moveChildUp(const std::string& name); + bool moveChildDown(const std::string& name); + void resetState(); + void registerWindowFocusing(); // only useful for imgui window types + mvRef stealChild(const std::string& name); // steals a child (used for moving) + + + protected: + + mvAppItemState m_state; + + mvAppItem* m_parentPtr = nullptr; + std::vector> m_children[2] = { {}, {} }; + + std::string m_label; // internal label + + std::unordered_map m_colors; + std::unordered_map m_styles; + + // cached theming + bool m_theme_color_dirty = true; + bool m_theme_style_dirty = true; + bool m_theme_font_dirty = false; + mvThemeColors m_cached_colors; + std::unordered_map m_cached_styles; + std::unordered_map m_cached_styles1; + std::unordered_map m_cached_styles2; + + // fonts + ImFont* m_cached_font = nullptr; + + // config + std::string m_name = ""; + std::string m_source = ""; + std::string m_specificedlabel = "__DearPyGuiDefault"; + std::string m_parent = ""; + std::string m_before = ""; + int m_width = 0; + int m_height = 0; + int m_windowPosx = 0; + int m_windowPosy = 0; + int m_posx = 0; + int m_posy = 0; + bool m_show = true; + bool m_enabled = true; + mvCallable m_callback = nullptr; + mvCallableData m_callback_data = nullptr; + + }; + + inline void DecodeType(long encoded_constant, mvAppItemType* type) { *type = (mvAppItemType)(encoded_constant / 1000); } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvAppItemCommons.h b/DearPyGui/src/core/AppItems/mvAppItemCommons.h new file mode 100644 index 000000000..f8d2edb9b --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvAppItemCommons.h @@ -0,0 +1,98 @@ +#pragma once + +#include "basic/mvInputText.h" +#include "basic/mvRadioButton.h" +#include "basic/mvListbox.h" +#include "basic/mvCheckbox.h" +#include "basic/mvButton.h" +#include "basic/mvSelectable.h" +#include "basic/mvCombo.h" +#include "basic/mvInputSingle.h" +#include "basic/mvInputMulti.h" +#include "basic/mvSliderMulti.h" +#include "basic/mvSliderSingle.h" +#include "basic/mvDragSingle.h" +#include "basic/mvDragMulti.h" +#include "basic/mvColorButton.h" +#include "basic/mvColorEdit.h" +#include "basic/mvColorPicker.h" +#include "basic/mvText.h" +#include "basic/mvTabButton.h" +#include "basic/mvMenuItem.h" +#include "basic/mvImage.h" +#include "basic/mvImageButton.h" + +#include "misc/mvProgressBar.h" +#include "misc/mvDummy.h" +#include "misc/mvIndent.h" +#include "misc/mvUnindent.h" +#include "misc/mvSameLine.h" +#include "misc/mvSpacing.h" +#include "misc/mvSeparator.h" + +#include "containers/mvTreeNode.h" +#include "containers/mvChild.h" +#include "containers/mvGroup.h" +#include "containers/mvCollapsingHeader.h" +#include "containers/mvTab.h" +#include "containers/mvTabBar.h" +#include "containers/mvMenu.h" +#include "containers/mvMenuBar.h" +#include "containers/mvTooltip.h" +#include "containers/mvWindowAppItem.h" +#include "containers/mvPopup.h" + +#include "tables/mvTable.h" +#include "tables/mvTableColumn.h" +#include "tables/mvTableNextColumn.h" + +#include "drawing/mvDrawing.h" +#include "drawing/mvDrawLine.h" +#include "drawing/mvDrawArrow.h" +#include "drawing/mvDrawTriangle.h" +#include "drawing/mvDrawCircle.h" +#include "drawing/mvDrawBezierCurve.h" +#include "drawing/mvDrawQuad.h" +#include "drawing/mvDrawRect.h" +#include "drawing/mvDrawText.h" +#include "drawing/mvDrawPolygon.h" +#include "drawing/mvDrawPolyline.h" +#include "drawing/mvDrawImage.h" + +#include "custom/mvTimePicker.h" +#include "custom/mvDatePicker.h" +#include "custom/mvColorMapScale.h" + +#include "composite/mvDataGrid.h" +#include "composite/mvLogger.h" +#include "composite/mvAboutWindow.h" +#include "composite/mvDocWindow.h" +#include "composite/mvDebugWindow.h" +#include "composite/mvMetricsWindow.h" +#include "composite/mvStyleWindow.h" +#include "composite/mvFileDialog.h" + +#include "plots/mvPlot.h" +#include "plots/mvDragPoint.h" +#include "plots/mvDragLine.h" +#include "plots/mvAnnotation.h" + +#include "plots/mvSimplePlot.h" +#include "plots/mvLineSeries.h" +#include "plots/mvBarSeries.h" +#include "plots/mvScatterSeries.h" +#include "plots/mvAreaSeries.h" +#include "plots/mvStemSeries.h" +#include "plots/mvLabelSeries.h" +#include "plots/mvPieSeries.h" +#include "plots/mvShadeSeries.h" +#include "plots/mvErrorSeries.h" +#include "plots/mvHeatSeries.h" +#include "plots/mvImageSeries.h" +#include "plots/mvStairSeries.h" +#include "plots/mvCandleSeries.h" +#include "plots/mvInfiniteLineSeries.h" + +#include "nodes/mvNodeEditor.h" +#include "nodes/mvNode.h" +#include "nodes/mvNodeAttribute.h" \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvAppItemState.cpp b/DearPyGui/src/core/AppItems/mvAppItemState.cpp new file mode 100644 index 000000000..db0634c20 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvAppItemState.cpp @@ -0,0 +1,39 @@ +#include "mvAppItemState.h" +#include +#include "mvAppItem.h" + +namespace Marvel { + + void mvAppItemState::reset() + { + m_hovered = false; + m_active = false; + m_focused = false; + m_clicked = false; + m_visible = false; + m_edited = false; + m_activated = false; + m_deactivated = false; + m_deactivatedAfterEdit = false; + m_toggledOpen = false; + } + + void mvAppItemState::update() + { + m_hovered = ImGui::IsItemHovered(); + m_active = ImGui::IsItemActive(); + m_focused = ImGui::IsItemFocused(); + m_clicked = ImGui::IsItemClicked(); + m_visible = ImGui::IsItemVisible(); + m_edited = ImGui::IsItemEdited(); + m_activated = ImGui::IsItemActivated(); + m_deactivated = ImGui::IsItemDeactivated(); + m_deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit(); + m_toggledOpen = ImGui::IsItemToggledOpen(); + m_rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y }; + m_rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y }; + m_rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y }; + + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvAppItemState.h b/DearPyGui/src/core/AppItems/mvAppItemState.h new file mode 100644 index 000000000..fec350e71 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvAppItemState.h @@ -0,0 +1,67 @@ +#pragma once + +#include "mvCore.h" + +namespace Marvel { + + // forward declarations + class mvAppItem; + + class mvAppItemState + { + + public: + + void reset(); + void update(); + + // getters + [[nodiscard]] bool isItemHovered () const { return m_hovered; } + [[nodiscard]] bool isItemActive () const { return m_active; } + [[nodiscard]] bool isItemFocused () const { return m_focused; } + [[nodiscard]] bool isItemClicked () const { return m_clicked; } + [[nodiscard]] bool isItemVisible () const { return m_visible; } + [[nodiscard]] bool isItemEdited () const { return m_edited; } + [[nodiscard]] bool isItemActivated () const { return m_activated; } + [[nodiscard]] bool isItemDeactivated () const { return m_deactivated; } + [[nodiscard]] bool isItemDeactivatedAfterEdit() const { return m_deactivatedAfterEdit; } + [[nodiscard]] bool isItemToogledOpen () const { return m_toggledOpen; } + [[nodiscard]] mvVec2 getItemRectMin () const { return m_rectMin; } + [[nodiscard]] mvVec2 getItemRectMax () const { return m_rectMax; } + [[nodiscard]] mvVec2 getItemRectSize () const { return m_rectSize; } + + // setters + void setHovered (bool value) { m_hovered = value; } + void setActive (bool value) { m_active = value; } + void setFocused (bool value) { m_focused = value; } + void setClicked (bool value) { m_clicked = value; } + void setVisible (bool value) { m_visible = value; } + void setEdited (bool value) { m_edited = value; } + void setActivated (bool value) { m_activated = value; } + void setDeactivated (bool value) { m_deactivated = value; } + void setDeactivatedAfterEdit(bool value) { m_deactivatedAfterEdit = value; } + void setToggledOpen (bool value) { m_toggledOpen = value; } + void setRectMin (mvVec2 value) { m_rectMin = value; } + void setRectMax (mvVec2 value) { m_rectMax = value; } + void setRectSize (mvVec2 value) { m_rectSize = value; } + void setParent (mvAppItem* parent) { m_parent = parent; }; + + private: + + bool m_hovered = false; + bool m_active = false; + bool m_focused = false; + bool m_clicked = false; + bool m_visible = false; + bool m_edited = false; + bool m_activated = false; + bool m_deactivated = false; + bool m_deactivatedAfterEdit = false; + bool m_toggledOpen = false; + mvVec2 m_rectMin = { 0.0f, 0.0f }; + mvVec2 m_rectMax = { 0.0f, 0.0f }; + mvVec2 m_rectSize = { 0.0f, 0.0f }; + mvAppItem* m_parent = nullptr; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvItemRegistry.cpp b/DearPyGui/src/core/AppItems/mvItemRegistry.cpp new file mode 100644 index 000000000..3bbbc6684 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvItemRegistry.cpp @@ -0,0 +1,804 @@ +#include "mvItemRegistry.h" +#include "mvProfiler.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvAppItemCommons.h" +#include "mvLog.h" + +namespace Marvel { + + void mvItemRegistry::InsertParser(std::map* parsers) + { + + parsers->insert({ "move_item", mvPythonParser({ + {mvPythonDataType::String, "item"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "parent", "", "''"}, + {mvPythonDataType::String, "before", "", "''"} + }, "Moves an existing item.", "None", "Widget Commands") }); + + parsers->insert({ "get_windows", mvPythonParser({ + }, "Returns a list of windows.", "List[str]", "Widget Commands") }); + + parsers->insert({ "get_all_items", mvPythonParser({ + }, "Returns a list of all items.", "List[str]", "Widget Commands") }); + + parsers->insert({ "delete_item", mvPythonParser({ + {mvPythonDataType::String, "item"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "children_only", "delete children only", "False"} + }, "Deletes an item if it exists.", "None", "Widget Commands") }); + + parsers->insert({ "does_item_exist", mvPythonParser({ + {mvPythonDataType::String, "item"}, + }, "Checks if item exists.", "bool", "Widget Commands") }); + + parsers->insert({ "move_item_up", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Moves item up if possible and if it exists.", "None", "Widget Commands") }); + + parsers->insert({ "move_item_down", mvPythonParser({ + {mvPythonDataType::String, "item"} + }, "Moves item down if possible and if it exists.", "None", "Widget Commands") }); + + parsers->insert({ "get_active_window", mvPythonParser({ + }, "Returns the active window name.", "str") }); + + parsers->insert({ "set_primary_window", mvPythonParser({ + {mvPythonDataType::String, "window"}, + {mvPythonDataType::Bool, "value"}, + }, "Sets the primary window to fill the viewport.") }); + + } + + mvItemRegistry::mvItemRegistry() + { + mvEventBus::Subscribe(this, 0, mvEVT_CATEGORY_ITEM); + mvEventBus::Subscribe(this, mvEVT_PRE_RENDER_RESET); + mvEventBus::Subscribe(this, mvEVT_RENDER); + mvEventBus::Subscribe(this, mvEVT_ACTIVE_WINDOW); + + auto add_hidden_window = [&](mvRef item, const std::string& label) { + m_backWindows.push_back(item); + m_backWindows.back()->setLabel(label); + m_backWindows.back()->hide(); + }; + + add_hidden_window(CreateRef("documentation##standard"), "Core Documentation"); + add_hidden_window(CreateRef("debug##standard"), "Dear PyGui Debug"); + add_hidden_window(CreateRef("about##standard"), "About Dear PyGui"); + add_hidden_window(CreateRef("metrics##standard"), "Metrics"); + add_hidden_window(CreateRef("style##standard"), "Dear PyGui Style Editor"); + add_hidden_window(CreateRef(), "FileDialog"); + + } + + mvValueVariant mvItemRegistry::getValue(const std::string& name) + { + mvRef item = getItem(name); + if (item) + return item->getValue(); + return nullptr; + } + + bool mvItemRegistry::deleteItem(const std::string& name, bool childrenOnly) + { + + MV_ITEM_REGISTRY_TRACE("Attempting to delete: " + name); + + // delete item's children only + if(childrenOnly) + { + auto item = getItem(name); + if (item) + { + item->deleteChildren(); + MV_ITEM_REGISTRY_INFO("Item found and it's children deleted."); + return true; + } + } + + bool deletedItem = false; + + // try to delete build-in item + for (auto window : m_frontWindows) + { + deletedItem = window->deleteChild(name); + if (deletedItem) + break; + } + + // try to delete user added item + if (!deletedItem) + { + for (auto window : m_backWindows) + { + deletedItem = window->deleteChild(name); + if (deletedItem) + break; + } + } + + bool frontWindowDeleting = false; + bool backWindowDeleting = false; + + // check if attempting to delete a window + for (auto window : m_frontWindows) + { + if (window->m_name == name) + { + frontWindowDeleting = true; + break; + } + } + + for (auto window : m_backWindows) + { + if (window->m_name == name) + { + backWindowDeleting = true; + break; + } + } + + // delete window and update window vector + // this should be changed to a different data + // structure + if (frontWindowDeleting) + { + std::vector> oldwindows = m_frontWindows; + + m_frontWindows.clear(); + + for (auto window : oldwindows) + { + if (window->m_name == name) + { + deletedItem = true; + continue; + } + m_frontWindows.push_back(window); + } + } + + if (backWindowDeleting) + { + std::vector> oldwindows = m_backWindows; + + m_backWindows.clear(); + + for (auto window : oldwindows) + { + if (window->m_name == name) + { + deletedItem = true; + continue; + } + m_backWindows.push_back(window); + } + } + + if (deletedItem) + { + MV_ITEM_REGISTRY_INFO(name + " found and deleted."); + } + else + mvThrowPythonError(1001, name + " not deleted because it was not found"); + + assert(deletedItem && "Item to delete not found"); + return deletedItem; + } + + bool mvItemRegistry::moveItem(const std::string& name, const std::string& parent, const std::string& before) + { + + MV_ITEM_REGISTRY_TRACE("Attempting to move: " + name); + + mvRef child = nullptr; + + bool movedItem = false; + + for (auto window : m_frontWindows) + { + child = window->stealChild(name); + if (child) + break; + } + + if (child == nullptr) + { + mvThrowPythonError(1000, name + " not moved because it was not found"); + MV_ITEM_REGISTRY_WARN("Could not move item, it was not found"); + } + + if (child) + addRuntimeItem(parent, before, child); + + assert(movedItem && "Item to move not found"); + + return movedItem; + } + + bool mvItemRegistry::moveItemUp(const std::string& name) + { + + MV_ITEM_REGISTRY_TRACE("Attempting to move: " + name); + + bool movedItem = false; + + for (auto window : m_frontWindows) + { + movedItem = window->moveChildUp(name); + if (movedItem) + break; + } + + if (!movedItem) + { + mvThrowPythonError(1000, name + " not moved because it was not found"); + MV_ITEM_REGISTRY_WARN("Could not move item, it was not found"); + } + + assert(movedItem && "Item to move not found"); + + return movedItem; + } + + bool mvItemRegistry::moveItemDown(const std::string& name) + { + + MV_ITEM_REGISTRY_TRACE("Attempting to move: " + name); + + bool movedItem = false; + + for (auto window : m_frontWindows) + { + movedItem = window->moveChildDown(name); + if (movedItem) + break; + } + + if (!movedItem) + { + mvThrowPythonError(1000, name + " not moved because it was not found"); + MV_ITEM_REGISTRY_WARN("Could not move item, it was not found"); + } + + assert(movedItem && "Item to move not found"); + + return movedItem; + } + + bool mvItemRegistry::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + + dispatcher.dispatch(BIND_EVENT_METH(mvItemRegistry::onPreRenderReset), mvEVT_PRE_RENDER_RESET); + dispatcher.dispatch(BIND_EVENT_METH(mvItemRegistry::onRender), mvEVT_RENDER); + dispatcher.dispatch(BIND_EVENT_METH(mvItemRegistry::onActiveWindow), mvEVT_ACTIVE_WINDOW); + + return event.handled; + } + + bool mvItemRegistry::onRender(mvEvent& event) + { + + MV_PROFILE_FUNCTION(); + + // resets app items states (i.e. hovered) + for (auto window : m_frontWindows) + window->draw(nullptr, 0.0f, 0.0f); + for (auto window : m_backWindows) + window->draw(nullptr, 0.0f, 0.0f); + + return false; + } + + bool mvItemRegistry::onPreRenderReset(mvEvent& event) + { + + MV_PROFILE_FUNCTION(); + + // resets app items states (i.e. hovered) + for (auto window : m_frontWindows) + window->resetState(); + for (auto window : m_backWindows) + window->resetState(); + + return false; + } + + bool mvItemRegistry::onActiveWindow(mvEvent& event) + { + + m_activeWindow = GetEString(event, "WINDOW"); + + MV_ITEM_REGISTRY_INFO("Active window changed to: " + m_activeWindow); + + return false; + } + + bool mvItemRegistry::addRuntimeItem(const std::string& parent, const std::string& before, mvRef item) + { + MV_ITEM_REGISTRY_TRACE("Attempting to add new widget: ", item->m_name); + + // add runtime items + bool addedItem = false; + + for (auto window : m_frontWindows) + { + addedItem = window->addRuntimeChild(parent, before, item); + if (addedItem) + break; + } + + assert(addedItem); + return addedItem; + } + + bool mvItemRegistry::addItemAfter(const std::string& prev, mvRef item) + { + MV_ITEM_REGISTRY_TRACE("Attempting to add new widget after: ", item->m_name); + + bool addedItem = false; + + for (auto& window : m_frontWindows) + { + addedItem = window->addChildAfter(prev, item); + if (addedItem) + break; + } + + assert(addedItem); + return addedItem; + } + + void mvItemRegistry::pushParent(mvRef item) + { + m_parents.push(item); + } + + mvRef mvItemRegistry::popParent() + { + if (m_parents.empty()) + { + mvThrowPythonError(1000, "No parent to pop."); + MV_ITEM_REGISTRY_WARN("No parent to pop."); + assert(false); + return nullptr; + } + + auto item = m_parents.top(); + m_parents.pop(); + return item; + } + + void mvItemRegistry::emptyParents() + { + while (!m_parents.empty()) + m_parents.pop(); + + MV_ITEM_REGISTRY_INFO("Parent stack emptied."); + } + + mvRef mvItemRegistry::topParent() + { + if (!m_parents.empty()) + return m_parents.top(); + return nullptr; + } + + mvRef mvItemRegistry::getItem(const std::string& name) + { + mvRef item = nullptr; + + for (auto window : m_frontWindows) + { + if (window->m_name == name) + return window; + + auto child = window->getChild(name); + if (child) + return child; + } + + for (auto window : m_backWindows) + { + if (window->m_name == name) + return window; + + auto child = window->getChild(name); + if (child) + return child; + } + + //assert(false && "Item not found."); + + return nullptr; + } + + mvWindowAppItem* mvItemRegistry::getWindow(const std::string& name) + { + + mvRef item = getItem(name); + if (item == nullptr) + { + assert(false && "Window not found."); + return nullptr; + } + + if (item->getType() == mvAppItemType::mvWindowAppItem) + return static_cast(item.get()); + + assert(false && "Item is not a window not found."); + return nullptr; + } + + bool mvItemRegistry::addItem(mvRef item) + { + + MV_ITEM_REGISTRY_TRACE("Adding item: " + item->m_name); + + mvRef parentitem = topParent(); + item->m_parentPtr = parentitem.get(); + parentitem->addItem(item); + + return true; + } + + bool mvItemRegistry::addWindow(mvRef item) + { + MV_ITEM_REGISTRY_INFO("Adding window: " + item->m_name); + m_frontWindows.push_back(item); + return true; + } + + void mvItemRegistry::clearRegistry() + { + MV_ITEM_REGISTRY_INFO("Clearing item registry."); + m_frontWindows.clear(); + m_backWindows.clear(); + } + + bool mvItemRegistry::addItemWithRuntimeChecks(mvRef item, const char* parent, const char* before) + { + MV_ITEM_REGISTRY_TRACE("Adding runtime item: " + item->m_name); + + if (item == nullptr) + return false; + + //--------------------------------------------------------------------------- + // STEP 0: check if an item with this name exists + //--------------------------------------------------------------------------- + if (getItem(item->m_name)) + { + mvThrowPythonError(1000, "Item must have a unique name."); + MV_ITEM_REGISTRY_WARN("Item must have a unique name."); + //assert(false); + return false; + } + + enum class AddTechnique + { + NONE, BEFORE, PARENT, STACK + }; + AddTechnique technique = AddTechnique::NONE; + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + //--------------------------------------------------------------------------- + // STEP 1: empty parent stack if mistakes were made + //--------------------------------------------------------------------------- + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_ROOT) && topParent() != nullptr) + { + mvThrowPythonError(1000, "Parent stack not empty."); + emptyParents(); + MV_ITEM_REGISTRY_ERROR("Parent stack not empty when adding " + item->m_name); + assert(false); + } + + //--------------------------------------------------------------------------- + // STEP 2: handle window case + //--------------------------------------------------------------------------- + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_ROOT)) + { + if (mvApp::IsAppStarted()) + { + m_frontWindows.push_back(item); + return true; + } + return addWindow(item); + } + + //--------------------------------------------------------------------------- + // STEP 3: attempt to deduce parent + //--------------------------------------------------------------------------- + mvRef parentPtr = nullptr; + if (!std::string(before).empty()) + { + parentPtr = getItem(before); + technique = AddTechnique::BEFORE; + } + + else if (!std::string(parent).empty()) + { + parentPtr = getItem(parent); + technique = AddTechnique::PARENT; + } + + else + { + parentPtr = topParent(); + technique = AddTechnique::STACK; + } + + //--------------------------------------------------------------------------- + // STEP 4: check if parent was deduced + //--------------------------------------------------------------------------- + if (parentPtr == nullptr) + { + mvThrowPythonError(1000, "Parent could not be deduced."); + MV_ITEM_REGISTRY_ERROR("Parent could not be deduced."); + assert(false); + return false; + } + + //--------------------------------------------------------------------------- + // STEP 5: check if parent is a compatible type + //--------------------------------------------------------------------------- + if (!item->isParentCompatible(parentPtr->getType())) + return false; + + //--------------------------------------------------------------------------- + // STEP 6: check if parent accepts our item (this isn't duplicate STEP 3 ha) + //--------------------------------------------------------------------------- + if (!parentPtr->canChildBeAdded(item->getType())) + return false; + + //--------------------------------------------------------------------------- + // STEP 7: add items who require "after" adding (i.e. popup, tooltip) + //--------------------------------------------------------------------------- + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_AFTER)) + return addItemAfter(parent, item); + + //--------------------------------------------------------------------------- + // STEP 8: handle "before" and "after" style adding + //--------------------------------------------------------------------------- + if (technique == AddTechnique::BEFORE || technique == AddTechnique::PARENT) + return addRuntimeItem(parent, before, item); // same for run/compile time + + //--------------------------------------------------------------------------- + // STEP 9: handle "stack" style adding + //--------------------------------------------------------------------------- + if(mvApp::IsAppStarted()) + return addRuntimeItem(parentPtr->m_name, "", item); + return addItem(item); + } + + std::string mvItemRegistry::getItemParentName(const std::string& name) + { + mvRef item = getItem(name); + if (item) + return item->m_parentPtr->m_name; + + mvThrowPythonError(1000, name + ": item not found"); + assert(false && "Item not found."); + + return ""; + } + + std::vector mvItemRegistry::getItemChildren(const std::string& name) + { + + mvRef item = getItem(name); + + std::vector childList; + + if (item) + { + auto children0 = item->m_children[0]; + auto children1 = item->m_children[1]; + for (auto child : children0) + childList.emplace_back(child->m_name); + for (auto child : children1) + childList.emplace_back(child->m_name); + } + else + { + mvThrowPythonError(1000, name + ": item not found"); + assert(false && "Item not found."); + } + + return childList; + } + + std::vector mvItemRegistry::getAllItems() + { + + std::vector childList; + + // to help recursively retrieve children + std::function)> ChildRetriever; + ChildRetriever = [&childList, &ChildRetriever](mvRef item) { + auto children0 = item->m_children[0]; + auto children1 = item->m_children[1]; + for (auto child : children0) + { + childList.emplace_back(child->m_name); + if (mvAppItem::DoesItemHaveFlag(child.get(), MV_ITEM_DESC_CONTAINER)) + ChildRetriever(child); + } + for (auto child : children1) + { + childList.emplace_back(child->m_name); + if (mvAppItem::DoesItemHaveFlag(child.get(), MV_ITEM_DESC_CONTAINER)) + ChildRetriever(child); + } + + }; + + for (auto window : m_frontWindows) + { + childList.emplace_back(window->m_name); + ChildRetriever(window); + } + for (auto window : m_backWindows) + { + childList.emplace_back(window->m_name); + ChildRetriever(window); + } + + return childList; + } + + std::vector mvItemRegistry::getWindows() + { + + std::vector childList; + for (auto window : m_frontWindows) + childList.emplace_back(window->m_name); + + for (auto window : m_backWindows) + childList.emplace_back(window->m_name); + + return childList; + } + + void mvItemRegistry::setPrimaryWindow(const std::string& name, bool value) + { + + mvWindowAppItem* window = getWindow(name); + + if (window) + { + if (window->getWindowAsMainStatus() == value) + return; + else + window->setWindowAsMainStatus(value); + } + else + { + mvThrowPythonError(1000, "Window does not exists."); + assert(false); + } + + // reset other windows + for (auto window : m_frontWindows) + { + if (window->m_name != name) + static_cast(window.get())->setWindowAsMainStatus(false); + } + + mvAppLog::Focus(); + } + + PyObject* mvItemRegistry::set_primary_window(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* item; + int value; + + if (!(mvApp::GetApp()->getParsers())["set_primary_window"].parse(args, kwargs, __FUNCTION__, &item, &value)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().setPrimaryWindow(item, value); + + return GetPyNone(); + } + + PyObject* mvItemRegistry::get_active_window(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + return ToPyString(mvApp::GetApp()->getItemRegistry().getActiveWindow()); + } + + PyObject* mvItemRegistry::move_item(PyObject* self, PyObject* args, PyObject* kwargs) + { + + const char* item; + const char* parent = ""; + const char* before = ""; + + if (!(mvApp::GetApp()->getParsers())["move_item"].parse(args, kwargs, __FUNCTION__, + &item, &parent, &before)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().moveItem(item, parent, before); + + return GetPyNone(); + } + + PyObject* mvItemRegistry::delete_item(PyObject* self, PyObject* args, PyObject* kwargs) + { + + const char* item; + int childrenOnly = false; + + if (!(mvApp::GetApp()->getParsers())["delete_item"].parse(args, kwargs, __FUNCTION__, &item, &childrenOnly)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().deleteItem(item, childrenOnly); + + return GetPyNone(); + + } + + PyObject* mvItemRegistry::does_item_exist(PyObject* self, PyObject* args, PyObject* kwargs) + { + + const char* item; + + if (!(mvApp::GetApp()->getParsers())["does_item_exist"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + if (mvApp::GetApp()->getItemRegistry().getItem(item)) + return ToPyBool(true); + return ToPyBool(false); + } + + PyObject* mvItemRegistry::move_item_up(PyObject* self, PyObject* args, PyObject* kwargs) + { + + const char* item; + + if (!(mvApp::GetApp()->getParsers())["move_item_up"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().moveItemUp(item); + + return GetPyNone(); + + } + + PyObject* mvItemRegistry::move_item_down(PyObject* self, PyObject* args, PyObject* kwargs) + { + + const char* item; + + if (!(mvApp::GetApp()->getParsers())["move_item_down"].parse(args, kwargs, __FUNCTION__, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().moveItemDown(item); + + return GetPyNone(); + } + + PyObject* mvItemRegistry::get_all_items(PyObject* self, PyObject* args, PyObject* kwargs) + { + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + return ToPyList(mvApp::GetApp()->getItemRegistry().getAllItems()); + } + + PyObject* mvItemRegistry::get_windows(PyObject* self, PyObject* args, PyObject* kwargs) + { + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + return ToPyList(mvApp::GetApp()->getItemRegistry().getWindows()); + } +} diff --git a/DearPyGui/src/core/AppItems/mvItemRegistry.h b/DearPyGui/src/core/AppItems/mvItemRegistry.h new file mode 100644 index 000000000..6b583ea1a --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvItemRegistry.h @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "mvEvents.h" +#include "mvApp.h" +#include "mvAppItem.h" +#include "mvPythonParser.h" +#include "cpp.hint" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // Forward Declarations + //----------------------------------------------------------------------------- + class mvAppItem; + class mvWindowAppItem; + + //----------------------------------------------------------------------------- + // mvItemRegistry + // - Responsibilities: + // * holds widget hierarchy roots (windows) + // * keeping up with the active window + // * managing the parent deduction system (parent stack) + // * acts as the interface for accessing widgets + // * creates the "standard" windows on startup (debug, about, etc.) + //----------------------------------------------------------------------------- + class mvItemRegistry : public mvEventHandler + { + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(move_item); + MV_CREATE_EXTRA_COMMAND(delete_item); + MV_CREATE_EXTRA_COMMAND(does_item_exist); + MV_CREATE_EXTRA_COMMAND(move_item_down); + MV_CREATE_EXTRA_COMMAND(move_item_up); + MV_CREATE_EXTRA_COMMAND(get_windows); + MV_CREATE_EXTRA_COMMAND(get_all_items); + MV_CREATE_EXTRA_COMMAND(get_active_window); + MV_CREATE_EXTRA_COMMAND(set_primary_window); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(move_item); + MV_ADD_EXTRA_COMMAND(delete_item); + MV_ADD_EXTRA_COMMAND(does_item_exist); + MV_ADD_EXTRA_COMMAND(move_item_down); + MV_ADD_EXTRA_COMMAND(move_item_up); + MV_ADD_EXTRA_COMMAND(get_windows); + MV_ADD_EXTRA_COMMAND(get_all_items); + MV_ADD_EXTRA_COMMAND(get_active_window); + MV_ADD_EXTRA_COMMAND(set_primary_window); + MV_END_EXTRA_COMMANDS + + public: + + mvItemRegistry(); + + //----------------------------------------------------------------------------- + // Event Handling + //----------------------------------------------------------------------------- + bool onEvent (mvEvent& event) override; + bool onRender (mvEvent& event); + bool onPreRenderReset(mvEvent& event); + bool onActiveWindow (mvEvent& event); + + //----------------------------------------------------------------------------- + // Widget Operations + //----------------------------------------------------------------------------- + bool deleteItem (const std::string& name, bool childrenOnly = false); + bool moveItem (const std::string& name, const std::string& parent, const std::string& before); + bool moveItemUp (const std::string& name); + bool moveItemDown (const std::string& name); + void clearRegistry (); + mvValueVariant getValue (const std::string& name); + mvRef getItem (const std::string& name); + mvWindowAppItem* getWindow (const std::string& name); + std::vector>& getFrontWindows () { return m_frontWindows; } + std::vector>& getBackWindows () { return m_backWindows; } + const std::string& getActiveWindow () const { return m_activeWindow; } + bool addItemWithRuntimeChecks(mvRef item, const char* parent, const char* before); + + // called by python interface + std::vector getAllItems (); + std::vector getWindows (); + std::vector getItemChildren (const std::string& name); + std::string getItemParentName (const std::string& name); + void setPrimaryWindow (const std::string& name, bool value); + + //----------------------------------------------------------------------------- + // Parent stack operations + // - used for automatic parent deduction + //----------------------------------------------------------------------------- + void pushParent (mvRef item); // pushes parent onto stack + void emptyParents(); // empties parent stack + mvRef popParent (); // pop parent off stack and return it + mvRef topParent (); // returns top parent without popping + + private: + + bool addItem (mvRef item); + bool addItemAfter (const std::string& prev, mvRef item); // for popups/tooltips + bool addWindow (mvRef item); + bool addRuntimeItem(const std::string& parent, const std::string& before, mvRef item); + + + private: + + std::stack> m_parents; // parent stack, top of stack becomes widget's parent + std::vector> m_frontWindows; // user added windows + std::vector> m_backWindows; // default "standard" windows (debug, style editor, etc.) + std::string m_activeWindow; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvTypeBases.cpp b/DearPyGui/src/core/AppItems/mvTypeBases.cpp new file mode 100644 index 000000000..e7f533537 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvTypeBases.cpp @@ -0,0 +1,549 @@ +#include "mvTypeBases.h" +#include +#include "mvApp.h" +#include "mvLog.h" +#include "mvUtilities.h" +#include "mvAppLog.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + mvIntPtrBase::mvIntPtrBase(const std::string& name) + : + mvAppItem(name) + { + } + + void mvIntPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>(item->getValue()); + } + + PyObject* mvIntPtrBase::getPyValue() + { + return ToPyInt(*m_value); + } + + void mvIntPtrBase::setPyValue(PyObject* value) + { + *m_value = ToInt(value); + } + + mvInt4PtrBase::mvInt4PtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvInt4PtrBase::getPyValue() + { + return ToPyIntList(m_value->data(), 4); + } + + void mvInt4PtrBase::setPyValue(PyObject* value) + { + std::vector temp = ToIntVect(value); + while (temp.size() < 4) + temp.push_back(0); + std::array temp_array; + for (int i = 0; i < temp_array.size(); i++) + temp_array[i] = temp[i]; + if (m_value) + *m_value = temp_array; + else + m_value = std::make_shared>(temp_array); + } + + void mvInt4PtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>>(item->getValue()); + } + + mvFloatPtrBase::mvFloatPtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvFloatPtrBase::getPyValue() + { + return ToPyFloat(*m_value); + } + + void mvFloatPtrBase::setPyValue(PyObject* value) + { + *m_value = ToFloat(value); + } + + void mvFloatPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>(item->getValue()); + } + + mvFloat4PtrBase::mvFloat4PtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvFloat4PtrBase::getPyValue() + { + return ToPyFloatList(m_value->data(), 4); + } + + void mvFloat4PtrBase::setPyValue(PyObject* value) + { + std::vector temp = ToFloatVect(value); + while (temp.size() < 4) + temp.push_back(0.0f); + std::array temp_array; + for (int i = 0; i < temp_array.size(); i++) + temp_array[i] = temp[i]; + if (m_value) + *m_value = temp_array; + else + m_value = std::make_shared>(temp_array); + } + + void mvFloat4PtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>>(item->getValue()); + } + + mvColorPtrBase::mvColorPtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvColorPtrBase::getPyValue() + { + mvColor color = { + m_value->data()[0], + m_value->data()[1], + m_value->data()[2], + m_value->data()[3] + }; + return ToPyColor(color); + } + + void mvColorPtrBase::setPyValue(PyObject* value) + { + std::vector temp = ToFloatVect(value); + while (temp.size() < 4) + temp.push_back(0.0f); + std::array temp_array; + for (int i = 0; i < temp_array.size(); i++) + temp_array[i] = temp[i]; + if (m_value) + *m_value = temp_array; + else + m_value = std::make_shared>(temp_array); + } + + void mvColorPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>>(item->getValue()); + } + + mvBoolPtrBase::mvBoolPtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvBoolPtrBase::getPyValue() + { + return ToPyBool(*m_value); + } + + void mvBoolPtrBase::setPyValue(PyObject* value) + { + *m_value = ToBool(value); + } + + void mvBoolPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>(item->getValue()); + } + + mvStringPtrBase::mvStringPtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvStringPtrBase::getPyValue() + { + return ToPyString(*m_value); + } + + void mvStringPtrBase::setPyValue(PyObject* value) + { + *m_value = ToString(value); + } + + void mvStringPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>(item->getValue()); + } + + mvTimePtrBase::mvTimePtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvTimePtrBase::getPyValue() + { + return ToPyTime(*m_value); + } + + void mvTimePtrBase::setPyValue(PyObject* value) + { + + if (m_value) + *m_value = ToTime(value); + else + m_value = {}; + + ImPlot::GetGmtTime(*m_imvalue, m_value.get()); + } + + mvFloatVectPtrBase::mvFloatVectPtrBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvFloatVectPtrBase::getPyValue() + { + return ToPyList(*m_value); + } + + void mvFloatVectPtrBase::setPyValue(PyObject* value) + { + *m_value = ToFloatVect(value); + } + + void mvFloatVectPtrBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>>(item->getValue()); + } + + mvSeriesBase::mvSeriesBase(const std::string& name) + : mvAppItem(name) + { + } + + PyObject* mvSeriesBase::getPyValue() + { + return ToPyList(*m_value); + } + + void mvSeriesBase::setPyValue(PyObject* value) + { + *m_value = ToVectVectFloat(value); + resetMaxMins(); + calculateMaxMins(); + } + + void mvSeriesBase::setDataSource(const std::string& dataSource) + { + if (dataSource == m_source) return; + m_source = dataSource; + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(dataSource); + if (!item) + { + ThrowPythonException("Source item not found."); + return; + } + if (item->getValueType() != getValueType()) + { + ThrowPythonException("Values types do not match"); + return; + } + m_value = std::get>>>(item->getValue()); + resetMaxMins(); + calculateMaxMins(); + } + + const std::pair& mvSeriesBase::getMaxMin(int i) const + { + assert(i < m_maxMins.size()); + + return m_maxMins[i]; + } + + void mvSeriesBase::calculateMaxMins() + { + + static const std::vector* xptr; + + for (auto& data : (*m_value.get())) + { + xptr = &data; + if (xptr->empty()) + { + m_maxMins.emplace_back(0.0f, 0.0f); + continue; + } + float maxValue = (*xptr)[0]; + float minValue = (*xptr)[0]; + + for (const auto& x : (*xptr)) + { + if (x > maxValue) maxValue = x; + if (x < minValue) minValue = x; + } + + m_maxMins.emplace_back(maxValue, minValue); + } + } + + void mvSeriesBase::resetMaxMins() + { + m_maxMins.clear(); + } + + bool mvSeriesBase::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvPlot) + return true; + + mvThrowPythonError(1000, "Item's parent must be plot."); + MV_ITEM_REGISTRY_ERROR("Item's parent must be plot."); + assert(false); + return false; + } + + mvBaseWindowAppitem::mvBaseWindowAppitem(const std::string& name) + : + mvAppItem(name) + { + } + + void mvBaseWindowAppitem::addFlag(ImGuiWindowFlags flag) + { + m_windowflags |= flag; + } + + void mvBaseWindowAppitem::removeFlag(ImGuiWindowFlags flag) + { + m_windowflags &= ~flag; + } + + void mvBaseWindowAppitem::setWindowPos(float x, float y) + { + m_xpos = (int)x; + m_ypos = (int)y; + m_dirty_pos = true; + } + + void mvBaseWindowAppitem::setWidth(int width) + { + m_width = width; + m_dirty_size = true; + } + + void mvBaseWindowAppitem::setHeight(int height) + { + m_height = height; + m_dirty_size = true; + } + + mvVec2 mvBaseWindowAppitem::getWindowPos() const + { + return { (float)m_xpos, (float)m_ypos }; + } + + bool mvBaseWindowAppitem::prerender() + { + + if (!m_show) + return false; + + if (m_dirty_size) + { + ImGui::SetNextWindowSize(ImVec2((float)m_width, (float)m_height)); + m_dirty_size = false; + } + + if (m_dirty_pos) + { + ImGui::SetNextWindowPos(ImVec2((float)m_xpos, (float)m_ypos)); + m_dirty_pos = false; + } + + if (!ImGui::Begin(m_label.c_str(), &m_show, m_windowflags)) + { + ImGui::End(); + return false; + } + + return true; + } + + void mvBaseWindowAppitem::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "x_pos")) setWindowPos((float)ToInt(item), (float)m_ypos); + if (PyObject* item = PyDict_GetItemString(dict, "y_pos")) setWindowPos((float)m_xpos, (float)ToInt(item)); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // window flags + flagop("autosize", ImGuiWindowFlags_AlwaysAutoResize, m_windowflags); + flagop("no_move", ImGuiWindowFlags_NoMove, m_windowflags); + flagop("no_resize", ImGuiWindowFlags_NoResize, m_windowflags); + flagop("no_title_bar", ImGuiWindowFlags_NoTitleBar, m_windowflags); + flagop("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + flagop("no_collapse", ImGuiWindowFlags_NoCollapse, m_windowflags); + flagop("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + flagop("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, m_windowflags); + flagop("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, m_windowflags); + flagop("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + flagop("no_background", ImGuiWindowFlags_NoBackground, m_windowflags); + + } + + void mvBaseWindowAppitem::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "x_pos", ToPyInt(m_xpos)); + PyDict_SetItemString(dict, "y_pos", ToPyInt(m_ypos)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // window flags + checkbitset("autosize", ImGuiWindowFlags_AlwaysAutoResize, m_windowflags); + checkbitset("no_resize", ImGuiWindowFlags_NoResize, m_windowflags); + checkbitset("no_title_bar", ImGuiWindowFlags_NoTitleBar, m_windowflags); + checkbitset("no_move", ImGuiWindowFlags_NoMove, m_windowflags); + checkbitset("no_scrollbar", ImGuiWindowFlags_NoScrollbar, m_windowflags); + checkbitset("no_collapse", ImGuiWindowFlags_NoCollapse, m_windowflags); + checkbitset("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, m_windowflags); + checkbitset("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, m_windowflags); + checkbitset("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, m_windowflags); + checkbitset("menubar", ImGuiWindowFlags_MenuBar, m_windowflags); + checkbitset("no_background", ImGuiWindowFlags_NoBackground, m_windowflags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/mvTypeBases.h b/DearPyGui/src/core/AppItems/mvTypeBases.h new file mode 100644 index 000000000..44de400a1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/mvTypeBases.h @@ -0,0 +1,265 @@ +#pragma once + +#include "mvAppItem.h" +#include +#include +#include +#include "mvItemRegistry.h" + +//----------------------------------------------------------------------------- +// mvTypeBases +// +// - This file contains abstract classes for concrete mvAppItem +// implementations which share common underlying data types. +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvIntPtrBase + //----------------------------------------------------------------------------- + class mvIntPtrBase : public mvAppItem + { + + public: + + mvIntPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef m_value = CreateRef(0); + int m_disabled_value = 0; + }; + + //----------------------------------------------------------------------------- + // mvInt4PtrBase + //----------------------------------------------------------------------------- + class mvInt4PtrBase : public mvAppItem + { + + public: + + mvInt4PtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef> m_value = CreateRef>(std::array{0, 0, 0, 0}); + int m_disabled_value[4] {}; + }; + + //----------------------------------------------------------------------------- + // mvFloatPtrBase + //----------------------------------------------------------------------------- + class mvFloatPtrBase : public mvAppItem + { + + public: + + mvFloatPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef m_value = CreateRef(0.0f); + float m_disabled_value = 0.0; + }; + + //----------------------------------------------------------------------------- + // mvFloat4PtrBase + //----------------------------------------------------------------------------- + class mvFloat4PtrBase : public mvAppItem + { + + public: + + mvFloat4PtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef> m_value = CreateRef>(std::array{0.0f, 0.0f, 0.0f, 0.0f}); + float m_disabled_value[4] {}; + }; + + //----------------------------------------------------------------------------- + // mvColorPtrBase + //----------------------------------------------------------------------------- + class mvColorPtrBase : public mvAppItem + { + + public: + + mvColorPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef> m_value = CreateRef>(std::array{0.0f, 0.0f, 0.0f, -1.0f}); + float m_disabled_value[4]{}; + }; + + //----------------------------------------------------------------------------- + // mvBoolPtrBase + //----------------------------------------------------------------------------- + class mvBoolPtrBase : public mvAppItem + { + + public: + + mvBoolPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef m_value = CreateRef(false); + bool m_disabled_value = false; + }; + + //----------------------------------------------------------------------------- + // mvStringPtrBase + //----------------------------------------------------------------------------- + class mvStringPtrBase : public mvAppItem + { + + public: + + mvStringPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef m_value = CreateRef(""); + std::string m_disabled_value = ""; + }; + + //----------------------------------------------------------------------------- + // mvTimePtrBase + //----------------------------------------------------------------------------- + class mvTimePtrBase : public mvAppItem + { + + public: + + mvTimePtrBase(const std::string& name); + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef m_value = {}; + mvRef m_imvalue = {}; + }; + + //----------------------------------------------------------------------------- + // mvFloatVectPtrBase + //----------------------------------------------------------------------------- + class mvFloatVectPtrBase : public mvAppItem + { + + public: + + mvFloatVectPtrBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + + protected: + + mvRef> m_value = CreateRef>(std::vector{0.0f}); + }; + + //----------------------------------------------------------------------------- + // mvSeriesBase + //----------------------------------------------------------------------------- + class mvSeriesBase : public mvAppItem + { + + public: + + mvSeriesBase(const std::string& name); + void setDataSource(const std::string& dataSource) override; + mvValueVariant getValue() override { return m_value; } + PyObject* getPyValue() override; + void setPyValue(PyObject* value) override; + bool isParentCompatible(mvAppItemType type) override; + + const std::pair& getMaxMin(int i) const; + bool doesSeriesContributeToBounds() const { return m_contributeToBounds; } + + protected: + + void calculateMaxMins(); + void resetMaxMins(); + + protected: + + mvRef>> m_value = CreateRef>>( + std::vector>{ std::vector{}, + std::vector{}, + std::vector{}, + std::vector{}, + std::vector{} }); + std::vector> m_maxMins; + bool m_contributeToBounds = false; + ImPlotYAxis_ m_axis = ImPlotYAxis_1; + }; + + //----------------------------------------------------------------------------- + // mvBaseWindowAppitem + //----------------------------------------------------------------------------- + class mvBaseWindowAppitem : public mvAppItem + { + + public: + + + mvBaseWindowAppitem(const std::string& name); + + void addFlag (ImGuiWindowFlags flag); + void removeFlag (ImGuiWindowFlags flag); + void setWindowPos(float x, float y); + bool prerender (); + mvVec2 getWindowPos() const; + + void setWidth (int width) override; + void setHeight (int height) override; + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + protected: + + ImGuiWindowFlags m_windowflags = ImGuiWindowFlags_NoSavedSettings; + int m_xpos = 200; + int m_ypos = 200; + bool m_dirty_pos = true; + bool m_dirty_size = true; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/nodes/mvNode.cpp b/DearPyGui/src/core/AppItems/nodes/mvNode.cpp new file mode 100644 index 000000000..46654ddba --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNode.cpp @@ -0,0 +1,162 @@ +#include "mvNode.h" +#include +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImNodesThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + static std::string FindRenderedTextEnd(const char* text, const char* text_end = nullptr) + { + int size = 0; + + const char* text_display_end = text; + if (!text_end) + text_end = (const char*)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + { + text_display_end++; + size++; + } + + char* cvalue = new char[size + 1]; + for (int i = 0; i < size; i++) + cvalue[i] = text[i]; + + cvalue[size] = '\0'; + + auto result = std::string(cvalue); + delete[] cvalue; + + return result; + } + + void mvNode::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "draggable", "Allow node to be draggable.", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "x_pos", "x position the node will start at", "100"}, + {mvPythonDataType::Integer, "y_pos", "y position the node will start at", "100"}, + }, "Adds a node to a node editor.", + "None", "Containers") }); + } + + mvNode::mvNode(const std::string& name) + : mvAppItem(name) + { + m_label = FindRenderedTextEnd(m_name.c_str()); + m_specificedlabel = m_label; + int64_t address = (int64_t)this; + int64_t reduced_address = address % 2147483648; + m_id = (int)reduced_address; + } + + bool mvNode::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvNodeEditor) + return true; + + mvThrowPythonError(1000, "Node parent must be node editor."); + MV_ITEM_REGISTRY_ERROR("Node parent must be node editor."); + assert(false); + return false; + } + + bool mvNode::canChildBeAdded(mvAppItemType type) + { + if(type == mvAppItemType::mvNodeAttribute) + return true; + + mvThrowPythonError(1000, "Node children must be node attributes only."); + MV_ITEM_REGISTRY_ERROR("Node children must be node attributes only."); + assert(false); + + return false; + } + + void mvNode::setNodePos(float x, float y) + { + m_xpos = (int)x; + m_ypos = (int)y; + m_dirty_pos = true; + } + + void mvNode::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImNodesThemeScope scope(this); + mvFontScope fscope(this); + + if (m_dirty_pos) + { + imnodes::SetNodeGridSpacePos((int)m_id, ImVec2(m_xpos, m_ypos)); + m_dirty_pos = false; + } + + imnodes::SetNodeDraggable((int)m_id, m_draggable); + + imnodes::BeginNode(m_id); + + imnodes::BeginNodeTitleBar(); + ImGui::TextUnformatted(m_label.c_str()); + imnodes::EndNodeTitleBar(); + + //we do this so that the children dont get the theme + scope.cleanup(); + + for (auto item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, x, y); + + auto& state = item->getState(); + state.setActive(imnodes::IsAttributeActive()); + + } + + imnodes::EndNode(); + + ImVec2 pos = imnodes::GetNodeGridSpacePos((int)m_id); + m_xpos = pos.x; + m_ypos = pos.y; + } + + void mvNode::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "x_pos")) setNodePos((float)ToInt(item), (float)m_ypos); + if (PyObject* item = PyDict_GetItemString(dict, "y_pos")) setNodePos((float)m_xpos, (float)ToInt(item)); + if (PyObject* item = PyDict_GetItemString(dict, "draggable")) m_draggable = ToBool(item); + + } + + void mvNode::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "x_pos", ToPyInt(m_xpos)); + PyDict_SetItemString(dict, "y_pos", ToPyInt(m_ypos)); + PyDict_SetItemString(dict, "draggable", ToPyBool(m_draggable)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/nodes/mvNode.h b/DearPyGui/src/core/AppItems/nodes/mvNode.h new file mode 100644 index 000000000..16613f589 --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNode.h @@ -0,0 +1,82 @@ +#pragma once +#include "mvAppItem.h" +#include "mvItemRegistry.h" +#include +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvNode, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvNode : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + friend class mvNodeEditor; + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvNode, add_node) + + MV_CREATE_CONSTANT(mvThemeCol_Node_Background , imnodes::ColorStyle::ColorStyle_NodeBackground , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_BackgroundHovered , imnodes::ColorStyle::ColorStyle_NodeBackgroundHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_BackgroundSelected , imnodes::ColorStyle::ColorStyle_NodeBackgroundSelected, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_Outline , imnodes::ColorStyle::ColorStyle_NodeOutline , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_TitleBar , imnodes::ColorStyle::ColorStyle_TitleBar , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_TitleBarHovered , imnodes::ColorStyle::ColorStyle_TitleBarHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Node_TitleBarSelected , imnodes::ColorStyle::ColorStyle_TitleBarSelected , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Node_CornerRounding , imnodes::StyleVar::StyleVar_NodeCornerRounding , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Node_PaddingHorizontal , imnodes::StyleVar::StyleVar_NodePaddingHorizontal , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Node_PaddingVertical , imnodes::StyleVar::StyleVar_NodePaddingVertical , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Node_BorderThickness , imnodes::StyleVar::StyleVar_NodeBorderThickness , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_Background, mvColor( 50, 50, 50, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_BackgroundHovered, mvColor( 75, 75, 75, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_BackgroundSelected, mvColor( 75, 75, 75, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_Outline, mvColor(100, 100, 100, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_TitleBar, mvColor( 41, 74, 122, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_TitleBarHovered, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Node_TitleBarSelected, mvColor( 66, 150, 250, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Node_CornerRounding, 5, 20), + MV_ADD_CONSTANT(mvThemeStyle_Node_PaddingHorizontal, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Node_PaddingVertical, 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_Node_BorderThickness, 1, 20), + + MV_END_STYLE_CONSTANTS + + public: + + mvNode(const std::string& name); + + void setNodePos(float x, float y); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + bool canChildBeAdded(mvAppItemType type) override; + + int getId() const {return m_id;} + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_id = 0; + bool m_dirty_pos = true; + int m_xpos = 100; + int m_ypos = 100; + bool m_draggable = true; + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.cpp b/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.cpp new file mode 100644 index 000000000..0740c4784 --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.cpp @@ -0,0 +1,123 @@ +#include "mvNodeAttribute.h" +#include +#include "mvApp.h" +#include "mvCore.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvNodeEditor.h" +#include "mvImNodesThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvNodeAttribute::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "shape", "Pin shape", "1"}, + {mvPythonDataType::Bool, "output", "Set as output attribute", "False"}, + {mvPythonDataType::Bool, "static", "Set as static attribute", "False"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + }, "Adds a node attribute.", + "None", "Containers") }); + } + + mvNodeAttribute::mvNodeAttribute(const std::string& name) + : mvAppItem(name) + { + int64_t address = (int64_t)this; + int64_t reduced_address = address % 2147483648; + m_id = (int)reduced_address; + } + + mvNodeAttribute::~mvNodeAttribute() + { + if (!m_delete) + { + if (m_parentPtr) + if (m_parentPtr->m_parentPtr) + static_cast(m_parentPtr->m_parentPtr)->deleteLink(m_name, m_id, true); + } + } + + bool mvNodeAttribute::isParentCompatible(mvAppItemType type) + { + if(type == mvAppItemType::mvNode) + return true; + + mvThrowPythonError(1000, "Node attribute parent must be node."); + MV_ITEM_REGISTRY_ERROR("Node attribute parent must be node."); + assert(false); + return false; + } + + void mvNodeAttribute::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImNodesThemeScope scope(this); + mvFontScope fscope(this); + + if (m_static) + imnodes::BeginStaticAttribute((int)m_id); + else if(m_output) + imnodes::BeginOutputAttribute((int)m_id, m_shape); + else + imnodes::BeginInputAttribute((int)m_id, m_shape); + + //we do this so that the children dont get the theme + //scope.cleanup(); + + for (auto item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, x, y); + + item->getState().update(); + } + + if (m_static) + imnodes::EndStaticAttribute(); + else if (m_output) + imnodes::EndOutputAttribute(); + else + imnodes::EndInputAttribute(); + } + + void mvNodeAttribute::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "output")) m_output = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "static")) m_static = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "shape")) m_shape = (imnodes::PinShape)ToInt(item); + + if (PyObject* item = PyDict_GetItemString(dict, "shape")) + { + m_shape = (imnodes::PinShape)ToInt(item); + DecodelibID(m_shape, (int*)&m_shape); + } + } + + void mvNodeAttribute::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "output", ToPyBool(m_output)); + PyDict_SetItemString(dict, "static", ToPyBool(m_static)); + PyDict_SetItemString(dict, "shape", ToPyInt(MV_ENCODE_CONSTANT((int)m_shape, 0))); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.h b/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.h new file mode 100644 index 000000000..3241b3dfe --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNodeAttribute.h @@ -0,0 +1,72 @@ +#pragma once +#include "mvAppItem.h" +#include "mvItemRegistry.h" +#include +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvNodeAttribute, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvNodeAttribute : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvNodeAttribute, add_node_attribute) + + MV_CREATE_CONSTANT(mvThemeCol_NodeAttr_Pin , imnodes::ColorStyle::ColorStyle_Pin, 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeAttr_PinHovered , imnodes::ColorStyle::ColorStyle_PinHovered, 0L); + + MV_CREATE_CONSTANT(mvNode_PinShape_Circle , imnodes::PinShape::PinShape_Circle , 0L); + MV_CREATE_CONSTANT(mvNode_PinShape_CircleFilled , imnodes::PinShape::PinShape_CircleFilled , 0L); + MV_CREATE_CONSTANT(mvNode_PinShape_Triangle , imnodes::PinShape::PinShape_Triangle , 0L); + MV_CREATE_CONSTANT(mvNode_PinShape_TriangleFilled , imnodes::PinShape::PinShape_TriangleFilled, 0L); + MV_CREATE_CONSTANT(mvNode_PinShape_Quad , imnodes::PinShape::PinShape_Quad , 0L); + MV_CREATE_CONSTANT(mvNode_PinShape_QuadFilled , imnodes::PinShape::PinShape_QuadFilled , 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_Circle), + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_CircleFilled), + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_Triangle), + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_TriangleFilled), + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_Quad), + MV_ADD_GENERAL_CONSTANT(mvNode_PinShape_QuadFilled) + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeAttr_Pin, mvColor(53, 150, 250, 180)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeAttr_PinHovered, mvColor(53, 150, 250, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvNodeAttribute(const std::string& name); + ~mvNodeAttribute(); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + int getId() const {return m_id;} + void markForDeletion() { m_delete = true; } + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + int m_id = 0; + bool m_output = false; + bool m_static = false; + imnodes::PinShape m_shape = imnodes::PinShape_CircleFilled; + bool m_delete = false; // specific delete instructions when node editor is deleted + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.cpp b/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.cpp new file mode 100644 index 000000000..aeb42c609 --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.cpp @@ -0,0 +1,629 @@ +#include "mvNodeEditor.h" +#include +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvNode.h" +#include "mvNodeAttribute.h" +#include "mvImGuiThemeScope.h" +#include "mvImNodesThemeScope.h" +#include "mvLog.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvNodeEditor::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Callable , "link_callback", "Callback ran when a new link is created.", "None"}, + {mvPythonDataType::Callable , "delink_callback", "Callback ran when a link is detached.", "None"}, + + }, "Adds a node editor.", + "None", "Containers") }); + + parsers->insert({ "add_node_link", mvPythonParser({ + {mvPythonDataType::String, "node_editor"}, + {mvPythonDataType::String, "node_1"}, + {mvPythonDataType::String, "node_2"}, + }, "Adds a node link between nodes.", + "None", "Containers") }); + + parsers->insert({ "delete_node_link", mvPythonParser({ + {mvPythonDataType::String, "node_editor"}, + {mvPythonDataType::String, "node_1"}, + {mvPythonDataType::String, "node_2"}, + }, "Deletes a node link if it exist.", + "None", "Containers") }); + + parsers->insert({ "get_selected_nodes", mvPythonParser({ + {mvPythonDataType::String, "node_editor"} + }, "Returns selected nodes.", + "List[str]", "Containers") }); + + parsers->insert({ "get_selected_links", mvPythonParser({ + {mvPythonDataType::String, "node_editor"} + }, "Returns selected links.", + "List[List[str]]", "Containers") }); + + parsers->insert({ "get_links", mvPythonParser({ + {mvPythonDataType::String, "node_editor"} + }, "Returns all links. ", + "List[List[str]]", "Containers") }); + + parsers->insert({ "clear_selected_links", mvPythonParser({ + {mvPythonDataType::String, "node_editor"} + }, "Clears selected links.", + "None", "Containers") }); + + parsers->insert({ "clear_selected_nodes", mvPythonParser({ + {mvPythonDataType::String, "node_editor"} + }, "Clears selected nodes.", + "None", "Containers") }); + } + + mvNodeEditor::mvNodeEditor(const std::string& name) + : mvAppItem(name) + { + } + + mvNodeEditor::~mvNodeEditor() + { + m_delinkCallback = nullptr; + for (auto& child : m_children[1]) + { + for (auto& grandchild : child->m_children[1]) + { + ((mvNodeAttribute*)grandchild.get())->markForDeletion(); + deleteLink(grandchild->m_name, ((mvNodeAttribute*)grandchild.get())->getId(), true); + } + + } + } + + void mvNodeEditor::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "link_callback")) + { + if (m_linkCallback) + Py_XDECREF(m_linkCallback); + if (item) + Py_XINCREF(item); + m_linkCallback = item; + } + + if (PyObject* item = PyDict_GetItemString(dict, "delink_callback")) + { + if (m_delinkCallback) + Py_XDECREF(m_delinkCallback); + if (item) + Py_XINCREF(item); + m_delinkCallback = item; + } + } + + bool mvNodeEditor::canChildBeAdded(mvAppItemType type) + { + if(type ==mvAppItemType::mvNode) + return true; + + mvThrowPythonError(1006, "Node editor children must be nodes only."); + MV_ITEM_REGISTRY_ERROR("Node editor children must be nodes only."); + assert(false); + return false; + } + + void mvNodeEditor::addLink(const std::string& node1, const std::string& node2) + { + int64_t node1_id = 0; + int64_t node2_id = 0; + + for (const auto& node : m_children[1]) + { + for (const auto& attr : node->m_children[1]) + { + if (attr->m_name == node1) + node1_id = static_cast(attr.get())->getId(); + if (attr->m_name == node2) + node2_id = static_cast(attr.get())->getId(); + } + } + + if (node1_id == 0 || node2_id == 0) + return; + + addLink(node1_id, node2_id); + + bool found = false; + for (const auto& link : m_linksStrings) + { + if (link.first == node1 && link.second == node2) + found = true; + } + if (!found) + m_linksStrings.push_back(std::make_pair(node1, node2)); + + if(m_linkCallback) + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() { + PyObject* link = PyTuple_New(2); + PyTuple_SetItem(link, 0, ToPyString(node1)); + PyTuple_SetItem(link, 1, ToPyString(node2)); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_linkCallback, m_name, link); + }); + + } + + void mvNodeEditor::deleteLink(const std::string& node, int id, bool deletion) + { + int nodeid = id; + + std::vector> oldLinks = m_links; + m_links.clear(); + for (auto& link : oldLinks) + { + if (link.first == nodeid || link.second == nodeid) + continue; + m_links.push_back(link); + } + + std::vector> oldLinkStrings = m_linksStrings; + m_linksStrings.clear(); + for (auto& link_string : oldLinkStrings) + { + if (link_string.first == node || link_string.second == node) + continue; + m_linksStrings.push_back(link_string); + } + + if(m_delinkCallback && !deletion) + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() { + PyObject* link = PyTuple_New(1); + PyTuple_SetItem(link, 0, ToPyString(node)); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_delinkCallback, m_name, link); + }); + + } + + void mvNodeEditor::deleteLink(const std::string& node1, const std::string& node2) + { + int node1_id = 0; + int node2_id = 0; + + for (const auto& node : m_children[1]) + { + for (const auto& attr : node->m_children[1]) + { + if (attr->m_name == node1) + node1_id = static_cast(attr.get())->getId(); + if (attr->m_name == node2) + node2_id = static_cast(attr.get())->getId(); + } + } + + if (node1_id == 0 || node2_id == 0) + return; + + deleteLink(node1_id, node2_id); + std::vector> oldLinkStrings = m_linksStrings; + m_linksStrings.clear(); + for (auto& link_string : oldLinkStrings) + { + if (link_string.first == node1 && link_string.second == node2) + continue; + m_linksStrings.push_back(link_string); + } + + if (m_delinkCallback) + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() { + PyObject* link = PyTuple_New(2); + PyTuple_SetItem(link, 0, ToPyString(node1)); + PyTuple_SetItem(link, 1, ToPyString(node2)); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_delinkCallback, m_name, link); + }); + + } + + void mvNodeEditor::addLink(int node1, int node2) + { + bool found = false; + for (const auto& link : m_links) + { + if (link.first == node1 && link.second == node2) + found = true; + } + if (!found) + m_links.push_back(std::make_pair(node1, node2)); + } + + void mvNodeEditor::deleteLink(int node1, int node2) + { + std::vector> oldLinks = m_links; + m_links.clear(); + for (auto& link : oldLinks) + { + if (link.first == node1 && link.second == node2) + continue; + m_links.push_back(link); + } + } + + std::vector mvNodeEditor::getSelectedNodes() const + { + std::vector result; + for (const auto& item : m_selectedNodes) + { + for (const auto& child : m_children[1]) + { + int i1 = item; + int i2 = static_cast(child.get())->getId(); + int i3 = i1 + i2; + //if (static_cast(child.get())->getId() == item) + if (i1 == i2) + result.push_back(child->m_name); + } + } + + return result; + } + + void mvNodeEditor::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + imnodes::StyleColorsClassic(); + mvImNodesThemeScope scope(this); + mvFontScope fscope(this); + + imnodes::PushAttributeFlag(imnodes::AttributeFlags_EnableLinkDetachWithDragClick); + + imnodes::IO& io = imnodes::GetIO(); + io.link_detach_with_modifier_click.modifier = &ImGui::GetIO().KeyCtrl; + + imnodes::BeginNodeEditor(); + + if (m_clearLinks) + { + imnodes::ClearLinkSelection(); + m_clearLinks = false; + } + + if (m_clearNodes) + { + imnodes::ClearNodeSelection(); + m_clearNodes = false; + } + + // build links + for(int i = 0; im_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, x, y); + + item->getState().update(); + } + + imnodes::EndNodeEditor(); + imnodes::PopAttributeFlag(); + + + static int hovered_node_id; + for (auto& child : m_children[1]) + { + child->getState().setHovered(false); + + ImVec2 size = imnodes::GetNodeDimensions(static_cast(child.get())->getId()); + child->getState().setRectSize({ size.x, size.y }); + child->getState().setRectMin({ size.x, size.y }); + child->getState().setRectMax({ size.x, size.y }); + } + + if (imnodes::IsNodeHovered(&hovered_node_id)) + { + for (auto& child : m_children[1]) + { + if (static_cast(child.get())->getId() == hovered_node_id) + child->getState().setHovered(true); + } + } + + m_selectedNodes.clear(); + if (imnodes::NumSelectedNodes() > 0) + { + int* selected_nodes = new int[imnodes::NumSelectedNodes()]; + imnodes::GetSelectedNodes(selected_nodes); + + for (int i = 0; i < imnodes::NumSelectedNodes(); i++) + m_selectedNodes.push_back(selected_nodes[i]); + delete[] selected_nodes; + } + + m_selectedLinks.clear(); + if (imnodes::NumSelectedLinks() > 0) + { + int* selected_links = new int[imnodes::NumSelectedLinks()]; + imnodes::GetSelectedLinks(selected_links); + + for (int i = 0; i < imnodes::NumSelectedLinks(); i++) + m_selectedLinks.push_back(selected_links[i]); + delete[] selected_links; + } + + static int start_attr, end_attr; + if (imnodes::IsLinkCreated(&start_attr, &end_attr)) + { + std::string node1, node2; + for (const auto& child : m_children[1]) + { + for (const auto& grandchild : child->m_children[1]) + { + if (static_cast(grandchild.get())->getId()== start_attr) + node1 = grandchild->m_name; + + if (static_cast(grandchild.get())->getId() == end_attr) + node2 = grandchild->m_name; + } + } + addLink(node1, node2); + } + + static int destroyed_attr; + if (imnodes::IsLinkDestroyed(&destroyed_attr)) + { + auto item = m_linksStrings[destroyed_attr]; + deleteLink(item.first, item.second); + } + + m_state.setHovered(imnodes::IsEditorHovered()); + + + } + + PyObject* mvNodeEditor::add_node_link(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + const char* node_1; + const char* node_2; + + + if (!(mvApp::GetApp()->getParsers())["add_node_link"].parse(args, kwargs, __FUNCTION__, &node_editor, + &node_1, &node_2)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + + editor->addLink(node_1, node_2); + + return GetPyNone(); + + } + + PyObject* mvNodeEditor::delete_node_link(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + const char* node_1; + const char* node_2; + + + if (!(mvApp::GetApp()->getParsers())["delete_node_link"].parse(args, kwargs, __FUNCTION__, &node_editor, + &node_1, &node_2)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + + editor->deleteLink(node_1, node_2); + + return GetPyNone(); + + } + + PyObject* mvNodeEditor::get_selected_nodes(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + + + if (!(mvApp::GetApp()->getParsers())["get_selected_nodes"].parse(args, kwargs, __FUNCTION__, &node_editor)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + + auto selected_nodes = editor->getSelectedNodes(); + + return ToPyList(selected_nodes); + + } + + PyObject* mvNodeEditor::get_selected_links(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + + if (!(mvApp::GetApp()->getParsers())["get_selected_links"].parse(args, kwargs, __FUNCTION__, &node_editor)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + + auto& selected_links = editor->getSelectedLinks(); + auto& links = editor->getLinks(); + + std::vector> selections; + for (auto& link : selected_links) + selections.push_back(links[link]); + + return ToPyList(selections); + + } + + PyObject* mvNodeEditor::get_links(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + + if (!(mvApp::GetApp()->getParsers())["get_links"].parse(args, kwargs, __FUNCTION__, &node_editor)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + + auto& links = editor->getLinks(); + + return ToPyList(links); + + } + + PyObject* mvNodeEditor::clear_selected_links(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + + if (!(mvApp::GetApp()->getParsers())["clear_selected_links"].parse(args, kwargs, __FUNCTION__, &node_editor)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + editor->clearLinks(); + + return GetPyNone(); + + } + + PyObject* mvNodeEditor::clear_selected_nodes(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* node_editor; + + if (!(mvApp::GetApp()->getParsers())["clear_selected_nodes"].parse(args, kwargs, __FUNCTION__, &node_editor)) + return ToPyBool(false); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto anode_editor = mvApp::GetApp()->getItemRegistry().getItem(node_editor); + if (anode_editor == nullptr) + { + std::string message = node_editor; + ThrowPythonException(message + " node_editor does not exist."); + return GetPyNone(); + } + + if (anode_editor->getType() != mvAppItemType::mvNodeEditor) + { + std::string message = node_editor; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvNodeEditor* editor = static_cast(anode_editor.get()); + editor->clearNodes(); + + return GetPyNone(); + + } + +} diff --git a/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h b/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h new file mode 100644 index 000000000..13e99feb3 --- /dev/null +++ b/DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h @@ -0,0 +1,121 @@ +#pragma once +#include "mvAppItem.h" +#include "mvItemRegistry.h" +#include +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvNodeEditor, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvNodeEditor : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvNodeEditor, add_node_editor) + + MV_CREATE_EXTRA_COMMAND(add_node_link); + MV_CREATE_EXTRA_COMMAND(delete_node_link); + MV_CREATE_EXTRA_COMMAND(get_selected_nodes); + MV_CREATE_EXTRA_COMMAND(get_links); + MV_CREATE_EXTRA_COMMAND(get_selected_links); + MV_CREATE_EXTRA_COMMAND(clear_selected_nodes); + MV_CREATE_EXTRA_COMMAND(clear_selected_links); + + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_Link , imnodes::ColorStyle::ColorStyle_Link , 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_LinkHovered , imnodes::ColorStyle::ColorStyle_LinkHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_LinkSelected , imnodes::ColorStyle::ColorStyle_LinkSelected , 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_BoxSelector , imnodes::ColorStyle::ColorStyle_BoxSelector , 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_BoxSelectorOutline , imnodes::ColorStyle::ColorStyle_BoxSelectorOutline, 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_GridBackground , imnodes::ColorStyle::ColorStyle_GridBackground , 0L); + MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_GridLine , imnodes::ColorStyle::ColorStyle_GridLine , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_GridSpacing , imnodes::StyleVar::StyleVar_GridSpacing , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkThickness , imnodes::StyleVar::StyleVar_LinkThickness , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkLineSegmentsPerLength, imnodes::StyleVar::StyleVar_LinkLineSegmentsPerLength , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkHoverDistance , imnodes::StyleVar::StyleVar_LinkHoverDistance , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinCircleRadius , imnodes::StyleVar::StyleVar_PinCircleRadius , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinQuadSideLength , imnodes::StyleVar::StyleVar_PinQuadSideLength , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinTriangleSideLength , imnodes::StyleVar::StyleVar_PinTriangleSideLength , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinLineThickness , imnodes::StyleVar::StyleVar_PinLineThickness , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinHoverRadius , imnodes::StyleVar::StyleVar_PinHoverRadius , 0L); + MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_PinOffset , imnodes::StyleVar::StyleVar_PinOffset , 0L); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(add_node_link); + MV_ADD_EXTRA_COMMAND(delete_node_link); + MV_ADD_EXTRA_COMMAND(get_selected_nodes); + MV_ADD_EXTRA_COMMAND(get_links); + MV_ADD_EXTRA_COMMAND(get_selected_links); + MV_ADD_EXTRA_COMMAND(clear_selected_nodes); + MV_ADD_EXTRA_COMMAND(clear_selected_links); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_Link, mvColor( 61, 133, 224, 200)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_LinkHovered, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_LinkSelected, mvColor( 66, 150, 250, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_BoxSelector, mvColor( 61, 133, 224, 30)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_BoxSelectorOutline, mvColor( 61, 133, 224, 150)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_GridBackground, mvColor( 40, 40, 50, 200)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_GridLine, mvColor(200, 200, 200, 40)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_GridSpacing, 20, 20), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_LinkThickness, 3, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_LinkLineSegmentsPerLength, 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_LinkHoverDistance, 3, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinCircleRadius, 5, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinQuadSideLength, 5, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinTriangleSideLength, 5, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinLineThickness, 3, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinHoverRadius, 5, 12), + MV_ADD_CONSTANT(mvThemeStyle_NodeEditor_PinOffset, 0, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvNodeEditor(const std::string& name); + ~mvNodeEditor(); + + void setExtraConfigDict(PyObject* dict) override; + + bool canChildBeAdded(mvAppItemType type) override; + + // called by python + void addLink (const std::string& node1, const std::string& node2); + void deleteLink(const std::string& node1, const std::string& node2); + + + void addLink(int node1, int node2); + void deleteLink(const std::string& node, int id, bool deletion); + void deleteLink(int node1, int node2); + std::vector getSelectedNodes() const; + const std::vector>& getLinks() const { return m_linksStrings; } + const std::vector& getSelectedLinks() const { return m_selectedLinks; } + void clearNodes() { m_clearNodes = true; } + void clearLinks() { m_clearLinks = true; } + + void draw(ImDrawList* drawlist, float x, float y) override; + + private: + + std::vector> m_links; + std::vector> m_linksStrings; + std::vector m_selectedNodes; + std::vector m_selectedLinks; + + bool m_clearNodes = false; + bool m_clearLinks = false; + + mvCallable m_linkCallback = nullptr; + mvCallable m_delinkCallback = nullptr; + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvAnnotation.cpp b/DearPyGui/src/core/AppItems/plots/mvAnnotation.cpp new file mode 100644 index 000000000..b9901f952 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvAnnotation.cpp @@ -0,0 +1,75 @@ +#include +#include "mvAnnotation.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvAnnotation::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "offset", "", "(0.0, 0.0)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::FloatList, "color", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Bool, "clamped", "", "True"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvAnnotation::mvAnnotation(const std::string& name) + : mvFloat4PtrBase(name) + { + } + + bool mvAnnotation::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvPlot) + return true; + + mvThrowPythonError(1000, "Item's parent must be plot."); + MV_ITEM_REGISTRY_ERROR("Item's parent must be plot."); + assert(false); + return false; + } + + void mvAnnotation::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvFontScope fscope(this); + + if (m_clamped) + ImPlot::AnnotateClamped((*m_value.get())[0], (*m_value.get())[1], m_pixOffset, m_color.toVec4(), m_label.c_str()); + else + ImPlot::Annotate((*m_value.get())[0], (*m_value.get())[1], m_pixOffset, m_color.toVec4(), m_label.c_str()); + + } + + void mvAnnotation::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "clamped")) m_clamped = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "offset")) m_pixOffset = ToVec2(item); + + } + + void mvAnnotation::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvAnnotation.h b/DearPyGui/src/core/AppItems/plots/mvAnnotation.h new file mode 100644 index 000000000..2af40a0f2 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvAnnotation.h @@ -0,0 +1,46 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvAnnotation, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float4, 1); + class mvAnnotation : public mvFloat4PtrBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvAnnotation, add_plot_annotation) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvAnnotation(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + bool isParentCompatible(mvAppItemType type) override; + + private: + + mvColor m_color = mvColor(0.0f, 0.0f, 0.0f, -1.0f); + bool m_clamped = true; + ImVec2 m_pixOffset; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvAreaSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvAreaSeries.cpp new file mode 100644 index 000000000..e4c46d970 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvAreaSeries.cpp @@ -0,0 +1,191 @@ +#include "mvAreaSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvAreaSeries::drawPolygon() + { + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlotLimits limits = ImPlot::GetPlotLimits(); + + std::vector points; + for (unsigned i = 0; i < xptr->size(); i++) + { + float x = (*xptr)[i] > limits.X.Max ? (float)limits.X.Max : (float)(*xptr)[i]; + x = (*xptr)[i] < limits.X.Min ? (float)limits.X.Min : x; + + float y = (*yptr)[i] > limits.Y.Max ? (float)limits.Y.Max : (float)(*yptr)[i]; + y = (*yptr)[i] < limits.Y.Min ? (float)limits.Y.Min : y; + auto p = ImPlot::PlotToPixels({ x, y }); + points.push_back(p); + } + + if (m_fill.r > 0.0f) + { + size_t i; + int y; + int miny, maxy; + int x1, y1; + int x2, y2; + int ind1, ind2; + size_t ints; + size_t n = points.size(); + int* polyints = new int[n]; + + /* Determine Y maxima */ + miny = (int)points[0].y; + maxy = (int)points[0].y; + for (i = 1; i < n; i++) + { + miny = std::min(miny, (int)points[i].y); + maxy = std::max(maxy, (int)points[i].y); + } + + /* Draw, scanning y */ + for (y = miny; y <= maxy; y++) { + ints = 0; + for (i = 0; (i < n); i++) { + if (!i) + { + ind1 = (int)n - 1; + ind2 = 0; + } + else + { + ind1 = (int)i - 1; + ind2 = (int)i; + } + y1 = (int)points[ind1].y; + y2 = (int)points[ind2].y; + if (y1 < y2) + { + x1 = (int)points[ind1].x; + x2 = (int)points[ind2].x; + } + else if (y1 > y2) + { + y2 = (int)points[ind1].y; + y1 = (int)points[ind2].y; + x2 = (int)points[ind1].x; + x1 = (int)points[ind2].x; + } + else + continue; + + if (((y >= y1) && (y < y2)) || ((y == maxy) && (y > y1) && (y <= y2))) + polyints[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; + + } + + auto compare_int = [](const void* a, const void* b) + { + return (*(const int*)a) - (*(const int*)b); + }; + + qsort(polyints, ints, sizeof(int), compare_int); + + for (i = 0; i < ints; i += 2) + ImGui::GetWindowDrawList()->AddLine({ (float)polyints[i], (float)y }, { (float)polyints[i + 1], (float)y }, m_fill, 1.0f); + } + delete[] polyints; + } + + } + + void mvAreaSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::FloatList, "fill", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvAreaSeries::mvAreaSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvAreaSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotLine(m_label.c_str(), xptr->data(), yptr->data(), xptr->size()); + + ImPlot::PushPlotClipRect(); + auto item = ImPlot::RegisterOrGetItem(m_label.c_str()); + drawPolygon(); + ImPlot::PopPlotClipRect(); + + } + + void mvAreaSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "fill")) m_fill = ToColor(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvAreaSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvAreaSeries.h b/DearPyGui/src/core/AppItems/plots/mvAreaSeries.h new file mode 100644 index 000000000..0f80154c7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvAreaSeries.h @@ -0,0 +1,53 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvAreaSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvAreaSeries : public mvSeriesBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvAreaSeries, add_area_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Area_Line, ImPlotCol_Line, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Area_Weight, ImPlotStyleVar_LineWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Area_Line, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Area_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvAreaSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + void drawPolygon(); + + private: + + mvColor m_fill = MV_DEFAULT_COLOR; + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvBarSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvBarSeries.cpp new file mode 100644 index 000000000..385bc2cb1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvBarSeries.cpp @@ -0,0 +1,96 @@ +#include +#include "mvBarSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvBarSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::Float, "weight", "", "1.0"}, + {mvPythonDataType::Bool, "horizontal", "", "False"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvBarSeries::mvBarSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvBarSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + if (m_horizontal) + ImPlot::PlotBarsH(m_name.c_str(), xptr->data(), yptr->data(), (int)xptr->size(), m_weight); + else + ImPlot::PlotBars(m_name.c_str(), xptr->data(), yptr->data(), (int)xptr->size(), m_weight); + + } + + void mvBarSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "horizontal")) m_horizontal= ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "weight")) m_weight= ToFloat(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvBarSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvBarSeries.h b/DearPyGui/src/core/AppItems/plots/mvBarSeries.h new file mode 100644 index 000000000..df358060f --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvBarSeries.h @@ -0,0 +1,47 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvBarSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvBarSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvBarSeries, add_bar_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Bar, ImPlotCol_Line, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Bar, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvBarSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_horizontal = false; + float m_weight = 1.0f; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvCandleSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvCandleSeries.cpp new file mode 100644 index 000000000..b80c9c6c1 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvCandleSeries.cpp @@ -0,0 +1,187 @@ +#include "mvCandleSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + template + int BinarySearch(const T* arr, int l, int r, T x) { + if (r >= l) { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return BinarySearch(arr, l, mid - 1, x); + return BinarySearch(arr, mid + 1, r, x); + } + return -1; + } + + static void PlotCandlestick(const char* label_id, const float* xs, const float* opens, + const float* closes, const float* lows, const float* highs, int count, + bool tooltip, float width_percent, ImVec4 bullCol, ImVec4 bearCol) { + + // get ImGui window DrawList + ImDrawList* draw_list = ImPlot::GetPlotDrawList(); + // calc real value width + float half_width = count > 1 ? (xs[1] - xs[0]) * width_percent : width_percent; + + // custom tool + if (ImPlot::IsPlotHovered() && tooltip) { + ImPlotPoint mouse = ImPlot::GetPlotMousePos(); + mouse.x = ImPlot::RoundTime(ImPlotTime::FromDouble(mouse.x), ImPlotTimeUnit_Day).ToDouble(); + float tool_l = ImPlot::PlotToPixels(mouse.x - half_width * 1.5, mouse.y).x; + float tool_r = ImPlot::PlotToPixels(mouse.x + half_width * 1.5, mouse.y).x; + float tool_t = ImPlot::GetPlotPos().y; + float tool_b = tool_t + ImPlot::GetPlotSize().y; + ImPlot::PushPlotClipRect(); + draw_list->AddRectFilled(ImVec2(tool_l, tool_t), ImVec2(tool_r, tool_b), IM_COL32(128, 128, 128, 64)); + ImPlot::PopPlotClipRect(); + // find mouse location index + int idx = BinarySearch(xs, 0, count - 1, (float)mouse.x); + // render tool tip (won't be affected by plot clip rect) + if (idx != -1) { + ImGui::BeginTooltip(); + char buff[32]; + ImPlot::FormatDate(ImPlotTime::FromDouble(xs[idx]), buff, 32, ImPlotDateFmt_DayMoYr, ImPlot::GetStyle().UseISO8601); + ImGui::Text("Day: %s", buff); + ImGui::Text("Open: $%.2f", opens[idx]); + ImGui::Text("Close: $%.2f", closes[idx]); + ImGui::Text("Low: $%.2f", lows[idx]); + ImGui::Text("High: $%.2f", highs[idx]); + ImGui::EndTooltip(); + } + } + + // begin plot item + if (ImPlot::BeginItem(label_id)) { + // override legend icon color + ImPlot::GetCurrentItem()->Color = ImGui::ColorConvertFloat4ToU32({ 0.25f, 0.25f, 0.25f, 1.0f }); + // fit data if requested + if (ImPlot::FitThisFrame()) { + for (int i = 0; i < count; ++i) { + ImPlot::FitPoint(ImPlotPoint(xs[i], lows[i])); + ImPlot::FitPoint(ImPlotPoint(xs[i], highs[i])); + } + } + // render data + for (int i = 0; i < count; ++i) { + ImVec2 open_pos = ImPlot::PlotToPixels(xs[i] - half_width, opens[i]); + ImVec2 close_pos = ImPlot::PlotToPixels(xs[i] + half_width, closes[i]); + ImVec2 low_pos = ImPlot::PlotToPixels(xs[i], lows[i]); + ImVec2 high_pos = ImPlot::PlotToPixels(xs[i], highs[i]); + ImU32 color = ImGui::GetColorU32(opens[i] > closes[i] ? bearCol : bullCol); + draw_list->AddLine(low_pos, high_pos, color); + draw_list->AddRectFilled(open_pos, close_pos, color); + } + + // end plot item + ImPlot::EndItem(); + } + } + + void mvCandleSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "dates"}, + {mvPythonDataType::FloatList, "opens"}, + {mvPythonDataType::FloatList, "closes"}, + {mvPythonDataType::FloatList, "lows"}, + {mvPythonDataType::FloatList, "highs"}, + {mvPythonDataType::Bool, "tooltip", "", "True"}, + {mvPythonDataType::FloatList, "bull_color", "", "(0, 255, 113, 255)"}, + {mvPythonDataType::FloatList, "bear_color", "", "(218, 13, 79, 255)"}, + {mvPythonDataType::Float, "weight", "", "0.25"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvCandleSeries::mvCandleSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvCandleSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* datesptr; + static const std::vector* openptr; + static const std::vector* closeptr; + static const std::vector* lowptr; + static const std::vector* highptr; + + datesptr = &(*m_value.get())[0]; + openptr = &(*m_value.get())[1]; + closeptr = &(*m_value.get())[2]; + lowptr = &(*m_value.get())[3]; + highptr = &(*m_value.get())[4]; + + PlotCandlestick(m_label.c_str(), datesptr->data(), openptr->data(), closeptr->data(), + lowptr->data(), highptr->data(), (int)datesptr->size(), m_tooltip, m_width, m_bullColor, + m_bearColor); + + } + + void mvCandleSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "bull_color")) m_bullColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "bear_color")) m_bearColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "width")) m_width = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "tooltip")) m_tooltip = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "dates")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "opens")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "closes")) { valueChanged = true; (*m_value)[2] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "lows")) { valueChanged = true; (*m_value)[3] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "highs")) { valueChanged = true; (*m_value)[4] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvCandleSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvCandleSeries.h b/DearPyGui/src/core/AppItems/plots/mvCandleSeries.h new file mode 100644 index 000000000..14da5dfa4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvCandleSeries.h @@ -0,0 +1,48 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvCandleSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvCandleSeries : public mvSeriesBase + { + + public: + + static void InsertParser(std::map*parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvCandleSeries, add_candle_series) + + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvCandleSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + float m_width = 0.25f; + bool m_tooltip = true; + mvColor m_bullColor = { 0, 255, 113, 255}; + mvColor m_bearColor = { 218, 13, 79, 255 }; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvDragLine.cpp b/DearPyGui/src/core/AppItems/plots/mvDragLine.cpp new file mode 100644 index 000000000..afa06fac7 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvDragLine.cpp @@ -0,0 +1,93 @@ +#include +#include "mvDragLine.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDragLine::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0, 0.0, 0.0)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::FloatList, "color", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "thickness", "", "1.0"}, + {mvPythonDataType::Bool, "show_label", "", "True"}, + {mvPythonDataType::Bool, "vertical", "", "True"}, + {mvPythonDataType::Callable, "callback", "function to run when point is moved", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvDragLine::mvDragLine(const std::string& name) + : mvFloatPtrBase(name) + { + } + + bool mvDragLine::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvPlot) + return true; + + mvThrowPythonError(1000, "Item's parent must be plot."); + MV_ITEM_REGISTRY_ERROR("Item's parent must be plot."); + assert(false); + return false; + } + + void mvDragLine::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvFontScope fscope(this); + + static double dummy = 0.0; + dummy = *(float*)m_value.get(); + + if (m_vertical) + { + if (ImPlot::DragLineX(m_label.c_str(), &dummy, m_show_label, m_color, m_thickness)) + { + *m_value.get() = (float)dummy; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, nullptr); + } + } + else + { + if (ImPlot::DragLineY(m_label.c_str(), &dummy, m_show_label, m_color, m_thickness)) + { + *m_value.get() = (float)dummy; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, nullptr); + } + } + + } + + void mvDragLine::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "thickness")) m_thickness = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "show_label")) m_show_label = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "vertical")) m_vertical = ToBool(item); + + } + + void mvDragLine::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvDragLine.h b/DearPyGui/src/core/AppItems/plots/mvDragLine.h new file mode 100644 index 000000000..9d93b29e3 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvDragLine.h @@ -0,0 +1,47 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDragLine, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float, 1); + class mvDragLine : public mvFloatPtrBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragLine, add_drag_line) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDragLine(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + bool isParentCompatible(mvAppItemType type) override; + + private: + + bool m_show_label = true; + mvColor m_color = mvColor(0.0f, 0.0f, 0.0f, -1.0f); + float m_thickness = 1.0f; + bool m_vertical = true; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvDragPoint.cpp b/DearPyGui/src/core/AppItems/plots/mvDragPoint.cpp new file mode 100644 index 000000000..725a6c01e --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvDragPoint.cpp @@ -0,0 +1,83 @@ +#include +#include "mvDragPoint.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvDragPoint::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "default_value", "", "(0.0, 0.0, 0.0, 0.0)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::FloatList, "color", "", "(0, 0, 0, -1)"}, + {mvPythonDataType::Float, "radius", "", "4.0"}, + {mvPythonDataType::Bool, "show_label", "", "True"}, + {mvPythonDataType::Callable, "callback", "function to run when point is moved", "None"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvDragPoint::mvDragPoint(const std::string& name) + : mvFloat4PtrBase(name) + { + } + + bool mvDragPoint::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvPlot) + return true; + + mvThrowPythonError(1000, "Item's parent must be plot."); + MV_ITEM_REGISTRY_ERROR("Item's parent must be plot."); + assert(false); + return false; + } + + void mvDragPoint::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvFontScope fscope(this); + + static double dummyx = (*m_value.get())[0]; + static double dummyy = (*m_value.get())[1]; + dummyx = (*m_value.get())[0]; + dummyy = (*m_value.get())[1]; + + if (ImPlot::DragPoint(m_label.c_str(), &dummyx, &dummyy, m_show_label, m_color, m_radius)) + { + (*m_value.get())[0] = dummyx; + (*m_value.get())[1] = dummyy; + mvApp::GetApp()->getCallbackRegistry().addCallback(m_callback, m_name, nullptr); + } + + } + + void mvDragPoint::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "color")) m_color = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "radius")) m_radius = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "show_label")) m_show_label = ToBool(item); + + } + + void mvDragPoint::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvDragPoint.h b/DearPyGui/src/core/AppItems/plots/mvDragPoint.h new file mode 100644 index 000000000..2ad1c0c01 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvDragPoint.h @@ -0,0 +1,46 @@ +#pragma once + +#include "mvTypeBases.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvDragPoint, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Float4, 1); + class mvDragPoint : public mvFloat4PtrBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvDragPoint, add_drag_point) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvDragPoint(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + bool isParentCompatible(mvAppItemType type) override; + + private: + + bool m_show_label = true; + mvColor m_color = mvColor(0.0f, 0.0f, 0.0f, -1.0f); + float m_radius = 4.0f; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvErrorSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvErrorSeries.cpp new file mode 100644 index 000000000..9ae474c72 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvErrorSeries.cpp @@ -0,0 +1,103 @@ +#include +#include "mvErrorSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvErrorSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::FloatList, "negative"}, + {mvPythonDataType::FloatList, "positive"}, + {mvPythonDataType::Bool, "horizontal", "", "False"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvErrorSeries::mvErrorSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvErrorSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + static const std::vector* zptr; + static const std::vector* wptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + zptr = &(*m_value.get())[2]; + wptr = &(*m_value.get())[3]; + + if (m_horizontal) + ImPlot::PlotErrorBarsH(m_name.c_str(), xptr->data(), yptr->data(), zptr->data(), wptr->data(), (int)xptr->size()); + else + ImPlot::PlotErrorBars(m_name.c_str(), xptr->data(), yptr->data(), zptr->data(), wptr->data(), (int)xptr->size()); + + } + + void mvErrorSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "horizontal")) m_horizontal= ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "negative")) { valueChanged = true; (*m_value)[2] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "positive")) { valueChanged = true; (*m_value)[3] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvErrorSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvErrorSeries.h b/DearPyGui/src/core/AppItems/plots/mvErrorSeries.h new file mode 100644 index 000000000..e9f7d4020 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvErrorSeries.h @@ -0,0 +1,51 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvErrorSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvErrorSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvErrorSeries, add_error_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Error, ImPlotCol_ErrorBar, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Error_Size, ImPlotStyleVar_ErrorBarSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Error_Weight, ImPlotStyleVar_ErrorBarWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Error, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Error_Size, 5.0f, 10.0f), + MV_ADD_CONSTANT(mvThemeStyle_Plot_Error_Weight, 1.5f, 10.0f), + MV_END_STYLE_CONSTANTS + + public: + + mvErrorSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + bool m_horizontal = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvHeatSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvHeatSeries.cpp new file mode 100644 index 000000000..5d4ac6e9e --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvHeatSeries.cpp @@ -0,0 +1,85 @@ +#include +#include "mvHeatSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvHeatSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::Integer, "rows", "", "1"}, + {mvPythonDataType::Integer, "cols", "", "1"}, + {mvPythonDataType::Double, "scale_min", "", "0.0"}, + {mvPythonDataType::Double, "scale_max", "", "1.0"}, + {mvPythonDataType::String, "format", "", "'%0.1f'"}, + {mvPythonDataType::FloatList, "bounds_min", "", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "bounds_max", "", "(1.0, 1.0)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvHeatSeries::mvHeatSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvHeatSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + static const std::vector* xptr; + + xptr = &(*m_value.get())[0]; + + + ImPlot::PlotHeatmap(m_name.c_str(), xptr->data(), m_rows, m_cols, m_scale_min, m_scale_max, + m_format.c_str(), { m_bounds_min.x, m_bounds_min.y }, { m_bounds_max.x, m_bounds_max.y }); + + } + + void mvHeatSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "rows")) m_rows = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "cols")) m_cols = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "bounds_min")) m_bounds_min = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "bounds_max")) m_bounds_max = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "scale_min")) m_scale_min = (double)ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "scale_max")) m_scale_max = (double)ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvHeatSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvHeatSeries.h b/DearPyGui/src/core/AppItems/plots/mvHeatSeries.h new file mode 100644 index 000000000..13556d598 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvHeatSeries.h @@ -0,0 +1,49 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvHeatSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvHeatSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvHeatSeries, add_heat_series) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvHeatSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_rows = 1; + int m_cols = 1; + double m_scale_min = 0.0; + double m_scale_max = 1.0; + std::string m_format = "%0.1f"; + mvVec2 m_bounds_min = {0.0f, 0.0f}; + mvVec2 m_bounds_max = {1.0f, 1.0f}; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvImageSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvImageSeries.cpp new file mode 100644 index 000000000..a6fea547d --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvImageSeries.cpp @@ -0,0 +1,120 @@ +#include +#include "mvImageSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" +#include "mvTextureStorage.h" + +namespace Marvel { + + void mvImageSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "value"}, + {mvPythonDataType::FloatList, "bounds_min", "bottom left coordinate"}, + {mvPythonDataType::FloatList, "bounds_max", "top right coordinate"}, + {mvPythonDataType::FloatList, "uv_min", "normalized texture coordinates", "(0.0, 0.0)"}, + {mvPythonDataType::FloatList, "uv_max", "normalized texture coordinates", "(1.0, 1.0)"}, + {mvPythonDataType::IntList, "tint_color", "", "(255, 255, 255, 255)"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvImageSeries::mvImageSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + bool mvImageSeries::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvImageSeries::onTextureDeleted), mvEVT_DELETE_TEXTURE); + + return event.handled; + } + + bool mvImageSeries::onTextureDeleted(mvEvent& event) + { + std::string name = GetEString(event, "NAME"); + + if (name == m_imagevalue) + { + m_texture = nullptr; + return true; + } + + return false; + } + + void mvImageSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + if (m_texture == nullptr) + { + mvApp::GetApp()->getTextureStorage().addTexture(m_imagevalue); + mvTexture* texture = mvApp::GetApp()->getTextureStorage().getTexture(m_imagevalue); + m_texture = texture->texture; + } + if (m_texture) + ImPlot::PlotImage(m_name.c_str(), m_texture, m_bounds_min, m_bounds_max, m_uv_min, m_uv_max, m_tintColor); + + } + + void mvImageSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "value")) m_imagevalue = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) m_uv_min = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) m_uv_max = ToVec2(item); + if (PyObject* item = PyDict_GetItemString(dict, "tint_color")) m_tintColor = ToColor(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "bounds_min")) + { + auto result = ToVec2(item); + m_bounds_min.x = (double)result.x; + m_bounds_min.y = (double)result.y; + } + if (PyObject* item = PyDict_GetItemString(dict, "bounds_max")) + { + auto result = ToVec2(item); + m_bounds_max.x = (double)result.x; + m_bounds_max.y = (double)result.y; + } + + } + + void mvImageSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvImageSeries.h b/DearPyGui/src/core/AppItems/plots/mvImageSeries.h new file mode 100644 index 000000000..4d0f53fea --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvImageSeries.h @@ -0,0 +1,53 @@ +#pragma once + +#include "mvPlot.h" +#include "mvEvents.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvImageSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvImageSeries : public mvSeriesBase, public mvEventHandler + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvImageSeries, add_image_series) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvImageSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + bool onEvent(mvEvent& event) override; + bool onTextureDeleted(mvEvent& event); + + private: + + std::string m_imagevalue; + ImPlotPoint m_bounds_min; + ImPlotPoint m_bounds_max; + mvVec2 m_uv_min = { 0.0f, 0.0f }; + mvVec2 m_uv_max = { 1.0f, 1.0f }; + mvColor m_tintColor = { 1.0f, 1.0f, 1.0f, 1.0f }; + void* m_texture = nullptr; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.cpp new file mode 100644 index 000000000..682f57899 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.cpp @@ -0,0 +1,162 @@ +#include +#include "mvInfiniteLineSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvVLineSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvVLineSeries::mvVLineSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvVLineSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + + xptr = &(*m_value.get())[0]; + + ImPlot::PlotVLines(m_label.c_str(), xptr->data(), xptr->size()); + + } + + void mvVLineSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvVLineSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + + void mvHLineSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvHLineSeries::mvHLineSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvHLineSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + + xptr = &(*m_value.get())[0]; + + ImPlot::PlotHLines(m_label.c_str(), xptr->data(), xptr->size()); + + } + + void mvHLineSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvHLineSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.h b/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.h new file mode 100644 index 000000000..3428da954 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvInfiniteLineSeries.h @@ -0,0 +1,97 @@ +#pragma once + +#include "mvPlot.h" + +//----------------------------------------------------------------------------- +// Widget Index +// +// * mvVLineSeries +// * mvHLineSeries +// +//----------------------------------------------------------------------------- + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvVLineSeries + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvVLineSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvVLineSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvVLineSeries, add_vline_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_VLine, ImPlotCol_Line, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_VLine_Weight, ImPlotStyleVar_LineWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_VLine, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_VLine_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvVLineSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + + //----------------------------------------------------------------------------- + // mvHLineSeries + //----------------------------------------------------------------------------- + MV_REGISTER_WIDGET(mvHLineSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvHLineSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvHLineSeries, add_hline_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_HLine, ImPlotCol_Line, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_HLine_Weight, ImPlotStyleVar_LineWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_HLine, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_HLine_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvHLineSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp new file mode 100644 index 000000000..d7cbfd1fc --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp @@ -0,0 +1,97 @@ +#include +#include "mvLabelSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvLabelSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "x"}, + {mvPythonDataType::Float, "y"}, + {mvPythonDataType::Bool, "vertical", "", "False"}, + {mvPythonDataType::Integer, "x_offset", "", "0.0"}, + {mvPythonDataType::Integer, "y_offset", "", "0.0"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvLabelSeries::mvLabelSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvLabelSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotText(m_label.c_str(), (*xptr)[0], (*yptr)[0], m_vertical, + ImVec2((float)m_xoffset, (float)m_yoffset)); + + } + + void mvLabelSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "vertical")) m_vertical = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "x_offset")) m_xoffset = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "y_offset")) m_yoffset = ToInt(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvLabelSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvLabelSeries.h b/DearPyGui/src/core/AppItems/plots/mvLabelSeries.h new file mode 100644 index 000000000..216b144c5 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvLabelSeries.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvLabelSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvLabelSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvLabelSeries, add_text_point) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvLabelSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + int m_xoffset = 0; + int m_yoffset = 0; + bool m_vertical = false; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvLineSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvLineSeries.cpp new file mode 100644 index 000000000..a9e415354 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvLineSeries.cpp @@ -0,0 +1,90 @@ +#include +#include "mvLineSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvLineSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvLineSeries::mvLineSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvLineSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotLine(m_label.c_str(), xptr->data(), yptr->data(), xptr->size()); + + } + + void mvLineSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + } + + void mvLineSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvLineSeries.h b/DearPyGui/src/core/AppItems/plots/mvLineSeries.h new file mode 100644 index 000000000..dcfa2c83b --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvLineSeries.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvLineSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvLineSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvLineSeries, add_line_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Line, ImPlotCol_Line, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Line_Weight, ImPlotStyleVar_LineWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Line, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Line_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvLineSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvPieSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvPieSeries.cpp new file mode 100644 index 000000000..a9ee7c306 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvPieSeries.cpp @@ -0,0 +1,104 @@ +#include +#include "mvPieSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvPieSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "values"}, + {mvPythonDataType::StringList, "labels"}, + {mvPythonDataType::Double, "x"}, + {mvPythonDataType::Double, "y"}, + {mvPythonDataType::Double, "radius"}, + {mvPythonDataType::Bool, "normalize", "", "False"}, + {mvPythonDataType::Double, "angle", "", "90.0"}, + {mvPythonDataType::String, "format", "", "'%0.2f'"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvPieSeries::mvPieSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvPieSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + + xptr = &(*m_value.get())[0]; + + ImPlot::PlotPieChart(m_clabels.data(), xptr->data(), (int)m_labels.size(), + m_x, m_y, m_radius, m_normalize, m_format.c_str(), m_angle); + + } + + void mvPieSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "format")) m_format = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "x")) m_x = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "y")) m_y = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "radius")) m_radius = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "angle")) m_angle = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "normalize")) m_normalize = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "labels")) + { + m_labels = ToStringVect(item); + m_clabels.clear(); + for (const auto& label : m_labels) + m_clabels.push_back(label.c_str()); + } + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "values")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + + + } + + void mvPieSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvPieSeries.h b/DearPyGui/src/core/AppItems/plots/mvPieSeries.h new file mode 100644 index 000000000..ca497e7b2 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvPieSeries.h @@ -0,0 +1,50 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvPieSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvPieSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvPieSeries, add_pie_series) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvPieSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + double m_x = 0.0; + double m_y = 0.0; + double m_radius = 0.5f; + bool m_normalize = true; + double m_angle = 90.0; + std::string m_format; + std::vector m_labels; + std::vector m_clabels; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvPlot.cpp b/DearPyGui/src/core/AppItems/plots/mvPlot.cpp new file mode 100644 index 000000000..20425741b --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvPlot.cpp @@ -0,0 +1,966 @@ +#include +#include "mvPlot.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvInput.h" +#include "mvAreaSeries.h" +#include "mvBarSeries.h" +#include "mvCandleSeries.h" +#include "mvErrorSeries.h" +#include "mvHeatSeries.h" +#include "mvImageSeries.h" +#include "mvInfiniteLineSeries.h" +#include "mvLabelSeries.h" +#include "mvPieSeries.h" +#include "mvScatterSeries.h" +#include "mvShadeSeries.h" +#include "mvStairSeries.h" +#include "mvStemSeries.h" +#include "mvImPlotThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvPlot::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "x_axis_name", "", "''"}, + {mvPythonDataType::String, "y_axis_name", "", "''"}, + + // plot flags + {mvPythonDataType::Bool, "no_legend", "", "False"}, + {mvPythonDataType::Bool, "no_menus", "", "False"}, + {mvPythonDataType::Bool, "no_box_select", "", "False"}, + {mvPythonDataType::Bool, "no_mouse_pos", "", "False"}, + {mvPythonDataType::Bool, "no_highlight", "", "False"}, + {mvPythonDataType::Bool, "no_child", "", "False"}, + {mvPythonDataType::Bool, "query", "", "False"}, + {mvPythonDataType::Bool, "crosshairs", "", "False"}, + {mvPythonDataType::Bool, "anti_aliased", "", "False"}, + {mvPythonDataType::Bool, "equal_aspects", "", "False"}, + {mvPythonDataType::Bool, "yaxis2", "", "False"}, + {mvPythonDataType::Bool, "yaxis3", "", "False"}, + + // x axis flags + {mvPythonDataType::Bool, "xaxis_no_gridlines", "", "False"}, + {mvPythonDataType::Bool, "xaxis_no_tick_marks", "", "False"}, + {mvPythonDataType::Bool, "xaxis_no_tick_labels", "", "False"}, + {mvPythonDataType::Bool, "xaxis_log_scale", "", "False"}, + {mvPythonDataType::Bool, "xaxis_time", "", "False"}, + {mvPythonDataType::Bool, "xaxis_invert", "", "False"}, + {mvPythonDataType::Bool, "xaxis_lock_min", "", "False"}, + {mvPythonDataType::Bool, "xaxis_lock_max", "", "False"}, + + // y axis flags + {mvPythonDataType::Bool, "yaxis_no_gridlines", "", "False"}, + {mvPythonDataType::Bool, "yaxis_no_tick_marks", "", "False"}, + {mvPythonDataType::Bool, "yaxis_no_tick_labels", "", "False"}, + {mvPythonDataType::Bool, "yaxis_log_scale", "", "False"}, + {mvPythonDataType::Bool, "yaxis_invert", "", "False"}, + {mvPythonDataType::Bool, "yaxis_lock_min", "", "False"}, + {mvPythonDataType::Bool, "yaxis_lock_max", "", "False"}, + + // y2 axis flags + {mvPythonDataType::Bool, "y2axis_no_gridlines", "", "False"}, + {mvPythonDataType::Bool, "y2axis_no_tick_marks", "", "False"}, + {mvPythonDataType::Bool, "y2axis_no_tick_labels", "", "False"}, + {mvPythonDataType::Bool, "y2axis_log_scale", "", "False"}, + {mvPythonDataType::Bool, "y2axis_invert", "", "False"}, + {mvPythonDataType::Bool, "y2axis_lock_min", "", "False"}, + {mvPythonDataType::Bool, "y2axis_lock_max", "", "False"}, + + // y3 axis flags + {mvPythonDataType::Bool, "y3axis_no_gridlines", "", "False"}, + {mvPythonDataType::Bool, "y3axis_no_tick_marks", "", "False"}, + {mvPythonDataType::Bool, "y3axis_no_tick_labels", "", "False"}, + {mvPythonDataType::Bool, "y3axis_log_scale", "", "False"}, + {mvPythonDataType::Bool, "y3axis_invert", "", "False"}, + {mvPythonDataType::Bool, "y3axis_lock_min", "", "False"}, + {mvPythonDataType::Bool, "y3axis_lock_max", "", "False"}, + + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width", "", "-1"}, + {mvPythonDataType::Integer, "height", "", "-1"}, + {mvPythonDataType::Callable , "query_callback", "Callback ran when plot is queried. Should be of the form 'def Callback(sender, data)'\n Data is (x_min, x_max, y_min, y_max).", "None"}, + + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + + }, "Adds a plot widget.", "None", "Plotting") }); + + parsers->insert({ "is_plot_queried", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Returns true if plot was queried", "bool", "Plotting") }); + + parsers->insert({ "get_plot_query_area", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Returns the bounding axis limits for the query area [x_min, x_max, y_min, y_max]", "List[float]", "Plotting") }); + + parsers->insert({ "get_plot_xlimits", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Returns the plots x limits", "List[float]", "Plotting") }); + + parsers->insert({ "get_plot_ylimits", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Returns the plots x limits", "List[float]", "Plotting") }); + + parsers->insert({ "set_plot_xlimits", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + {mvPythonDataType::Float, "xmin"}, + {mvPythonDataType::Float, "xmax"}, + }, "Sets x axis limits of a plot. (can be undone with set_plot_xlimits_auto()", "None", "Plotting") }); + + parsers->insert({ "set_plot_ylimits", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + {mvPythonDataType::Float, "ymin"}, + {mvPythonDataType::Float, "ymax"}, + }, "Sets y axis limits of a plot. (can be undone with set_plot_ylimits_auto()", "None", "Plotting") }); + + parsers->insert({ "set_plot_xlimits_auto", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Sets plots x limits to be automatic.", "None", "Plotting") }); + + parsers->insert({ "set_plot_ylimits_auto", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Sets plots y limits to be automatic.", "None", "Plotting") }); + + parsers->insert({ "set_xticks", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + {mvPythonDataType::Object, "label_pairs", "list of [str,float]"}, + }, "Sets plots x ticks and labels", "None", "Plotting") }); + + parsers->insert({ "set_yticks", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + {mvPythonDataType::Object, "label_pairs", "list of [str,float]"}, + }, "Sets plots y ticks and labels", "None", "Plotting") }); + + parsers->insert({ "reset_xticks", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Sets plots x ticks and labels back to automatic", "None", "Plotting") }); + + parsers->insert({ "reset_yticks", mvPythonParser({ + {mvPythonDataType::String, "plot"}, + }, "Sets plots y ticks and labels back to automatic", "None", "Plotting") }); + + } + + static bool CheckList(const char* plot, PyObject* list) + { + if (!PyList_Check(list)) + { + ThrowPythonException(std::string(plot) + " add area series requires a list of floats."); + return false; + } + return true; + } + + static bool CheckIfPlotOk(const char* name, mvAppItem* plot) + { + if (plot == nullptr) + { + ThrowPythonException(std::string(name) + " plot does not exist."); + return false; + } + + if (plot->getType() != mvAppItemType::mvPlot) + { + ThrowPythonException(std::string(name) + " is not a plot."); + return false; + } + return true; + } + + static bool Check2ArraySizes(const char* name, const std::vector* first, const std::vector* second) + { + if (second == nullptr) + return true; + + return first->size() == second->size(); + } + + static bool CheckArraySizes(const char* name, const std::vector*>& arrays) + { + for (size_t i = 0; i < arrays.size() - 1; i++) + { + if (!Check2ArraySizes(name, arrays[i], arrays[i + 1])) + { + ThrowPythonException(std::string(name) + " data list must be the same size."); + return false; + } + } + return true; + } + + mvPlot::mvPlot(const std::string& name) + : mvAppItem(name) + { + m_width = -1; + m_height = -1; + } + + bool mvPlot::canChildBeAdded(mvAppItemType type) + { + if (type == mvAppItemType::mvDragPoint) return true; + if (type == mvAppItemType::mvDragLine) return true; + if (type == mvAppItemType::mvAnnotation) return true; + if (type == mvAppItemType::mvLineSeries) return true; + if (type == mvAppItemType::mvVLineSeries) return true; + if (type == mvAppItemType::mvHLineSeries) return true; + if (type == mvAppItemType::mvScatterSeries) return true; + if (type == mvAppItemType::mvStemSeries) return true; + if (type == mvAppItemType::mvStairSeries) return true; + if (type == mvAppItemType::mvBarSeries) return true; + if (type == mvAppItemType::mvErrorSeries) return true; + if (type == mvAppItemType::mvHeatSeries) return true; + if (type == mvAppItemType::mvImageSeries) return true; + if (type == mvAppItemType::mvPieSeries) return true; + if (type == mvAppItemType::mvShadeSeries) return true; + if (type == mvAppItemType::mvLabelSeries) return true; + if (type == mvAppItemType::mvCandleSeries) return true; + if (type == mvAppItemType::mvAreaSeries) return true; + + mvThrowPythonError(1000, "Plot children must be compatible."); + MV_ITEM_REGISTRY_ERROR("Plot children must be compatible."); + assert(false); + + return false; + } + + void mvPlot::SetColorMap(ImPlotColormap colormap) + { + if (colormap < ImPlot::GetColormapCount()) + m_dirty = true; { + m_colormap = colormap; + m_dirty = true; + } + } + + void mvPlot::resetXTicks() + { + m_xlabels.clear(); + m_xclabels.clear(); + m_xlabelLocations.clear(); + } + + void mvPlot::resetYTicks() + { + m_ylabels.clear(); + m_yclabels.clear(); + m_ylabelLocations.clear(); + } + + void mvPlot::setXTicks(const std::vector& labels, const std::vector& locations) + { + m_xlabels = labels; + m_xlabelLocations = locations; + + for (const auto& item : m_xlabels) + m_xclabels.push_back(item.data()); + } + + void mvPlot::setYTicks(const std::vector& labels, const std::vector& locations) + { + m_ylabels = labels; + m_ylabelLocations = locations; + + for (const auto& item : m_ylabels) + m_yclabels.push_back(item.data()); + } + + void mvPlot::draw(ImDrawList* drawlist, float x, float y) + { + + ImGui::PushID(m_colormap); + + if (m_setXLimits || m_dirty) + ImPlot::SetNextPlotLimitsX(m_xlimits.x, m_xlimits.y, ImGuiCond_Always); + + if (m_setYLimits || m_dirty) + ImPlot::SetNextPlotLimitsY(m_ylimits.x, m_ylimits.y, ImGuiCond_Always); + + if (m_setY2Limits || m_dirty) + ImPlot::SetNextPlotLimitsY(m_y2limits.x, m_y2limits.y, ImGuiCond_Always, ImPlotYAxis_2); + + if (m_setY3Limits || m_dirty) + ImPlot::SetNextPlotLimitsY(m_y3limits.x, m_y3limits.y, ImGuiCond_Always, ImPlotYAxis_3); + + // resets automatic sizing when new data is added + if (m_dirty) m_dirty = false; + + if (!m_xlabels.empty()) + { + // TODO: Checks + ImPlot::SetNextPlotTicksX(m_xlabelLocations.data(), (int)m_xlabels.size(), m_xclabels.data()); + } + if (!m_ylabels.empty()) + { + // TODO: Checks + ImPlot::SetNextPlotTicksY(m_ylabelLocations.data(), (int)m_ylabels.size(), m_yclabels.data()); + } + + mvImPlotThemeScope scope(this); + mvFontScope fscope(this); + + if (ImPlot::BeginPlot(m_label.c_str(), m_xaxisName.empty() ? nullptr : m_xaxisName.c_str(), m_yaxisName.empty() ? nullptr : m_yaxisName.c_str(), + ImVec2((float)m_width, (float)m_height), m_flags, + m_xflags, m_yflags, m_y2flags, m_y3flags)) + { + ImPlot::PushColormap(m_colormap); + + for (auto item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + ImPlot::PopColormap(); + + m_queried = ImPlot::IsPlotQueried(); + + if (m_queried) + { + auto area = ImPlot::GetPlotQuery(); + m_queryArea[0] = (float)area.X.Min; + m_queryArea[1] = (float)area.X.Max; + m_queryArea[2] = (float)area.Y.Min; + m_queryArea[3] = (float)area.Y.Max; + } + + if (m_queryCallback != nullptr && m_queried) + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() { + PyObject* area = PyTuple_New(4); + PyTuple_SetItem(area, 0, PyFloat_FromDouble(m_queryArea[0])); + PyTuple_SetItem(area, 1, PyFloat_FromDouble(m_queryArea[1])); + PyTuple_SetItem(area, 2, PyFloat_FromDouble(m_queryArea[2])); + PyTuple_SetItem(area, 3, PyFloat_FromDouble(m_queryArea[3])); + mvApp::GetApp()->getCallbackRegistry().addCallback(m_queryCallback, m_name, area); + }); + } + + + if (ImPlot::IsPlotHovered()) + mvInput::setPlotMousePosition((float)ImPlot::GetPlotMousePos().x, (float)ImPlot::GetPlotMousePos().y); + + m_xlimits_actual.x = ImPlot::GetPlotLimits().X.Min; + m_xlimits_actual.y = ImPlot::GetPlotLimits().X.Max; + m_ylimits_actual.x = ImPlot::GetPlotLimits().Y.Min; + m_ylimits_actual.y = ImPlot::GetPlotLimits().Y.Max; + m_y2limits_actual.x = ImPlot::GetPlotLimits(ImPlotYAxis_2).Y.Min; + m_y2limits_actual.y = ImPlot::GetPlotLimits(ImPlotYAxis_2).Y.Max; + m_y3limits_actual.x = ImPlot::GetPlotLimits(ImPlotYAxis_3).Y.Min; + m_y3limits_actual.y = ImPlot::GetPlotLimits(ImPlotYAxis_3).Y.Max; + + ImPlot::PushPlotClipRect(); + auto topleft = ImPlot::GetPlotPos(); + //m_drawList->draw(ImPlot::GetPlotDrawList(), topleft.x, topleft.y); + ImPlot::PopPlotClipRect(); + + ImPlot::EndPlot(); + } + + ImGui::PopID(); + } + + void mvPlot::setXLimits(float x_min, float x_max) + { + m_setXLimits = true; + m_xlimits = ImVec2(x_min, x_max); + } + + void mvPlot::setYLimits(float y_min, float y_max) + { + m_setYLimits = true; + m_ylimits = ImVec2(y_min, y_max); + } + + void mvPlot::setY2Limits(float y_min, float y_max) + { + m_setY2Limits = true; + m_y2limits = ImVec2(y_min, y_max); + } + + void mvPlot::setY3Limits(float y_min, float y_max) + { + m_setY3Limits = true; + m_y3limits = ImVec2(y_min, y_max); + } + + void mvPlot::setXLimitsAuto() + { + m_setXLimits = false; + } + + void mvPlot::setYLimitsAuto() + { + m_setYLimits = false; + } + + void mvPlot::setY2LimitsAuto() + { + m_setY2Limits = false; + } + + void mvPlot::setY3LimitsAuto() + { + m_setY3Limits = false; + } + + bool mvPlot::isPlotQueried() const + { + return m_queried; + } + + float* mvPlot::getPlotQueryArea() + { + return m_queryArea; + } + + void mvPlot::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "x_axis_name"))m_xaxisName = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "y_axis_name")) m_yaxisName = ToString(item); + + if (PyObject* item = PyDict_GetItemString(dict, "query_callback")) + { + if (m_queryCallback) + Py_XDECREF(m_queryCallback); + if (item) + Py_XINCREF(item); + m_queryCallback = item; + } + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + // plot flags + flagop("no_legend", ImPlotFlags_NoLegend, m_flags); + flagop("no_menus", ImPlotFlags_NoMenus, m_flags); + flagop("no_box_select", ImPlotFlags_NoBoxSelect, m_flags); + flagop("no_mouse_pos", ImPlotFlags_NoMousePos, m_flags); + flagop("no_highlight", ImPlotFlags_NoHighlight, m_flags); + flagop("no_child", ImPlotFlags_NoChild, m_flags); + flagop("query", ImPlotFlags_Query, m_flags); + flagop("crosshairs", ImPlotFlags_Crosshairs, m_flags); + flagop("anti_aliased", ImPlotFlags_AntiAliased, m_flags); + flagop("equal_aspects", ImPlotFlags_Equal, m_flags); + flagop("yaxis2", ImPlotFlags_YAxis2, m_flags); + flagop("yaxis3", ImPlotFlags_YAxis3, m_flags); + + // x axis flags + flagop("xaxis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_xflags); + flagop("xaxis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_xflags); + flagop("xaxis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_xflags); + flagop("xaxis_log_scale", ImPlotAxisFlags_LogScale, m_xflags); + flagop("xaxis_time", ImPlotAxisFlags_Time, m_xflags); + flagop("xaxis_invert", ImPlotAxisFlags_Invert, m_xflags); + flagop("xaxis_lock_min", ImPlotAxisFlags_LockMin, m_xflags); + flagop("xaxis_lock_max", ImPlotAxisFlags_LockMax, m_xflags); + + // y axis flags + flagop("yaxis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_yflags); + flagop("yaxis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_yflags); + flagop("yaxis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_yflags); + flagop("yaxis_log_scale", ImPlotAxisFlags_LogScale, m_yflags); + flagop("yaxis_invert", ImPlotAxisFlags_Invert, m_yflags); + flagop("yaxis_lock_min", ImPlotAxisFlags_LockMin, m_yflags); + flagop("yaxis_lock_max", ImPlotAxisFlags_LockMax, m_yflags); + + // y2 axis flags + flagop("y2axis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_y2flags); + flagop("y2axis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_y2flags); + flagop("y2axis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_y2flags); + flagop("y2axis_log_scale", ImPlotAxisFlags_LogScale, m_y2flags); + flagop("y2axis_invert", ImPlotAxisFlags_Invert, m_y2flags); + flagop("y2axis_lock_min", ImPlotAxisFlags_LockMin, m_y2flags); + flagop("y2axis_lock_max", ImPlotAxisFlags_LockMax, m_y2flags); + + // y3 axis flags + flagop("y3axis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_y3flags); + flagop("y3axis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_y3flags); + flagop("y3axis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_y3flags); + flagop("y3axis_log_scale", ImPlotAxisFlags_LogScale, m_y3flags); + flagop("y3axis_invert", ImPlotAxisFlags_Invert, m_y3flags); + flagop("y3axis_lock_min", ImPlotAxisFlags_LockMin, m_y3flags); + flagop("y3axis_lock_max", ImPlotAxisFlags_LockMax, m_y3flags); + + } + + void mvPlot::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "x_axis_name", ToPyString(m_xaxisName)); + PyDict_SetItemString(dict, "y_axis_name", ToPyString(m_yaxisName)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + // plot flags + checkbitset("no_legend", ImPlotFlags_NoLegend, m_flags); + checkbitset("no_menus", ImPlotFlags_NoMenus, m_flags); + checkbitset("no_box_select", ImPlotFlags_NoBoxSelect, m_flags); + checkbitset("no_mouse_pos", ImPlotFlags_NoMousePos, m_flags); + checkbitset("no_highlight", ImPlotFlags_NoHighlight, m_flags); + checkbitset("no_child", ImPlotFlags_NoChild, m_flags); + checkbitset("query", ImPlotFlags_Query, m_flags); + checkbitset("crosshairs", ImPlotFlags_Crosshairs, m_flags); + checkbitset("anti_aliased", ImPlotFlags_AntiAliased, m_flags); + checkbitset("equal_aspects", ImPlotFlags_Equal, m_flags); + checkbitset("yaxis2", ImPlotFlags_YAxis2, m_flags); + checkbitset("yaxis3", ImPlotFlags_YAxis3, m_flags); + + // x axis flags + checkbitset("xaxis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_xflags); + checkbitset("xaxis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_xflags); + checkbitset("xaxis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_xflags); + checkbitset("xaxis_log_scale", ImPlotAxisFlags_LogScale, m_xflags); + checkbitset("xaxis_time", ImPlotAxisFlags_Time, m_xflags); + checkbitset("xaxis_invert", ImPlotAxisFlags_Invert, m_xflags); + checkbitset("xaxis_lock_min", ImPlotAxisFlags_LockMin, m_xflags); + checkbitset("xaxis_lock_max", ImPlotAxisFlags_LockMax, m_xflags); + + // y axis flags + checkbitset("yaxis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_yflags); + checkbitset("yaxis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_yflags); + checkbitset("yaxis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_yflags); + checkbitset("yaxis_log_scale", ImPlotAxisFlags_LogScale, m_yflags); + checkbitset("yaxis_invert", ImPlotAxisFlags_Invert, m_yflags); + checkbitset("yaxis_lock_min", ImPlotAxisFlags_LockMin, m_yflags); + checkbitset("yaxis_lock_max", ImPlotAxisFlags_LockMax, m_yflags); + + // y2 axis flags + checkbitset("y2axis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_y2flags); + checkbitset("y2axis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_y2flags); + checkbitset("y2axis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_y2flags); + checkbitset("y2axis_log_scale", ImPlotAxisFlags_LogScale, m_y2flags); + checkbitset("y2axis_invert", ImPlotAxisFlags_Invert, m_y2flags); + checkbitset("y2axis_lock_min", ImPlotAxisFlags_LockMin, m_y2flags); + checkbitset("y2axis_lock_max", ImPlotAxisFlags_LockMax, m_y2flags); + + // y3 axis flags + checkbitset("y3axis_no_gridlines", ImPlotAxisFlags_NoGridLines, m_y3flags); + checkbitset("y3axis_no_tick_marks", ImPlotAxisFlags_NoTickMarks, m_y3flags); + checkbitset("y3axis_no_tick_labels", ImPlotAxisFlags_NoTickLabels, m_y3flags); + checkbitset("y3axis_log_scale", ImPlotAxisFlags_LogScale, m_y3flags); + checkbitset("y3axis_invert", ImPlotAxisFlags_Invert, m_y3flags); + checkbitset("y3axis_lock_min", ImPlotAxisFlags_LockMin, m_y3flags); + checkbitset("y3axis_lock_max", ImPlotAxisFlags_LockMax, m_y3flags); + } + + PyObject* mvPlot::add_plot(PyObject* self, PyObject* args, PyObject* kwargs) + { + static int i = 0; i++; + std::string name = std::string(std::string("$$DPG_ns") + s_internal_id + std::to_string(i)); + auto [parent, before] = mvAppItem::GetNameFromArgs(name, args, kwargs); + auto item = CreateRef(name); + item->checkConfigDict(kwargs); + item->setConfigArgs(args); + item->setConfigDict(kwargs); + item->setExtraConfigDict(kwargs); + mvApp::GetApp()->getItemRegistry().addItemWithRuntimeChecks(item, parent.c_str(), before.c_str()); + return ToPyString(name); + } + + PyObject* mvPlot::reset_xticks(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["reset_xticks"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->resetXTicks(); + + return GetPyNone(); + } + + PyObject* mvPlot::reset_yticks(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["reset_yticks"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->resetYTicks(); + + return GetPyNone(); + } + + PyObject* mvPlot::set_xticks(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + PyObject* label_pairs; + + if (!(mvApp::GetApp()->getParsers())["set_xticks"].parse(args, kwargs, __FUNCTION__, &plot, &label_pairs)) + return GetPyNone(); + + auto mlabel_pairs = ToVectPairStringFloat(label_pairs); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + std::vector labels; + std::vector locations; + + for (const auto& item : mlabel_pairs) + { + labels.emplace_back(item.first.c_str()); + locations.emplace_back((double)item.second); + } + graph->setXTicks(labels, locations); + + + return GetPyNone(); + } + + PyObject* mvPlot::set_yticks(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + PyObject* label_pairs; + + if (!(mvApp::GetApp()->getParsers())["set_yticks"].parse(args, kwargs, __FUNCTION__, &plot, &label_pairs)) + return GetPyNone(); + + auto mlabel_pairs = ToVectPairStringFloat(label_pairs); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + std::vector labels; + std::vector locations; + + for (const auto& item : mlabel_pairs) + { + labels.emplace_back(item.first.c_str()); + locations.emplace_back((double)item.second); + } + graph->setYTicks(labels, locations); + + return GetPyNone(); + } + + PyObject* mvPlot::set_plot_xlimits_auto(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["set_plot_xlimits_auto"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->setXLimitsAuto(); + + return GetPyNone(); + } + + PyObject* mvPlot::set_plot_ylimits_auto(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["set_plot_ylimits_auto"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->setYLimitsAuto(); + + return GetPyNone(); + } + + PyObject* mvPlot::set_plot_xlimits(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + float xmin; + float xmax; + + if (!(mvApp::GetApp()->getParsers())["set_plot_xlimits"].parse(args, kwargs, __FUNCTION__, &plot, &xmin, &xmax)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->setXLimits(xmin, xmax); + + return GetPyNone(); + } + + PyObject* mvPlot::set_plot_ylimits(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + float ymin; + float ymax; + + if (!(mvApp::GetApp()->getParsers())["set_plot_ylimits"].parse(args, kwargs, __FUNCTION__, &plot, &ymin, &ymax)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + graph->setYLimits(ymin, ymax); + + return GetPyNone(); + } + + PyObject* mvPlot::is_plot_queried(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["is_plot_queried"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + return ToPyBool(graph->isPlotQueried()); + } + + PyObject* mvPlot::get_plot_xlimits(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["get_plot_xlimits"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + const ImVec2& lim = graph->getXLimits(); + return ToPyPair(lim.x, lim.y); + } + + PyObject* mvPlot::get_plot_ylimits(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["get_plot_ylimits"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + const ImVec2& lim = graph->getYLimits(); + return ToPyPair(lim.x, lim.y); + } + + PyObject* mvPlot::get_plot_query_area(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* plot; + + if (!(mvApp::GetApp()->getParsers())["get_plot_query_area"].parse(args, kwargs, __FUNCTION__, &plot)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + auto aplot = mvApp::GetApp()->getItemRegistry().getItem(plot); + if (aplot == nullptr) + { + std::string message = plot; + ThrowPythonException(message + " plot does not exist."); + return GetPyNone(); + } + + if (aplot->getType() != mvAppItemType::mvPlot) + { + std::string message = plot; + ThrowPythonException(message + " is not a plot."); + return GetPyNone(); + } + + mvPlot* graph = static_cast(aplot.get()); + + float* result = graph->getPlotQueryArea(); + return Py_BuildValue("(ffff)", result[0], result[1], result[2], result[3]); + } + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvPlot.h b/DearPyGui/src/core/AppItems/plots/mvPlot.h new file mode 100644 index 000000000..f0e5e09ae --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvPlot.h @@ -0,0 +1,302 @@ +#pragma once + +#include "mvTypeBases.h" +#include +#include +#include +#include +#include "mvCore.h" +#include "mvPython.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvPlot, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvPlot : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvPlot, add_plot_stack) + + MV_CREATE_EXTRA_COMMAND(add_plot); + MV_CREATE_EXTRA_COMMAND(reset_xticks); + MV_CREATE_EXTRA_COMMAND(reset_yticks); + MV_CREATE_EXTRA_COMMAND(set_xticks); + MV_CREATE_EXTRA_COMMAND(set_yticks); + MV_CREATE_EXTRA_COMMAND(is_plot_queried); + MV_CREATE_EXTRA_COMMAND(get_plot_query_area); + MV_CREATE_EXTRA_COMMAND(set_plot_xlimits_auto); + MV_CREATE_EXTRA_COMMAND(set_plot_ylimits_auto); + MV_CREATE_EXTRA_COMMAND(set_plot_xlimits); + MV_CREATE_EXTRA_COMMAND(set_plot_ylimits); + MV_CREATE_EXTRA_COMMAND(get_plot_xlimits); + MV_CREATE_EXTRA_COMMAND(get_plot_ylimits); + + //----------------------------------------------------------------------------- + // Plot Marker Specifications + //----------------------------------------------------------------------------- + MV_CREATE_CONSTANT(mvPlotMarker_None , -1L, 0L); // no marker + MV_CREATE_CONSTANT(mvPlotMarker_Circle , 0L, 0L); // a circle marker will be rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Square , 1L, 0L); // a square maker will be rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Diamond , 2L, 0L); // a diamond marker will be rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Up , 3L, 0L); // an upward-pointing triangle marker will up rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Down , 4L, 0L); // an downward-pointing triangle marker will up rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Left , 5L, 0L); // an leftward-pointing triangle marker will up rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Right , 6L, 0L); // an rightward-pointing triangle marker will up rendered at each point + MV_CREATE_CONSTANT(mvPlotMarker_Cross , 7L, 0L); // a cross marker will be rendered at each point (not filled) + MV_CREATE_CONSTANT(mvPlotMarker_Plus , 8L, 0L); // a plus marker will be rendered at each point (not filled) + MV_CREATE_CONSTANT(mvPlotMarker_Asterisk, 9L, 0L); // a asterisk marker will be rendered at each point (not filled) + + //----------------------------------------------------------------------------- + // Built-in ImPlot Color maps + //----------------------------------------------------------------------------- + MV_CREATE_CONSTANT(mvPlotColormap_Default, 0L, 0L); // ImPlot default colormap (n=10) + MV_CREATE_CONSTANT(mvPlotColormap_Deep , 1L, 0L); // a.k.a. matplotlib "Set1" (n=9) + MV_CREATE_CONSTANT(mvPlotColormap_Dark , 2L, 0L); // a.k.a. matplotlib "Set1" (n=9) + MV_CREATE_CONSTANT(mvPlotColormap_Pastel , 3L, 0L); // a.k.a. matplotlib "Pastel1" (n=9) + MV_CREATE_CONSTANT(mvPlotColormap_Paired , 4L, 0L); // a.k.a. matplotlib "Paired" (n=12) + MV_CREATE_CONSTANT(mvPlotColormap_Viridis, 5L, 0L); // a.k.a. matplotlib "viridis" (n=11) + MV_CREATE_CONSTANT(mvPlotColormap_Plasma , 6L, 0L); // a.k.a. matplotlib "plasma" (n=11) + MV_CREATE_CONSTANT(mvPlotColormap_Hot , 7L, 0L); // a.k.a. matplotlib/MATLAB "hot" (n=11) + MV_CREATE_CONSTANT(mvPlotColormap_Cool , 8L, 0L); // a.k.a. matplotlib/MATLAB "cool" (n=11) + MV_CREATE_CONSTANT(mvPlotColormap_Pink , 9L, 0L); // a.k.a. matplotlib/MATLAB "pink" (n=11) + MV_CREATE_CONSTANT(mvPlotColormap_Jet , 10L, 0L); // a.k.a. MATLAB "jet" (n=11) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_FrameBg, 5L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_PlotBg, 6L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_PlotBorder, 7L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_LegendBg, 8L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_LegendBorder, 9L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_LegendText, 10L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_TitleText, 11L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_InlayText, 12L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_XAxis, 13L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_XAxisGrid, 14L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxis, 15L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxisGrid, 16L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxis2, 17L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxisGrid2, 18L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxis3, 19L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_YAxisGrid3, 20L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_Selection, 21L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_Query, 22L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_Crosshairs, 23L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_FillAlpha, 4L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_BorderSize, 9L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorAlpha, 10L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorTickLenX, 11L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorTickLenY, 11L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorTickLenX, 12L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorTickLenY, 12L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorTickSizeX, 13L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorTickSizeY, 13L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorTickSizeX, 14L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorTickSizeY, 14L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorGridSizeX, 15L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MajorGridSizeY, 15L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorGridSizeX, 16L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MinorGridSizeY, 16L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotPaddingX, 17L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotPaddingY, 17L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LabelPaddingX, 18L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LabelPaddingY, 18L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendPaddingX, 19L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendPaddingY, 19L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendInnerPaddingX, 20L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendInnerPaddingY, 20L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendSpacingX, 21L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_LegendSpacingY, 21L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MousePosPaddingX, 22L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_MousePosPaddingY, 22L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_AnnotationPaddingX, 23L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_AnnotationPaddingY, 23L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_FitPaddingX, 24L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_FitPaddingY, 24L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotDefaultSizeX, 25L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotDefaultSizeY, 25L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotMinSizeX, 26L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_PlotMinSizeY, 26L, 1L); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(add_plot); + MV_ADD_EXTRA_COMMAND(reset_xticks); + MV_ADD_EXTRA_COMMAND(reset_yticks); + MV_ADD_EXTRA_COMMAND(set_xticks); + MV_ADD_EXTRA_COMMAND(set_yticks); + MV_ADD_EXTRA_COMMAND(is_plot_queried); + MV_ADD_EXTRA_COMMAND(get_plot_query_area); + MV_ADD_EXTRA_COMMAND(set_plot_xlimits_auto); + MV_ADD_EXTRA_COMMAND(set_plot_ylimits_auto); + MV_ADD_EXTRA_COMMAND(set_plot_xlimits); + MV_ADD_EXTRA_COMMAND(set_plot_ylimits); + MV_ADD_EXTRA_COMMAND(get_plot_xlimits); + MV_ADD_EXTRA_COMMAND(get_plot_ylimits); + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_None), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Circle), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Square), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Diamond), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Up), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Down), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Left), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Right), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Cross), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Plus), + MV_ADD_GENERAL_CONSTANT(mvPlotMarker_Asterisk), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Default), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Deep), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Dark), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Pastel), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Paired), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Viridis), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Plasma), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Hot), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Cool), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Pink), + MV_ADD_GENERAL_CONSTANT(mvPlotColormap_Jet), + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_FrameBg, mvColor(255, 255, 255, 18)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_PlotBg, mvColor( 0, 0, 0, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_PlotBorder, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_LegendBg, mvColor( 20, 20, 20, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_LegendBorder, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_LegendText, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_TitleText, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_InlayText, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_XAxis, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_XAxisGrid, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxis, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxisGrid, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxis2, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxisGrid2, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxis3, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_YAxisGrid3, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_Selection, mvColor(255, 153, 0, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_Query, mvColor( 0, 255, 112, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Plot_Crosshairs, mvColor(255, 255, 255, 128)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_FillAlpha, 1, 1), + MV_ADD_CONSTANT(mvThemeStyle_Plot_BorderSize, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorAlpha, 0.25, 1), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorTickLenX, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorTickLenY, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorTickLenX, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorTickLenY, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorTickSizeX, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorTickSizeY, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorTickSizeX, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorTickSizeY, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorGridSizeX, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MajorGridSizeY, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorGridSizeX, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MinorGridSizeY, 1, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotPaddingX, 10, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotPaddingY, 10, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LabelPaddingX, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LabelPaddingY, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendPaddingX, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendPaddingY, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendInnerPaddingX, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendInnerPaddingY, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendSpacingX, 5, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_LegendSpacingY, 0, 10), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MousePosPaddingX, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_MousePosPaddingY, 10, 20), + MV_ADD_CONSTANT(mvThemeStyle_Plot_AnnotationPaddingX, 2, 4), + MV_ADD_CONSTANT(mvThemeStyle_Plot_AnnotationPaddingY, 2, 4), + MV_ADD_CONSTANT(mvThemeStyle_Plot_FitPaddingX, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Plot_FitPaddingY, 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotDefaultSizeX, 400, 800), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotDefaultSizeY, 300, 600), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotMinSizeX, 300, 600), + MV_ADD_CONSTANT(mvThemeStyle_Plot_PlotMinSizeY, 255, 510), + MV_END_STYLE_CONSTANTS + + mvPlot(const std::string& name); + + // settings + void SetColorMap (ImPlotColormap colormap); + void resetXTicks (); + void resetYTicks (); + void setXTicks (const std::vector& labels, const std::vector& locations); + void setYTicks (const std::vector& labels, const std::vector& locations); + void draw (ImDrawList* drawlist, float x, float y) override; + void setXLimits (float x_min, float x_max); + void setYLimits (float y_min, float y_max); + void setY2Limits (float y_min, float y_max); + void setY3Limits (float y_min, float y_max); + void setXLimitsAuto (); + void setYLimitsAuto (); + void setY2LimitsAuto (); + void setY3LimitsAuto (); + + [[nodiscard]] bool isPlotQueried() const; + float* getPlotQueryArea(); + + ImPlotFlags getFlags () const { return m_flags; } + ImPlotAxisFlags getXFlags () const { return m_xflags; } + ImPlotAxisFlags getYFlags () const { return m_yflags; } + ImPlotAxisFlags getY2Flags () const { return m_y2flags; } + ImPlotAxisFlags getY3Flags () const { return m_y3flags; } + const std::string& getXAxisName () const { return m_xaxisName; } + const std::string& getYAxisName () const { return m_yaxisName; } + const ImVec2& getXLimits () const { return m_xlimits_actual; } + const ImVec2& getYLimits () const { return m_ylimits_actual; } + const ImVec2& getY2Limits () const { return m_y2limits_actual; } + const ImVec2& getY3Limits () const { return m_y3limits_actual; } + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + bool canChildBeAdded(mvAppItemType type) override; + + private: + + std::string m_xaxisName; + std::string m_yaxisName; + ImPlotFlags m_flags = 0; + ImPlotAxisFlags m_xflags = 0; + ImPlotAxisFlags m_yflags = 0; + ImPlotAxisFlags m_y2flags = 0; + ImPlotAxisFlags m_y3flags = 0; + + ImPlotColormap m_colormap = ImPlotColormap_Deep; + + bool m_setXLimits = false; + bool m_setYLimits = false; + bool m_equalAspectRatios = false; + ImVec2 m_xlimits; + ImVec2 m_xlimits_actual; + ImVec2 m_ylimits; + ImVec2 m_ylimits_actual; + mvCallable m_queryCallback = nullptr; + bool m_queried = false; + float m_queryArea[4] = {0.0f , 0.0f, 0.0f, 0.0f}; + bool m_dirty = false; + + std::vector m_xlabels; + std::vector m_ylabels; + std::vector m_xclabels; // to prevent conversion from string to char* every frame + std::vector m_yclabels; // to prevent conversion from string to char* every frame + std::vector m_xlabelLocations; + std::vector m_ylabelLocations; + + // y axis 2 + bool m_setY2Limits = false; + ImVec2 m_y2limits; + ImVec2 m_y2limits_actual; + + // y axis 3 + bool m_setY3Limits = false; + ImVec2 m_y3limits; + ImVec2 m_y3limits_actual; + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvScatterSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvScatterSeries.cpp new file mode 100644 index 000000000..141fd6332 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvScatterSeries.cpp @@ -0,0 +1,89 @@ +#include +#include "mvScatterSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvScatterSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvScatterSeries::mvScatterSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvScatterSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotScatter(m_label.c_str(), xptr->data(), yptr->data(), xptr->size()); + + } + + void mvScatterSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + } + + void mvScatterSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvScatterSeries.h b/DearPyGui/src/core/AppItems/plots/mvScatterSeries.h new file mode 100644 index 000000000..08a04aea8 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvScatterSeries.h @@ -0,0 +1,51 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvScatterSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvScatterSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvScatterSeries, add_scatter_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Scatter_Outline, ImPlotCol_MarkerOutline, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_Scatter_Fill, ImPlotCol_MarkerFill, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Scatter_Marker, ImPlotStyleVar_Marker, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Scatter_Size, ImPlotStyleVar_MarkerSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Scatter_Weight, ImPlotStyleVar_MarkerWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Scatter_Outline, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_ADD_CONSTANT(mvThemeCol_Plot_Scatter_Fill, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Scatter_Marker, ImPlotMarker_Circle, 9), + MV_ADD_CONSTANT(mvThemeStyle_Plot_Scatter_Size, 4.0f, 12), + MV_ADD_CONSTANT(mvThemeStyle_Plot_Scatter_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvScatterSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvShadeSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvShadeSeries.cpp new file mode 100644 index 000000000..146788e4a --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvShadeSeries.cpp @@ -0,0 +1,100 @@ +#include +#include "mvShadeSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvShadeSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y1"}, + {mvPythonDataType::FloatList, "y2"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvShadeSeries::mvShadeSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvShadeSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* y1ptr; + static const std::vector* y2ptr; + + xptr = &(*m_value.get())[0]; + y1ptr = &(*m_value.get())[1]; + y2ptr = &(*m_value.get())[2]; + + ImPlot::PlotShaded(m_label.c_str(), xptr->data(), y1ptr->data(), + y2ptr->data(), (int)xptr->size()); + + } + + void mvShadeSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y1")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y2")) { valueChanged = true; (*m_value)[2] = ToFloatVect(item); } + + if (valueChanged) + { + if ((*m_value)[1].size() != (*m_value)[2].size()) + { + (*m_value)[2].clear(); + for (auto& item : (*m_value)[1]) + (*m_value)[2].push_back(0.0f); + } + resetMaxMins(); + calculateMaxMins(); + } + } + + void mvShadeSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvShadeSeries.h b/DearPyGui/src/core/AppItems/plots/mvShadeSeries.h new file mode 100644 index 000000000..058ccecf9 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvShadeSeries.h @@ -0,0 +1,39 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvShadeSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvShadeSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvShadeSeries, add_shade_series) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvShadeSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvSimplePlot.cpp b/DearPyGui/src/core/AppItems/plots/mvSimplePlot.cpp new file mode 100644 index 000000000..31051ff8f --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvSimplePlot.cpp @@ -0,0 +1,91 @@ +#include "mvSimplePlot.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvSimplePlot::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "value", "Tuple of float values", "()"}, + {mvPythonDataType::String, "overlay", "overlays text (similar to a plot title)", "''"}, + {mvPythonDataType::Float, "minscale", "used if autoscale is false", "0.0"}, + {mvPythonDataType::Float, "maxscale", "used if autoscale is false", "0.0"}, + {mvPythonDataType::Bool, "histogram", "create a histogram", "False"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before","This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Integer, "width","", "0"}, + {mvPythonDataType::Integer, "height","", "0"}, + {mvPythonDataType::String, "source","", "''"}, + {mvPythonDataType::String, "label", "", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + }, "A simple plot for visualization of a set of values", "None", "Adding Widgets") }); + } + + mvSimplePlot::mvSimplePlot(const std::string& name) + : mvFloatVectPtrBase(name) + { + } + + void mvSimplePlot::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::PushID(this); + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (m_histogram) + ImGui::PlotHistogram(m_label.c_str(), m_value->data(), (int)m_value->size(), 0, m_overlay.c_str(), + m_min, m_max, ImVec2((float)m_width, (float)m_height)); + else + ImGui::PlotLines(m_label.c_str(), m_value->data(), (int)m_value->size(), 0, m_overlay.c_str(), + m_min, m_max, ImVec2((float)m_width, (float)m_height)); + + ImGui::PopID(); + } + + void mvSimplePlot::setValue(const std::vector& value) + { + *m_value = value; + + if (!value.empty()) + { + m_max = m_value->data()[0]; + m_min = m_value->data()[0]; + + for (auto& item : *m_value) + { + if (item > m_max) + m_max = item; + if (item < m_min) + m_min = item; + } + } + } + + void mvSimplePlot::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "overlay")) m_overlay = ToString(item); + if (PyObject* item = PyDict_GetItemString(dict, "minscale")) m_min = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "maxscale")) m_max = ToFloat(item); + if (PyObject* item = PyDict_GetItemString(dict, "histogram")) m_histogram = ToBool(item); + } + + void mvSimplePlot::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "overlay", ToPyString(m_overlay)); + PyDict_SetItemString(dict, "minscale", ToPyFloat(m_min)); + PyDict_SetItemString(dict, "maxscale", ToPyFloat(m_max)); + PyDict_SetItemString(dict, "histogram", ToPyBool(m_histogram)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvSimplePlot.h b/DearPyGui/src/core/AppItems/plots/mvSimplePlot.h new file mode 100644 index 000000000..8b6c2eda4 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvSimplePlot.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include "mvTypeBases.h" + +namespace Marvel{ + + MV_REGISTER_WIDGET(mvSimplePlot, MV_ITEM_DESC_DEFAULT, StorageValueTypes::FloatVect, 1); + class mvSimplePlot : public mvFloatVectPtrBase + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvSimplePlot, add_simple_plot) + + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_Text , 0L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_Border , 5L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_BorderShadow , 6L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_Bg , 7L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_PopupBg , 4L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_Lines , 40L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_LinesHovered , 41L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_Histogram , 42L, 0L); + MV_CREATE_CONSTANT(mvThemeCol_SimplePlot_HistogramHovered , 43L, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_Rounding , 11L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_BorderSize , 12L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_PaddingX , 10L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_PaddingY , 10L, 1L); + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_InnerItemSpacingX , 14L, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_SimplePlot_InnerItemSpacingY , 14L, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_Text, mvColor(255, 255, 255, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_Border, mvColor(110, 110, 128, 128)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_BorderShadow, mvColor( 0, 0, 0, 0)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_Bg, mvColor( 41, 74, 122, 138)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_PopupBg, mvColor( 20, 20, 20, 240)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_Lines, mvColor(156, 156, 156, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_LinesHovered, mvColor(255, 110, 89, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_Histogram, mvColor(230, 179, 0, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_SimplePlot_HistogramHovered, mvColor(255, 153, 0, 255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_BorderSize , 0, 1), + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_Rounding , 0, 12), + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_PaddingX , 8, 20), + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_PaddingY , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_InnerItemSpacingX , 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_SimplePlot_InnerItemSpacingY , 4, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvSimplePlot(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setValue(const std::vector& value); + [[nodiscard]] const std::vector& getValue() const { return *m_value; } + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + std::string m_overlay; + float m_min = 0.0f; + float m_max = 0.0f; + bool m_histogram = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvStairSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvStairSeries.cpp new file mode 100644 index 000000000..6bfe73f5c --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvStairSeries.cpp @@ -0,0 +1,89 @@ +#include +#include "mvStairSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvStairSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvStairSeries::mvStairSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvStairSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotStairs(m_label.c_str(), xptr->data(), yptr->data(), xptr->size()); + + } + + void mvStairSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + } + + void mvStairSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvStairSeries.h b/DearPyGui/src/core/AppItems/plots/mvStairSeries.h new file mode 100644 index 000000000..32980bd6b --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvStairSeries.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvStairSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvStairSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvStairSeries, add_stair_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Stair, ImPlotCol_Line, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Stair_Weight, ImPlotStyleVar_LineWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Stair, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Stair_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvStairSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/plots/mvStemSeries.cpp b/DearPyGui/src/core/AppItems/plots/mvStemSeries.cpp new file mode 100644 index 000000000..7f0e5e24f --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvStemSeries.cpp @@ -0,0 +1,89 @@ +#include +#include "mvStemSeries.h" +#include "mvCore.h" +#include "mvApp.h" +#include "mvItemRegistry.h" +#include "mvImPlotThemeScope.h" + +namespace Marvel { + + void mvStemSeries::InsertParser(std::map* parsers) + { + + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::FloatList, "x"}, + {mvPythonDataType::FloatList, "y"}, + {mvPythonDataType::String, "label", "Overrides 'name' as label", "''"}, + {mvPythonDataType::String, "source", "", "''"}, + {mvPythonDataType::String, "parent", "Parent to add this item to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::Integer, "axis", "", "0"}, + {mvPythonDataType::Bool, "contribute_to_bounds", "", "True"}, + }, "Adds a drag point to a plot.", "None", "Plotting") }); + } + + mvStemSeries::mvStemSeries(const std::string& name) + : mvSeriesBase(name) + { + } + + void mvStemSeries::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImPlotThemeScope scope(this); + + switch (m_axis) + { + case ImPlotYAxis_1: + ImPlot::SetPlotYAxis(ImPlotYAxis_1); + break; + case ImPlotYAxis_2: + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + break; + case ImPlotYAxis_3: + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + break; + default: + break; + } + + static const std::vector* xptr; + static const std::vector* yptr; + + xptr = &(*m_value.get())[0]; + yptr = &(*m_value.get())[1]; + + ImPlot::PlotStems(m_label.c_str(), xptr->data(), yptr->data(), xptr->size()); + + } + + void mvStemSeries::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item); + + bool valueChanged = false; + if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToFloatVect(item); } + if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToFloatVect(item); } + + if (valueChanged) + { + resetMaxMins(); + calculateMaxMins(); + } + } + + void mvStemSeries::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/plots/mvStemSeries.h b/DearPyGui/src/core/AppItems/plots/mvStemSeries.h new file mode 100644 index 000000000..1eaaa0050 --- /dev/null +++ b/DearPyGui/src/core/AppItems/plots/mvStemSeries.h @@ -0,0 +1,51 @@ +#pragma once + +#include "mvPlot.h" + +namespace Marvel { + + MV_REGISTER_WIDGET(mvStemSeries, MV_ITEM_DESC_DEFAULT, StorageValueTypes::Series, 1); + class mvStemSeries : public mvSeriesBase + { + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvStemSeries, add_stem_series) + + MV_CREATE_CONSTANT(mvThemeCol_Plot_Stem_Outline, ImPlotCol_MarkerOutline, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Plot_Stem_Fill, ImPlotCol_MarkerFill, 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Stem_Marker, ImPlotStyleVar_Marker, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Stem_Size, ImPlotStyleVar_MarkerSize, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Plot_Stem_Weight, ImPlotStyleVar_MarkerWeight, 0L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_ADD_CONSTANT(mvThemeCol_Plot_Stem_Outline, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_ADD_CONSTANT(mvThemeCol_Plot_Stem_Fill, mvColor(0, 0, 0, -255), mvColor(0, 0, 0, -255)), + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Plot_Stem_Marker, ImPlotMarker_Diamond, 9), + MV_ADD_CONSTANT(mvThemeStyle_Plot_Stem_Size, 4.0f, 12), + MV_ADD_CONSTANT(mvThemeStyle_Plot_Stem_Weight, 1.0f, 12), + MV_END_STYLE_CONSTANTS + + public: + + mvStemSeries(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/tables/mvTable.cpp b/DearPyGui/src/core/AppItems/tables/mvTable.cpp new file mode 100644 index 000000000..c27cd87d2 --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTable.cpp @@ -0,0 +1,221 @@ +#include "mvTable.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTable::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "header_row", "show headers at the top of the columns", "True"}, + {mvPythonDataType::Integer, "width", "", "0"}, + {mvPythonDataType::Integer, "height", "", "0"}, + {mvPythonDataType::Integer, "inner_width", "", "0"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "resizable", "Enable resizing columns", "False"}, + {mvPythonDataType::Bool, "reorderable", "Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)", "False"}, + {mvPythonDataType::Bool, "hideable", "Enable hiding/disabling columns in context menu.", "False"}, + {mvPythonDataType::Bool, "sortable", "Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate.", "False"}, + {mvPythonDataType::Bool, "context_menu_in_body", "Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow().", "False"}, + {mvPythonDataType::Bool, "row_background", "Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually)", "False"}, + {mvPythonDataType::Bool, "borders_innerH", "Draw horizontal borders between rows.", "False"}, + {mvPythonDataType::Bool, "borders_outerH", "Draw horizontal borders at the top and bottom.", "False"}, + {mvPythonDataType::Bool, "borders_innerV", "Draw vertical borders between columns.", "False"}, + {mvPythonDataType::Bool, "borders_outerV", "Draw vertical borders on the left and right sides.", "False"}, + {mvPythonDataType::Integer, "policy", "sizing policy", "0"}, + {mvPythonDataType::Bool, "no_host_extendX", "Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.", "False"}, + {mvPythonDataType::Bool, "no_host_extendY", "Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.", "False"}, + {mvPythonDataType::Bool, "no_keep_columns_visible", "Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable.", "False"}, + {mvPythonDataType::Bool, "precise_widths", "Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.", "False"}, + {mvPythonDataType::Bool, "no_clip", "Disable clipping rectangle for every individual columns.", "False"}, + {mvPythonDataType::Bool, "pad_outerX", "Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers.", "False"}, + {mvPythonDataType::Bool, "no_pad_outerX", "Default if BordersOuterV is off. Disable outer-most padding.", "False"}, + {mvPythonDataType::Bool, "no_pad_innerX", "Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off).", "False"}, + {mvPythonDataType::Bool, "scrollX", "Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX.", "False"}, + {mvPythonDataType::Bool, "scrollY", "Enable horizontal vertical.", "False"}, + + }, "Adds managed columns.", "None", "Containers") }); + } + + mvTable::mvTable(const std::string& name) + : mvAppItem(name) + { + } + + void mvTable::draw(ImDrawList* drawlist, float x, float y) + { + ScopedID id; + mvImGuiThemeScope scope(this); + mvFontScope fscope(this); + + if (ImGui::BeginTable(m_name.c_str(), m_columns, m_flags, + ImVec2(m_width, m_height), m_inner_width)) + { + + for (auto& item : m_children[0]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); + + item->getState().update(); + } + + if (m_tableHeader) + ImGui::TableHeadersRow(); + + ImGui::TableNextColumn(); + + for (auto& item : m_children[1]) + { + // skip item if it's not shown + if (!item->m_show) + continue; + + // set item width + if (item->m_width != 0) + ImGui::SetNextItemWidth((float)item->m_width); + + item->draw(drawlist, x, y); + + item->getState().update(); + } + ImGui::EndTable(); + } + + } + + void mvTable::onChildAdd(mvRef item) + { + if (item->getType() == mvAppItemType::mvTableColumn) + m_columns++; + } + + void mvTable::onChildRemoved(mvRef item) + { + if (item->getType() == mvAppItemType::mvTableColumn) + m_columns--; + } + + void mvTable::onChildrenRemoved() + { + m_columns = 0; + } + + void mvTable::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "header_row")) m_tableHeader = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "inner_width")) m_inner_width = ToFloat(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + flagop("resizable", ImGuiTableFlags_Resizable, m_flags); + flagop("reorderable", ImGuiTableFlags_Reorderable, m_flags); + flagop("hideable", ImGuiTableFlags_Hideable, m_flags); + flagop("sortable", ImGuiTableFlags_Sortable, m_flags); + flagop("context_menu_in_body", ImGuiTableFlags_ContextMenuInBody, m_flags); + flagop("row_background", ImGuiTableFlags_RowBg, m_flags); + flagop("borders_innerH", ImGuiTableFlags_BordersInnerH, m_flags); + flagop("borders_outerH", ImGuiTableFlags_BordersOuterH, m_flags); + flagop("borders_innerV", ImGuiTableFlags_BordersInnerV, m_flags); + flagop("borders_outerV", ImGuiTableFlags_BordersOuterV, m_flags); + flagop("no_host_extendX", ImGuiTableFlags_NoHostExtendX, m_flags); + flagop("no_host_extendY", ImGuiTableFlags_NoHostExtendY, m_flags); + flagop("no_keep_columns_visible", ImGuiTableFlags_NoKeepColumnsVisible, m_flags); + flagop("precise_widths", ImGuiTableFlags_PreciseWidths, m_flags); + flagop("no_clip", ImGuiTableFlags_NoClip, m_flags); + flagop("pad_outerX", ImGuiTableFlags_PadOuterX, m_flags); + flagop("no_pad_outerX", ImGuiTableFlags_NoPadOuterX, m_flags); + flagop("no_pad_innerX", ImGuiTableFlags_NoPadInnerX, m_flags); + flagop("scrollX", ImGuiTableFlags_ScrollX, m_flags); + flagop("scrollY", ImGuiTableFlags_ScrollY, m_flags); + + if (PyObject* item = PyDict_GetItemString(dict, "policy")) + { + int policy = ToInt(item); + + // remove old flags + m_flags &= ~ImGuiTableFlags_SizingFixedFit; + m_flags &= ~ImGuiTableFlags_SizingFixedSame; + m_flags &= ~ImGuiTableFlags_SizingStretchProp; + m_flags &= ~ImGuiTableFlags_SizingStretchSame; + + if (policy == ImGuiTableFlags_SizingFixedFit) + m_flags |= ImGuiTableFlags_SizingFixedFit; + else if(policy == ImGuiTableFlags_SizingFixedSame) + m_flags |= ImGuiTableFlags_SizingFixedSame; + else if (policy == ImGuiTableFlags_SizingStretchProp) + m_flags |= ImGuiTableFlags_SizingStretchProp; + else + m_flags |= ImGuiTableFlags_SizingStretchSame; + + } +} + + void mvTable::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "inner_width", ToPyInt(m_inner_width)); + PyDict_SetItemString(dict, "header_row", ToPyBool(m_tableHeader)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("resizable", ImGuiTableFlags_Resizable, m_flags); + checkbitset("reorderable", ImGuiTableFlags_Reorderable, m_flags); + checkbitset("hideable", ImGuiTableFlags_Hideable, m_flags); + checkbitset("sortable", ImGuiTableFlags_Sortable, m_flags); + checkbitset("context_menu_in_body", ImGuiTableFlags_ContextMenuInBody, m_flags); + checkbitset("row_background", ImGuiTableFlags_RowBg, m_flags); + checkbitset("borders_innerH", ImGuiTableFlags_BordersInnerH, m_flags); + checkbitset("borders_outerH", ImGuiTableFlags_BordersOuterH, m_flags); + checkbitset("borders_innerV", ImGuiTableFlags_BordersInnerV, m_flags); + checkbitset("borders_outerV", ImGuiTableFlags_BordersOuterV, m_flags); + checkbitset("no_host_extendX", ImGuiTableFlags_NoHostExtendX, m_flags); + checkbitset("no_host_extendY", ImGuiTableFlags_NoHostExtendY, m_flags); + checkbitset("no_keep_columns_visible", ImGuiTableFlags_NoKeepColumnsVisible, m_flags); + checkbitset("precise_widths", ImGuiTableFlags_PreciseWidths, m_flags); + checkbitset("no_clip", ImGuiTableFlags_NoClip, m_flags); + checkbitset("pad_outerX", ImGuiTableFlags_PadOuterX, m_flags); + checkbitset("no_pad_outerX", ImGuiTableFlags_NoPadOuterX, m_flags); + checkbitset("no_pad_innerX", ImGuiTableFlags_NoPadInnerX, m_flags); + checkbitset("scrollX", ImGuiTableFlags_ScrollX, m_flags); + checkbitset("scrollY", ImGuiTableFlags_ScrollY, m_flags); + + if(m_flags & ImGuiTableFlags_SizingFixedFit) + PyDict_SetItemString(dict, "policy", ToPyInt(ImGuiTableFlags_SizingFixedFit)); + else if (m_flags & ImGuiTableFlags_SizingFixedSame) + PyDict_SetItemString(dict, "policy", ToPyInt(ImGuiTableFlags_SizingFixedSame)); + else if (m_flags & ImGuiTableFlags_SizingStretchProp) + PyDict_SetItemString(dict, "policy", ToPyInt(ImGuiTableFlags_SizingStretchProp)); + else if (m_flags & ImGuiTableFlags_SizingStretchSame) + PyDict_SetItemString(dict, "policy", ToPyInt(ImGuiTableFlags_SizingStretchSame)); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/tables/mvTable.h b/DearPyGui/src/core/AppItems/tables/mvTable.h new file mode 100644 index 000000000..bcb158a50 --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTable.h @@ -0,0 +1,81 @@ +#pragma once + +#include "mvTypeBases.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTable, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); + class mvTable : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTable, add_table) + + MV_CREATE_CONSTANT(mvTable_SizingFixedFit, 8192L, 0L); + MV_CREATE_CONSTANT(mvTable_SizingFixedSame, 16384L, 0L); + MV_CREATE_CONSTANT(mvTable_SizingStretchProp, 24576L, 0L); + MV_CREATE_CONSTANT(mvTable_SizingStretchSame, 32768L, 0L); + + MV_CREATE_CONSTANT(mvThemeCol_Table_HeaderBg , ImGuiCol_TableHeaderBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_BorderStrong , ImGuiCol_TableBorderStrong, 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_BorderLight , ImGuiCol_TableBorderLight , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_BorderHovered , ImGuiCol_SeparatorHovered , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_BorderActive , ImGuiCol_SeparatorActive , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_RowBg , ImGuiCol_TableRowBg , 0L); + MV_CREATE_CONSTANT(mvThemeCol_Table_RowBgAlt , ImGuiCol_TableRowBgAlt , 0L); + + MV_CREATE_CONSTANT(mvThemeStyle_Table_CellPaddingX, ImGuiStyleVar_CellPadding, 0L); + MV_CREATE_CONSTANT(mvThemeStyle_Table_CellPaddingY, ImGuiStyleVar_CellPadding, 1L); + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_ADD_GENERAL_CONSTANT(mvTable_SizingFixedFit), + MV_ADD_GENERAL_CONSTANT(mvTable_SizingFixedSame), + MV_ADD_GENERAL_CONSTANT(mvTable_SizingStretchProp), + MV_ADD_GENERAL_CONSTANT(mvTable_SizingStretchSame) + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_HeaderBg, mvColor( 48, 48, 51, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_BorderStrong, mvColor( 79, 79, 89, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_BorderLight, mvColor( 59, 59, 64, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_BorderHovered, mvColor( 26, 102, 191, 199)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_BorderActive, mvColor( 26, 102, 191, 255)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_RowBg, mvColor( 0, 0, 0, 0)), + MV_CREATE_CONSTANT_PAIR(mvThemeCol_Table_RowBgAlt, mvColor(255, 255, 255, 15)) + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_ADD_CONSTANT(mvThemeStyle_Table_CellPaddingX, 4, 20), + MV_ADD_CONSTANT(mvThemeStyle_Table_CellPaddingY, 2, 20), + MV_END_STYLE_CONSTANTS + + public: + + mvTable(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + void onChildAdd(mvRef item) override; + void onChildRemoved(mvRef item) override; + void onChildrenRemoved() override; + + private: + + int m_columns = 0; + int m_inner_width = 0; + ImGuiTableFlags m_flags = 0; + bool m_tableHeader = true; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/tables/mvTableColumn.cpp b/DearPyGui/src/core/AppItems/tables/mvTableColumn.cpp new file mode 100644 index 000000000..6ebda6797 --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTableColumn.cpp @@ -0,0 +1,125 @@ +#include "mvTableColumn.h" +#include "mvTable.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTableColumn::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", ""}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Float, "init_width_or_weight", "init_width_or_weight", "0.0"}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + {mvPythonDataType::Bool, "default_hide", "Default as a hidden/disabled column.", "False"}, + {mvPythonDataType::Bool, "default_sort", "Default as a sorting column.", "False"}, + {mvPythonDataType::Bool, "width_stretch", "Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp).", "False"}, + {mvPythonDataType::Bool, "width_fixed", "Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable).", "False"}, + {mvPythonDataType::Bool, "no_resize", "Disable manual resizing.", "False"}, + {mvPythonDataType::Bool, "no_reorder", "Disable manual reordering this column, this will also prevent other columns from crossing over this column.", "False"}, + {mvPythonDataType::Bool, "no_hide", "Disable ability to hide/disable this column.", "False"}, + {mvPythonDataType::Bool, "no_clip", "Disable clipping for this column (all NoClip columns will render in a same draw command).", "False"}, + {mvPythonDataType::Bool, "no_sort", "Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table).", "False"}, + {mvPythonDataType::Bool, "no_sort_ascending", "Disable ability to sort in the ascending direction.", "False"}, + {mvPythonDataType::Bool, "no_sort_descending", "Disable ability to sort in the descending direction.", "False"}, + {mvPythonDataType::Bool, "no_header_width", "Disable header text width contribution to automatic column width.", "False"}, + {mvPythonDataType::Bool, "prefer_sort_ascending", "Make the initial sort direction Ascending when first sorting on this column (default).", "False"}, + {mvPythonDataType::Bool, "prefer_sort_descending", "Make the initial sort direction Descending when first sorting on this column.", "False"}, + {mvPythonDataType::Bool, "indent_enable", "Use current Indent value when entering cell (default for column 0).", "False"}, + {mvPythonDataType::Bool, "indent_disable", "Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored.", "False"}, + + }, "Changes to next column.", "None", "Containers") }); + } + + mvTableColumn::mvTableColumn(const std::string& name) + : mvAppItem(name) + { + } + + void mvTableColumn::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::TableSetupColumn(m_name.c_str(), m_flags, m_init_width_or_weight); + } + + bool mvTableColumn::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvTable) + return true; + + mvThrowPythonError(1000, "mvTableColumn parent must be a table."); + MV_ITEM_REGISTRY_ERROR("mvTableColumn parent must be a table."); + assert(false); + return false; + } + + void mvTableColumn::setExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "init_width_or_weight")) m_init_width_or_weight = ToFloat(item); + + // helper for bit flipping + auto flagop = [dict](const char* keyword, int flag, int& flags) + { + if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; + }; + + flagop("default_hide", ImGuiTableColumnFlags_DefaultHide, m_flags); + flagop("default_sort", ImGuiTableColumnFlags_DefaultSort, m_flags); + flagop("width_stretch", ImGuiTableColumnFlags_WidthStretch, m_flags); + flagop("width_fixed", ImGuiTableColumnFlags_WidthFixed, m_flags); + flagop("no_resize", ImGuiTableColumnFlags_NoResize, m_flags); + flagop("no_reorder", ImGuiTableColumnFlags_NoReorder, m_flags); + flagop("no_hide", ImGuiTableColumnFlags_NoHide, m_flags); + flagop("no_clip", ImGuiTableColumnFlags_NoClip, m_flags); + flagop("no_sort", ImGuiTableColumnFlags_NoSort, m_flags); + flagop("no_sort_ascending", ImGuiTableColumnFlags_NoSortAscending, m_flags); + flagop("no_sort_descending", ImGuiTableColumnFlags_NoSortDescending, m_flags); + flagop("no_header_width", ImGuiTableColumnFlags_NoHeaderWidth, m_flags); + flagop("prefer_sort_ascending", ImGuiTableColumnFlags_PreferSortAscending, m_flags); + flagop("prefer_sort_descending", ImGuiTableColumnFlags_PreferSortDescending, m_flags); + flagop("indent_enable", ImGuiTableColumnFlags_IndentEnable, m_flags); + flagop("indent_disable", ImGuiTableColumnFlags_IndentDisable, m_flags); + + } + + void mvTableColumn::getExtraConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + PyDict_SetItemString(dict, "init_width_or_weight", ToPyFloat(m_init_width_or_weight)); + + // helper to check and set bit + auto checkbitset = [dict](const char* keyword, int flag, const int& flags) + { + PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); + }; + + checkbitset("default_hide", ImGuiTableColumnFlags_DefaultHide, m_flags); + checkbitset("default_sort", ImGuiTableColumnFlags_DefaultSort, m_flags); + checkbitset("width_stretch", ImGuiTableColumnFlags_WidthStretch, m_flags); + checkbitset("width_fixed", ImGuiTableColumnFlags_WidthFixed, m_flags); + checkbitset("no_resize", ImGuiTableColumnFlags_NoResize, m_flags); + checkbitset("no_reorder", ImGuiTableColumnFlags_NoReorder, m_flags); + checkbitset("no_hide", ImGuiTableColumnFlags_NoHide, m_flags); + checkbitset("no_clip", ImGuiTableColumnFlags_NoClip, m_flags); + checkbitset("no_sort", ImGuiTableColumnFlags_NoSort, m_flags); + checkbitset("no_sort_ascending", ImGuiTableColumnFlags_NoSortAscending, m_flags); + checkbitset("no_sort_descending", ImGuiTableColumnFlags_NoSortDescending, m_flags); + checkbitset("no_header_width", ImGuiTableColumnFlags_NoHeaderWidth, m_flags); + checkbitset("prefer_sort_ascending", ImGuiTableColumnFlags_PreferSortAscending, m_flags); + checkbitset("prefer_sort_descending", ImGuiTableColumnFlags_PreferSortDescending, m_flags); + checkbitset("indent_enable", ImGuiTableColumnFlags_IndentEnable, m_flags); + checkbitset("indent_disable", ImGuiTableColumnFlags_IndentDisable, m_flags); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/tables/mvTableColumn.h b/DearPyGui/src/core/AppItems/tables/mvTableColumn.h new file mode 100644 index 000000000..2ddce068b --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTableColumn.h @@ -0,0 +1,45 @@ +#pragma once + +#include "mvTypeBases.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTableColumn, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 0); + class mvTableColumn : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTableColumn, add_table_column) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + mvTableColumn(const std::string& name); + + void draw(ImDrawList* drawlist, float x, float y) override; + bool isParentCompatible(mvAppItemType type) override; + + void setExtraConfigDict(PyObject* dict) override; + void getExtraConfigDict(PyObject* dict) override; + + private: + + ImGuiTableColumnFlags m_flags = 0; + float m_init_width_or_weight = 0.0f; + + }; + +} diff --git a/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.cpp b/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.cpp new file mode 100644 index 000000000..7f9cd776b --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.cpp @@ -0,0 +1,44 @@ +#include "mvTableNextColumn.h" +#include "mvApp.h" +#include "mvLog.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvFontScope.h" + +namespace Marvel { + + void mvTableNextColumn::InsertParser(std::map* parsers) + { + parsers->insert({ s_command, mvPythonParser({ + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "name", "", "'next_column'"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, + {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, + {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, + + }, "Changes to next column.", "None", "Containers") }); + } + + mvTableNextColumn::mvTableNextColumn(const std::string& name) + : mvAppItem(name) + { + } + + void mvTableNextColumn::draw(ImDrawList* drawlist, float x, float y) + { + ImGui::TableNextColumn(); + } + + bool mvTableNextColumn::isParentCompatible(mvAppItemType type) + { + if (type == mvAppItemType::mvTable) + return true; + + mvThrowPythonError(1000, "mvTableNextColumn parent must be a table."); + MV_ITEM_REGISTRY_ERROR("mvTableNextColumn parent must be a table."); + assert(false); + return false; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.h b/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.h new file mode 100644 index 000000000..1dd24e718 --- /dev/null +++ b/DearPyGui/src/core/AppItems/tables/mvTableNextColumn.h @@ -0,0 +1,40 @@ +#pragma once + +#include "mvTypeBases.h" +#include + +namespace Marvel { + + MV_REGISTER_WIDGET(mvTableNextColumn, MV_ITEM_DESC_DEFAULT, StorageValueTypes::None, 1); + class mvTableNextColumn : public mvAppItem + { + + public: + + static void InsertParser(std::map* parsers); + + MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvTableNextColumn, add_table_next_column) + + MV_START_EXTRA_COMMANDS + MV_END_EXTRA_COMMANDS + + MV_START_GENERAL_CONSTANTS + MV_END_GENERAL_CONSTANTS + + MV_START_COLOR_CONSTANTS + MV_END_COLOR_CONSTANTS + + MV_START_STYLE_CONSTANTS + MV_END_STYLE_CONSTANTS + + public: + + mvTableNextColumn(const std::string& name); + + bool isParentCompatible(mvAppItemType type) override; + + void draw(ImDrawList* drawlist, float x, float y) override; + + }; + +} diff --git a/DearPyGui/src/core/Modules/mvModule.h b/DearPyGui/src/core/Modules/mvModule.h new file mode 100644 index 000000000..0626c4177 --- /dev/null +++ b/DearPyGui/src/core/Modules/mvModule.h @@ -0,0 +1,28 @@ +#pragma once +#include "mvPython.h" +#include +#include + +namespace Marvel { + + template + struct mvModule + { + + static PyMethodDef* GetMethods() + { + return T::GetSubMethods(); + } + + static const std::vector>& GetModuleConstants() + { + return T::GetSubModuleConstants(); + } + + static const std::map& GetModuleParsers() + { + return T::GetSubModuleParsers(); + } + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Modules/mvModule_Core.cpp b/DearPyGui/src/core/Modules/mvModule_Core.cpp new file mode 100644 index 000000000..358c2fbb8 --- /dev/null +++ b/DearPyGui/src/core/Modules/mvModule_Core.cpp @@ -0,0 +1,167 @@ +#include "mvModule_Core.h" +#include "mvApp.h" +#include "mvInput.h" +#include "mvAppLog.h" +#include "mvAppItemCommons.h" +#include "mvViewport.h" +#include "mvFontManager.h" +#include "mvItemRegistry.h" +#include "mvImGuiThemeScope.h" +#include "mvTextureStorage.h" +#include +#include + +namespace Marvel { + + PyMethodDef* mvModule_Core::GetSubMethods() + { + + static std::vector methods; + methods.clear(); + + constexpr_for<1, (int)mvAppItemType::ItemTypeCount, 1>( + [&](auto i) { + using item_type = typename mvItemTypeMap::type; + methods.push_back(item_type::GetMethodDefinition()); + item_type::FillExtraCommands(methods); + }); + + mvViewport::FillExtraCommands(methods); + mvApp::FillExtraCommands(methods); + mvAppItem::FillExtraCommands(methods); + mvItemRegistry::FillExtraCommands(methods); + mvThemeManager::FillExtraCommands(methods); + mvFontManager::FillExtraCommands(methods); + mvTextureStorage::FillExtraCommands(methods); + mvCallbackRegistry::FillExtraCommands(methods); + mvInput::FillExtraCommands(methods); + + methods.push_back({ NULL, NULL, 0, NULL }); + + return methods.data(); + } + + const std::map& mvModule_Core::GetSubModuleParsers() + { + + static auto parsers = std::map(); + + if (parsers.empty()) + { + constexpr_for<1, (int)mvAppItemType::ItemTypeCount, 1>( + [&](auto i) { + using item_type = typename mvItemTypeMap::type; + item_type::InsertParser(&parsers); + }); + + mvViewport::InsertParser(&parsers); + mvApp::InsertParser(&parsers); + mvAppItem::InsertParser(&parsers); + mvItemRegistry::InsertParser(&parsers); + mvThemeManager::InsertParser(&parsers); + mvFontManager::InsertParser(&parsers); + mvTextureStorage::InsertParser(&parsers); + mvCallbackRegistry::InsertParser(&parsers); + mvInput::InsertParser(&parsers); + } + return parsers; + } + + const std::vector>& mvModule_Core::GetSubModuleConstants() + { + static bool First_Run = true; + static std::vector> ModuleConstants; + + if (First_Run) + { + mvInput::InsertConstants(ModuleConstants); + mvTextureStorage::InsertConstants(ModuleConstants); + + auto decodeType = [](long encoded_constant, mvAppItemType* type) + { + *type = (mvAppItemType)(encoded_constant / 1000); + }; + + constexpr_for<1, (int)mvAppItemType::ItemTypeCount, 1>( + [&](auto i) { + + using item_type = typename mvItemTypeMap::type; + + // color constants + for (const auto& item : item_type::GetColorConstants()) + { + ModuleConstants.push_back({ std::get<0>(item), std::get<1>(item) }); + + static mvAppItemType type; + long mvThemeConstant = std::get<1>(item); + decodeType(mvThemeConstant, &type); + mvColor color = std::get<2>(item); + mvColor color_disable = std::get<3>(item); + const std::string& name = std::get<0>(item); + + mvThemeManager::GetColors()[type][mvThemeConstant].first = color; + mvThemeManager::GetColors()[type][mvThemeConstant].second = color_disable; + mvThemeManager::GetColorsPtr().push_back({name, mvThemeConstant, &mvThemeManager::GetColors()[type][mvThemeConstant].first, &mvThemeManager::GetColors()[type][mvThemeConstant].second }); + + } + + // style constants + for (const auto& item : item_type::GetStyleConstants()) + { + ModuleConstants.push_back({ std::get<0>(item), std::get<1>(item) }); + + static mvAppItemType type; + long mvThemeConstant = std::get<1>(item); + decodeType(mvThemeConstant, &type); + float default_val = std::get<2>(item); + float max_val = std::get<3>(item); + const std::string& name = std::get<0>(item); + + mvThemeManager::GetStyles()[type][mvThemeConstant] = default_val; + mvThemeManager::GetStylesPtr().push_back({ name, mvThemeConstant, + &mvThemeManager::GetStyles()[type][mvThemeConstant] , max_val}); + + } + + // general constants + for (const auto& item : item_type::GetGeneralConstants()) + ModuleConstants.push_back({ item.first, item.second }); + + }); + } + + First_Run = false; + return ModuleConstants; + } + + PyMODINIT_FUNC PyInit_core(void) + { + static PyModuleDef dearpyguiModule = { + PyModuleDef_HEAD_INIT, "core", NULL, -1, mvModule_Core::GetMethods(), + NULL, NULL, NULL, NULL + }; + + PyObject* m; + + m = PyModule_Create(&dearpyguiModule); + if (m == NULL) + return NULL; + + const auto& constants = mvModule_Core::GetModuleConstants(); + + // handled in the stub file + for (auto& item : constants) + PyModule_AddIntConstant(m, item.first.c_str(), item.second); + + auto MarvelError = PyErr_NewException("dearpygui.error", NULL, NULL); + Py_XINCREF(MarvelError); + if (PyModule_AddObject(m, "error", MarvelError) < 0) { + Py_XDECREF(MarvelError); + Py_CLEAR(MarvelError); + Py_DECREF(m); + return NULL; + } + + return m; + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/Modules/mvModule_Core.h b/DearPyGui/src/core/Modules/mvModule_Core.h new file mode 100644 index 000000000..762b32a51 --- /dev/null +++ b/DearPyGui/src/core/Modules/mvModule_Core.h @@ -0,0 +1,22 @@ +#pragma once +#include "mvModule.h" + +//----------------------------------------------------------------------------- +// Helper Macro +//----------------------------------------------------------------------------- +#define ADD_PYTHON_FUNCTION(Function) methods.push_back({ #Function, (PyCFunction)Function, METH_VARARGS | METH_KEYWORDS, mvApp::GetApp()->getParsers()[#Function].getDocumentation() }) + +namespace Marvel { + + PyMODINIT_FUNC PyInit_core(void); + + struct mvModule_Core : mvModule + { + static const std::map& GetSubModuleParsers(); + static const std::vector>& GetSubModuleConstants(); + static PyMethodDef* GetSubMethods(); + + }; + + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Modules/mvModule_Core.mm b/DearPyGui/src/core/Modules/mvModule_Core.mm new file mode 100644 index 000000000..2436a3041 --- /dev/null +++ b/DearPyGui/src/core/Modules/mvModule_Core.mm @@ -0,0 +1 @@ +#include "mvModule_Core.cpp" \ No newline at end of file diff --git a/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.cpp b/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.cpp new file mode 100644 index 000000000..7ebc29ea2 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.cpp @@ -0,0 +1,17 @@ +#include "mvGlobalIntepreterLock.h" +#include "mvApp.h" +#include "mvAppLog.h" + +namespace Marvel { + + mvGlobalIntepreterLock::mvGlobalIntepreterLock() + { + m_gstate = PyGILState_Ensure(); + } + + mvGlobalIntepreterLock::~mvGlobalIntepreterLock() + { + PyGILState_Release(m_gstate); + } + +} diff --git a/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.h b/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.h new file mode 100644 index 000000000..a0fb9464b --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvGlobalIntepreterLock.h @@ -0,0 +1,27 @@ +#pragma once + +#include "mvPython.h" +#include + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvGlobalIntepreterLock + // - A convience class to automatically handle aqcuiring and releasing + // python's global intpreter lock between python c api calls. + //----------------------------------------------------------------------------- + class mvGlobalIntepreterLock + { + + public: + + mvGlobalIntepreterLock(); + ~mvGlobalIntepreterLock(); + + private: + + PyGILState_STATE m_gstate; + + }; + +} diff --git a/DearPyGui/src/core/PythonUtilities/mvPyObject.cpp b/DearPyGui/src/core/PythonUtilities/mvPyObject.cpp new file mode 100644 index 000000000..114e9a0f4 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPyObject.cpp @@ -0,0 +1,57 @@ +#include "mvPyObject.h" +#include + +namespace Marvel { + + mvPyObject::mvPyObject(PyObject* rawObject, bool borrowed) + : + m_rawObject(rawObject), + m_borrowed(borrowed), + m_ok(rawObject != nullptr) + { + + } + + mvPyObject::mvPyObject(mvPyObject&& other) + : + m_rawObject(nullptr), + m_borrowed(false), + m_ok(false) + { + std::swap(m_rawObject, other.m_rawObject); + std::swap(m_borrowed, other.m_borrowed); + std::swap(m_ok, other.m_ok); + } + + mvPyObject& mvPyObject::operator=(mvPyObject&& other) + { + if (this != &other) + { + if (m_rawObject != nullptr && !m_borrowed) + Py_XDECREF(m_rawObject); + + std::swap(other.m_rawObject, m_rawObject); + std::swap(other.m_borrowed, m_borrowed); + std::swap(other.m_ok, m_ok); + } + + return *this; + } + + mvPyObject::~mvPyObject() + { + if(!m_borrowed) + Py_XDECREF(m_rawObject); + } + + mvPyObject::operator PyObject*() + { + return m_rawObject; + } + + void mvPyObject::addRef() + { + Py_XINCREF(m_rawObject); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/PythonUtilities/mvPyObject.h b/DearPyGui/src/core/PythonUtilities/mvPyObject.h new file mode 100644 index 000000000..fa14d468e --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPyObject.h @@ -0,0 +1,33 @@ +#pragma once +#include "mvPython.h" + +namespace Marvel { + + class mvPyObject + { + + public: + + mvPyObject(PyObject* rawObject, bool borrowed=false); + mvPyObject(mvPyObject&& other); + mvPyObject& operator=(mvPyObject&& other); + + mvPyObject(const mvPyObject& other) = delete; + mvPyObject& operator=(mvPyObject& other) = delete; + + ~mvPyObject(); + + void addRef(); + bool isOk() const { return m_ok; } + + operator PyObject* (); + + private: + + PyObject* m_rawObject; + bool m_borrowed; + bool m_ok; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp b/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp new file mode 100644 index 000000000..8e1be7599 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp @@ -0,0 +1,44 @@ +#include "mvPython.h" +#include + +namespace Marvel +{ + + void ThrowPythonException(const std::string& message, bool line) + { + + std::string fullMessage = "Line: %d \t" + message; + + int lineno = 0; + if (line) + { + auto f = PyEval_GetFrame(); + if (f) + lineno = PyFrame_GetLineNumber(f); + else + fullMessage.append(" || error occured in a callback"); + } + + PyErr_Format(PyExc_Exception, fullMessage.c_str(), lineno); + PyErr_Print(); + } + + void mvThrowPythonError(int code, const std::string& message, bool line) + { + std::string fullMessage = "Error: [" + std::to_string(code) + std::string("] Line: %d \t") + message; + + int lineno = 0; + if (line) + { + auto f = PyEval_GetFrame(); + if (f) + lineno = PyFrame_GetLineNumber(f); + else + fullMessage.append(" || error occured in a callback"); + } + + PyErr_Format(PyExc_Exception, fullMessage.c_str(), lineno); + PyErr_Print(); + } + +} diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.h b/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.h new file mode 100644 index 000000000..bb7562fdc --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonExceptions.h @@ -0,0 +1,15 @@ +#pragma once + +#include "mvPython.h" +#include + +namespace Marvel +{ + + // older command + void ThrowPythonException(const std::string& message, bool line = true); + + // new command + void mvThrowPythonError(int code, const std::string& message, bool line = true); + +} diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonParser.cpp b/DearPyGui/src/core/PythonUtilities/mvPythonParser.cpp new file mode 100644 index 000000000..60dbe6c46 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonParser.cpp @@ -0,0 +1,247 @@ +#include "mvPythonParser.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include "mvAppLog.h" +#include +#include +#include + +namespace Marvel { + + static char PythonDataTypeSymbol(mvPythonDataType type) + { + switch (type) + { + case mvPythonDataType::String: return 's'; + case mvPythonDataType::Integer: return 'i'; + case mvPythonDataType::Float: return 'f'; + case mvPythonDataType::Double: return 'd'; + case mvPythonDataType::Bool: return 'p'; + case mvPythonDataType::Optional: return '|'; + case mvPythonDataType::KeywordOnly:return '$'; + default: return 'O'; + } + } + + static const char* PythonDataTypeString(mvPythonDataType type) + { + switch (type) + { + case mvPythonDataType::String: return " : str"; + case mvPythonDataType::Integer: return " : int"; + case mvPythonDataType::Float: return " : float"; + case mvPythonDataType::Double: return " : float"; + case mvPythonDataType::Bool: return " : bool"; + case mvPythonDataType::StringList: return " : List[str]"; + case mvPythonDataType::FloatList: return " : List[float]"; + case mvPythonDataType::IntList: return " : List[int]"; + case mvPythonDataType::Optional: return "Optional Arguments\n____________________"; + case mvPythonDataType::KeywordOnly: return "Keyword Only Arguments\n____________________"; + case mvPythonDataType::Callable: return " : Callable"; + case mvPythonDataType::Dict: return " : dict"; + case mvPythonDataType::ListFloatList: return " : List[List[float]]"; + case mvPythonDataType::ListStrList: return " : List[List[str]]"; + case mvPythonDataType::Kwargs: return ""; + case mvPythonDataType::Object: return " : Any"; + default: return " : unknown"; + } + } + + const char* PythonDataTypeActual(mvPythonDataType type) + { + switch (type) + { + case mvPythonDataType::String: return "str"; + case mvPythonDataType::Integer: return "int"; + case mvPythonDataType::Float: return "float"; + case mvPythonDataType::Double: return "float"; + case mvPythonDataType::Bool: return "bool"; + case mvPythonDataType::StringList: return "List[str]"; + case mvPythonDataType::FloatList: return "List[float]"; + case mvPythonDataType::IntList: return "List[int]"; + case mvPythonDataType::Callable: return "Callable"; + case mvPythonDataType::Dict: return "dict"; + case mvPythonDataType::ListFloatList: return "List[List[float]]"; + case mvPythonDataType::ListStrList: return "List[List[str]]"; + case mvPythonDataType::Kwargs: return ""; + case mvPythonDataType::Object: return "Any"; + default: return ""; + } + } + + char mvPythonDataElement::getSymbol() const + { + return PythonDataTypeSymbol(type); + } + + mvPythonParser::mvPythonParser(const std::initializer_list& elements, + std::string about, std::string returnType, std::string category) + : m_elements(elements), m_about(std::move(about)), m_return(std::move(returnType)), m_category(std::move(category)) + { + + for (const auto& element : m_elements) + { + // ignore name types for optional and keyword only + if (element.type != mvPythonDataType::Optional && element.type != mvPythonDataType::KeywordOnly) + m_keywords.push_back(element.name.c_str()); + + // ignore additional optionals + if (m_optional && element.type == mvPythonDataType::Optional) + continue; + else if (element.type == mvPythonDataType::Optional) + m_optional = true; + + if (element.type == mvPythonDataType::KeywordOnly && !m_optional) + { + m_formatstring.push_back('|'); + } + + // ignore additional keywords + if (m_keyword && element.type == mvPythonDataType::KeywordOnly) + continue; + else if (element.type == mvPythonDataType::KeywordOnly) + m_keyword = true; + + + m_formatstring.push_back(element.getSymbol()); + } + + m_formatstring.push_back(0); + m_keywords.push_back(NULL); + + buildDocumentation(); + } + + bool mvPythonParser::parse(PyObject* args, PyObject* kwargs, const char* message, ...) + { + + bool check = true; + + va_list arguments; + va_start(arguments, message); + if (!PyArg_VaParseTupleAndKeywords(args, kwargs, m_formatstring.data(), + const_cast(m_keywords.data()), arguments)) + { + PyErr_Print(); + check = false; + mvAppLog::Show(); + int line = PyFrame_GetLineNumber(PyEval_GetFrame()); + PyObject* ex = PyErr_Format(PyExc_Exception, + "Error parsing DearPyGui %s command on line %d.", message, line); + PyErr_Print(); + Py_XDECREF(ex); + } + + va_end(arguments); + + return check; + } + + void mvPythonParser::buildDocumentation() + { + std::string documentation = m_about + "\n\nReturn Type: " + m_return + "\n"; + + if (!m_elements.empty()) + documentation = documentation + "\n\nParameters\n__________\n\n"; + + bool opfound = false; + bool keyfound = false; + + for (auto& element : m_elements) + { + if (element.type == mvPythonDataType::Optional) + { + if (opfound) + continue; + opfound = true; + } + + if (element.type == mvPythonDataType::KeywordOnly) + { + if (keyfound) + continue; + keyfound = true; + } + + if(element.type != mvPythonDataType::KeywordOnly && element.type != mvPythonDataType::Optional && (opfound || keyfound)) + documentation = documentation + "* " + element.name + PythonDataTypeString(element.type) + " = " + element.default_value + + "\n\t" + element.description + "\n\n"; + else + documentation = documentation + "* " + element.name + PythonDataTypeString(element.type) + + "\n\t" + element.description + "\n\n"; + } + + m_documentation = std::move(documentation); + } + + void GenerateStubFile(const std::string& file) + { + const auto& commands = mvModule_Core::GetModuleParsers(); + + // current date/time based on current system + time_t now = time(0); + + // convert now to string form + char* dt = ctime(&now); + + std::ofstream stub; + stub.open(file); + + stub << "from typing import List, Any, Callable\n"; + stub << "from dearpygui.core import *\n\n"; + stub << "##########################################################\n"; + stub << "# This file is generated automatically by mvPythonParser #\n"; + stub << "##########################################################\n\n"; + stub << "# ~ Dear PyGui Version: " << mvApp::GetVersion() <<"\n"; + + for (const auto& parser : commands) + { + stub << "def " << parser.first << "("; + + auto elements = parser.second.getElements(); + + bool adddefault = false; + + for (size_t i = 0; i < elements.size(); i++) + { + if (elements[i].type == mvPythonDataType::KeywordOnly || elements[i].type == mvPythonDataType::Optional) + { + adddefault = true; + if (elements[i].type == mvPythonDataType::KeywordOnly) + stub << "*, "; + continue; + } + + if (i != elements.size() - 1) + { + if(adddefault) + stub << elements[i].name << ": " << PythonDataTypeActual(elements[i].type) << " = " << elements[i].default_value << ", "; + + else + stub << elements[i].name << ": " << PythonDataTypeActual(elements[i].type) << ", "; + } + else + { + if (elements[i].type == mvPythonDataType::Kwargs) + stub << elements[i].name << ") -> " << + parser.second.getReturnType() << ":\n\t\"\"\"" << parser.second.getAbout() << "\"\"\"\n\t...\n\n"; + + else if (adddefault) + stub << elements[i].name << ": " << PythonDataTypeActual(elements[i].type) << " = " << elements[i].default_value << ") -> " << + parser.second.getReturnType() << ":\n\t\"\"\"" << parser.second.getAbout() << "\"\"\"\n\t...\n\n"; + else + stub << elements[i].name << ": " << PythonDataTypeActual(elements[i].type) << + ") -> " << parser.second.getReturnType() << ":\n\t\"\"\"" << parser.second.getAbout() << "\"\"\"\n\t...\n\n"; + } + } + + if (elements.empty()) + stub << ") -> " << parser.second.getReturnType() << ":\n\t\"\"\"" << parser.second.getAbout() << "\"\"\"\n\t...\n\n"; + + + + } + + stub.close(); + } +} diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonParser.h b/DearPyGui/src/core/PythonUtilities/mvPythonParser.h new file mode 100644 index 000000000..800b8e052 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonParser.h @@ -0,0 +1,89 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvPythonParser +// +// - This class has the following responsibilities: +// +// * Assist in Python tuple parsing and error checks the operation +// * Builds documentation based on PythonDataElement List +// * Categorizes Python Commands +// * Builds the Python parse string +// +// - Should probably be reworked for v1.0 to be clearer +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include "mvCore.h" +#include "mvPython.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // Enums and Helper Functions + //----------------------------------------------------------------------------- + enum class mvPythonDataType + { + None, String, Integer, Float, Bool, StringList, FloatList, Optional, + Object, IntList, KeywordOnly, Double, Callable, Dict, ListFloatList, + ListStrList, Kwargs + }; + + //----------------------------------------------------------------------------- + // mvPythonDataElement + //----------------------------------------------------------------------------- + struct mvPythonDataElement + { + mvPythonDataType type = mvPythonDataType::None; + std::string name = ""; + std::string description; + std::string default_value = "..."; + + [[nodiscard]] char getSymbol() const; + }; + + const char* PythonDataTypeActual(mvPythonDataType type); + + //----------------------------------------------------------------------------- + // mvPythonParser + //----------------------------------------------------------------------------- + class mvPythonParser + { + + public: + + mvPythonParser() = default; + + mvPythonParser(const std::initializer_list& elements, + std::string about = "", std::string returnType = "None", + std::string category = "App"); + + bool parse(PyObject* args, PyObject* kwargs, const char* message, ...); + [[nodiscard]] const char* getDocumentation () const { return m_documentation.c_str(); } + [[nodiscard]] const std::string& getCategory () const { return m_category; } + [[nodiscard]] const std::string& getReturnType () const { return m_return; } + [[nodiscard]] const std::string& getAbout () const { return m_about; } + [[nodiscard]] const std::vector& getElements() const { return m_elements; } + [[nodiscard]] const std::vector& getKeywords () const { return m_keywords; } + + void buildDocumentation(); + + private: + + std::vector m_elements; + std::vector m_formatstring; + std::vector m_keywords; + bool m_optional = false; // check if optional has been found already + bool m_keyword = false; // check if keyword has been found already + std::string m_about; + std::string m_return; + std::string m_documentation; + std::string m_category; + + }; + + void GenerateStubFile(const std::string& file); +} \ No newline at end of file diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.cpp b/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.cpp new file mode 100644 index 000000000..d5dda3571 --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.cpp @@ -0,0 +1,888 @@ +#include "mvPythonTranslator.h" +#include "mvAppLog.h" + +namespace Marvel { + + void UpdatePyIntList(PyObject* pyvalue, const std::vector& value) + { + if (pyvalue == nullptr) + return; + + + if (!PyList_Check(pyvalue)) + { + ThrowPythonException("Python value error"); + return; + } + + + for (Py_ssize_t i = 0; i < PyList_Size(pyvalue); ++i) + { + if (static_cast(i) == value.size()) + break; + PyList_SetItem(pyvalue, i, PyLong_FromLong(value[i])); + } + } + + void UpdatePyFloatList(PyObject* pyvalue, const std::vector& value) + { + if (pyvalue == nullptr) + return; + + + if (!PyList_Check(pyvalue)) + { + ThrowPythonException("Python value error"); + return; + } + + + for (Py_ssize_t i = 0; i < PyList_Size(pyvalue); ++i) + { + if (static_cast(i) == value.size()) + break; + PyList_SetItem(pyvalue, i, PyFloat_FromDouble(value[i])); + } + } + + void UpdatePyStringStringList(PyObject* pyvalue, const std::vector>& value) + { + if (pyvalue == nullptr) + return; + + + if (!PyList_Check(pyvalue)) + { + ThrowPythonException("Python value error"); + return; + } + + + for (Py_ssize_t i = 0; i < PyList_Size(pyvalue); ++i) + { + if (static_cast(i) == value.size()) + break; + PyObject* row = PyList_GetItem(pyvalue, i); + for (Py_ssize_t j = 0; j < PyList_Size(row); ++j) + { + if (static_cast(j) == value[i].size()) + break; + PyList_SetItem(row, i, PyUnicode_FromString(value[i][j].c_str())); + } + } + } + + PyObject* GetPyNone() + { + + Py_RETURN_NONE; + } + + PyObject* ToPyString(const std::string& value) + { + + return PyUnicode_FromString(value.c_str()); + } + + PyObject* ToPyFloat(float value) + { + + return PyFloat_FromDouble(value); + } + + PyObject* ToPyInt(int value) + { + + return PyLong_FromLong(value); + } + + PyObject* ToPyBool(bool value) + { + + return PyBool_FromLong(value); + } + + PyObject* ToPyMPair(int x, float y) + { + + return Py_BuildValue("[if]", x, y); + } + + PyObject* ToPyMTrip(int i, float x, float y) + { + + return Py_BuildValue("[iff]", i, x, y); + } + + PyObject* ToPyPair(float x, float y) + { + + return Py_BuildValue("[ff]", x, y); + } + + PyObject* ToPyPairII(int x, int y) + { + + return Py_BuildValue("[ii]", x, y); + } + + PyObject* ToPyPair(const std::string& x, const std::string& y) + { + + return Py_BuildValue("[ss]", x.c_str(), y.c_str()); + } + + PyObject* ToPyList(const std::vector& value) + { + + + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, PyLong_FromLong(value[i])); + + return result; + } + + PyObject* ToPyList(const std::vector& value) + { + + + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + { + PyObject* item = PyList_New(2); + PyList_SetItem(item, 0, PyFloat_FromDouble (value[i].x)); + PyList_SetItem(item, 1, PyFloat_FromDouble (value[i].y)); + PyList_SetItem(item, i, item); + } + + return result; + } + + PyObject* ToPyList(const std::vector& value) + { + + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, PyFloat_FromDouble(value[i])); + + return result; + } + + PyObject* ToPyList(const std::vector>& value) + { + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, ToPyList(value[i])); + + return result; + } + + PyObject* ToPyList(const std::vector& value) + { + + + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, PyUnicode_FromString(value[i].c_str())); + + return result; + } + + PyObject* ToPyList(const std::vector>& value) + { + + + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, ToPyList(value[i])); + + return result; + } + + PyObject* ToPyList(const std::vector>& value) + { + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, ToPyPairII(value[i].first, value[i].second)); + + return result; + } + + PyObject* ToPyList(const std::vector>& value) + { + PyObject* result = PyList_New(value.size()); + + for (size_t i = 0; i < value.size(); ++i) + PyList_SetItem(result, i, ToPyPair(value[i].first, value[i].second)); + + return result; + } + + PyObject* ToPyColor(const mvColor& color) + { + + + PyObject* result = PyList_New(4); + + PyList_SetItem(result, 0, ToPyFloat((float)color.r)); + PyList_SetItem(result, 1, ToPyFloat((float)color.g)); + PyList_SetItem(result, 2, ToPyFloat((float)color.b)); + PyList_SetItem(result, 3, ToPyFloat((float)color.a)); + + return result; + } + + PyObject* ToPyTime(const tm& time) + { + + PyObject* dict = PyDict_New(); + PyDict_SetItemString(dict, "sec", ToPyInt(time.tm_sec)); + PyDict_SetItemString(dict, "min", ToPyInt(time.tm_min)); + PyDict_SetItemString(dict, "hour", ToPyInt(time.tm_hour)); + PyDict_SetItemString(dict, "month_day", ToPyInt(time.tm_mday)); + PyDict_SetItemString(dict, "month", ToPyInt(time.tm_mon)); + PyDict_SetItemString(dict, "year", ToPyInt(time.tm_year)); + PyDict_SetItemString(dict, "week_day", ToPyInt(time.tm_wday)); + PyDict_SetItemString(dict, "year_day", ToPyInt(time.tm_yday)); + PyDict_SetItemString(dict, "daylight_savings", ToPyInt(time.tm_isdst)); + return dict; + } + + PyObject* ToPyIntList(int* value, int count) + { + + + PyObject* result = PyList_New(count); + + for (int i = 0; i < count; ++i) + PyList_SetItem(result, i, PyLong_FromLong(value[i])); + + return result; + } + + PyObject* ToPyFloatList(float* value, int count) + { + + + PyObject* result = PyList_New(count); + + for (int i = 0; i < count; ++i) + PyList_SetItem(result, i, PyFloat_FromDouble(value[i])); + + return result; + } + + tm ToTime(PyObject* value, const std::string& message) + { + tm result = {}; + if (value == nullptr) + return result; + + if (!PyDict_Check(value)) + { + ThrowPythonException(message); + return result; + } + + if (PyObject* item = PyDict_GetItemString(value, "sec")) result.tm_sec = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "min")) result.tm_min = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "hour")) result.tm_hour = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "month_day")) result.tm_mday = ToInt(item); + else result.tm_mday = 1; + if (PyObject* item = PyDict_GetItemString(value, "month")) result.tm_mon = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "year")) result.tm_year = ToInt(item); + else result.tm_year = 70; + if (PyObject* item = PyDict_GetItemString(value, "week_day")) result.tm_wday = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "year_day")) result.tm_yday = ToInt(item); + if (PyObject* item = PyDict_GetItemString(value, "daylight_savings")) result.tm_isdst = ToInt(item); + + return result; + } + + int ToInt(PyObject* value, const std::string& message) + { + if (value == nullptr) + return 0; + + + if (!PyLong_Check(value)) + { + ThrowPythonException(message); + return 0; + } + + return PyLong_AsLong(value); + } + + float ToFloat(PyObject* value, const std::string& message) + { + if (value == nullptr) + return 0.0f; + + + if (!PyNumber_Check(value)) + { + ThrowPythonException(message); + return 0.0f; + } + + return (float)PyFloat_AsDouble(value); + } + + bool ToBool(PyObject* value, const std::string& message) + { + if (value == nullptr) + return false; + + + if (!PyBool_Check(value)) + { + ThrowPythonException(message); + return false; + } + + return PyLong_AsLong(value); + } + + std::string ToString(PyObject* value, const std::string& message) + { + std::string result; + if (value == nullptr) + return result; + + if (PyUnicode_Check(value)) + { + result = _PyUnicode_AsString(value); + } + else + { + PyObject* str = PyObject_Str(value); + if (str == nullptr) + { + ThrowPythonException(message); + return ""; + } + result = _PyUnicode_AsString(str); + Py_XDECREF(str); + } + + return result; + + } + + std::function BufferViewFunctions(Py_buffer& bufferView) + { + if (strcmp(bufferView.format, "f") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((float*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "d") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((double*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "i") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((int*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "I") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((unsigned int*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "l") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((long*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "L") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((unsigned long*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "B") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((unsigned char*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "b") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((signed char*)bufferView.buf + index); }; + + else if (strcmp(bufferView.format, "c") == 0) + return [](Py_buffer& bufferView, Py_ssize_t index) {return *((char*)bufferView.buf + index); }; + else + { + ThrowPythonException("Unknown buffer type."); + ThrowPythonException(bufferView.format); + ThrowPythonException("Currently supported buffer types f, d, l, B"); + return nullptr; + } + } + + std::vector ToIntVect(PyObject* value, const std::string& message) + { + + std::vector items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + items.resize(PyTuple_Size(value)); + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + items.emplace_back(PyLong_AsLong(PyTuple_GetItem(value, i))); + } + } + + else if (PyList_Check(value)) + { + items.resize(PyList_Size(value)); + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + items[i] = PyLong_AsLong(PyList_GetItem(value, i)); + } + } + + else if (PyObject_CheckBuffer(value)) + { + + + Py_buffer buffer_info; + + if (!PyObject_GetBuffer(value, &buffer_info, + PyBUF_CONTIG_RO | PyBUF_FORMAT)) + { + auto BufferViewer = BufferViewFunctions(buffer_info); + + for (Py_ssize_t i = 0; i < buffer_info.len / buffer_info.itemsize; ++i) + { + items.emplace_back(BufferViewer(buffer_info, i)); + } + } + + PyBuffer_Release(&buffer_info); + } + + else + ThrowPythonException(message); + + + return items; + } + + std::vector ToFloatVect(PyObject* value, const std::string& message) + { + + std::vector items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + items.emplace_back(PyFloat_AsDouble(PyTuple_GetItem(value, i))); + } + } + + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + items.emplace_back(PyFloat_AsDouble(PyList_GetItem(value, i))); + } + } + + else if (PyObject_CheckBuffer(value)) + { + Py_buffer buffer_info; + + if (!PyObject_GetBuffer(value, &buffer_info, + PyBUF_CONTIG_RO | PyBUF_FORMAT)) + { + + auto BufferViewer = BufferViewFunctions(buffer_info); + + for (Py_ssize_t i = 0; i < buffer_info.len / buffer_info.itemsize; ++i) + { + items.emplace_back(BufferViewer(buffer_info, i)); + } + } + PyBuffer_Release(&buffer_info); + } + + else + ThrowPythonException(message); + + + return items; + } + + std::vector ToStringVect(PyObject* value, const std::string& message) + { + + std::vector items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + PyObject* item = PyTuple_GetItem(value, i); + if (PyUnicode_Check(item)) + items.emplace_back(_PyUnicode_AsString(item)); + else + { + PyObject* str = PyObject_Str(item); + items.emplace_back(_PyUnicode_AsString(str)); + Py_XDECREF(str); + } + } + } + + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + PyObject* item = PyList_GetItem(value, i); + if (PyUnicode_Check(item)) + items.emplace_back(_PyUnicode_AsString(item)); + else + { + PyObject* str = PyObject_Str(item); + items.emplace_back(_PyUnicode_AsString(str)); + Py_XDECREF(str); + } + } + } + + else + ThrowPythonException(message); + + + return items; + } + + mvColor ToColor(PyObject* value, const std::string& message) + { + float color[4] = { -1.0f, 0.0f, 0.0f, 1.0f }; + + if (value == nullptr) + return mvColor{ color[0], color[1], color[2], color[3] }; + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + if (i >= 4) + break; + PyObject* item = PyTuple_GetItem(value, i); + if(PyNumber_Check(item)) + color[i] = PyFloat_AsDouble(item)/255.0f; + } + + } + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + if (i >= 4) + break; + PyObject* item = PyList_GetItem(value, i); + if (PyNumber_Check(item)) + color[i] = PyFloat_AsDouble(item)/255.0f; + } + } + + return mvColor{ color[0], color[1], color[2], color[3] }; + } + + mvVec2 ToVec2(PyObject* value, const std::string& message) + { + if (value == nullptr) + return { 0.0f, 0.0f }; + + std::vector result = ToFloatVect(value, message); + + if (result.size() > 1) + return { result[0], result[1] }; + else if (result.size() == 1) + return { result[0], 0.0f }; + else + return { 0.0f, 0.0f }; + } + + mvVec4 ToVec4(PyObject* value, const std::string& message) + { + if (value == nullptr) + return { 0.0f, 0.0f, 0.0f, 0.0f }; + + std::vector result = ToFloatVect(value, message); + + if (result.size() > 3) + return { result[0], result[1], result[2], result[3] }; + else if (result.size() > 2) + return { result[0], result[1], result[2], 0.0f }; + else if (result.size() > 1) + return { result[0], result[1], 0.0f, 0.0f }; + else if (result.size() == 1) + return { result[0], 0.0f, 0.0f, 0.0f }; + else + return { 0.0f, 0.0f, 0.0f, 0.0f }; + } + + std::vector> ToVectPairString(PyObject* value, const std::string& message) + { + std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + PyObject* item = PyTuple_GetItem(value, i); + if (PyTuple_Size(item) == 2) + items.emplace_back(PyUnicode_AsUTF8(PyTuple_GetItem(item, 0)), PyUnicode_AsUTF8(PyTuple_GetItem(item, 1))); + + } + + } + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + PyObject* item = PyList_GetItem(value, i); + if (PyList_Size(item) == 2) + items.emplace_back(PyUnicode_AsUTF8(PyList_GetItem(item, 0)), PyUnicode_AsUTF8(PyList_GetItem(item, 1))); + + } + } + + else + ThrowPythonException(message); + + return items; + } + + std::vector ToVectVec2(PyObject* value, const std::string& message) + { + std::vector items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + items.push_back(ToVec2(PyTuple_GetItem(value, i))); + } + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + items.push_back(ToVec2(PyList_GetItem(value, i))); + } + + else + ThrowPythonException(message); + + return items; + } + + std::pair, std::vector> ToPairVec(PyObject* value, const std::string& message) + { + std::pair, std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + if (PyTuple_Size(value) != 2) ThrowPythonException(message); + items.first = ToFloatVect(PyTuple_GetItem(value, 0), message); + items.second = ToFloatVect(PyTuple_GetItem(value, 1), message); + } + else if (PyList_Check(value)) + { + if (PyList_Size(value) != 2) ThrowPythonException(message); + items.first = ToFloatVect(PyList_GetItem(value, 0), message); + items.second = ToFloatVect(PyList_GetItem(value, 1), message); + } + + else + ThrowPythonException(message); + + return items; + } + + std::vector ToVectVec4(PyObject* value, const std::string& message) + { + std::vector items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + items.push_back(ToVec4(PyTuple_GetItem(value, i))); + } + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + items.push_back(ToVec4(PyList_GetItem(value, i))); + } + + else + ThrowPythonException(message); + + return items; + } + + std::vector> ToVectInt2(PyObject* value, const std::string& message) + { + std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + PyObject* point = PyTuple_GetItem(value, i); + if(PyTuple_Check(point)) + { + if (PyTuple_Size(point) >= 2) { + int x = PyLong_AsLong(PyTuple_GetItem(point, 0)); + int y = PyLong_AsLong(PyTuple_GetItem(point, 1)); + items.emplace_back(x, y); + } + } + else if(PyList_Check(point)) + { + if (PyList_Size(point) >= 2) { + int x = PyLong_AsLong(PyList_GetItem(point, 0)); + int y = PyLong_AsLong(PyList_GetItem(point, 1)); + items.emplace_back(x, y); + } + } + else + items.emplace_back(0, 0); + } + } + + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + PyObject* point = PyList_GetItem(value, i); + if(PyTuple_Check(point)) + { + if (PyTuple_Size(point) >= 2) { + int x = PyLong_AsLong(PyTuple_GetItem(point, 0)); + int y = PyLong_AsLong(PyTuple_GetItem(point, 1)); + items.emplace_back(x, y); + } + } + else if(PyList_Check(point)) + { + if (PyList_Size(point) >= 2) { + int x = PyLong_AsLong(PyList_GetItem(point, 0)); + int y = PyLong_AsLong(PyList_GetItem(point, 1)); + items.emplace_back(x, y); + } + } + else + items.emplace_back(0, 0); + } + } + + else + ThrowPythonException(message); + + return items; + + } + + std::vector> ToVectVectString(PyObject* value, const std::string& message) + { + std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + items.emplace_back(ToStringVect(PyTuple_GetItem(value, i), message)); + } + + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + items.emplace_back(ToStringVect(PyList_GetItem(value, i), message)); + } + + return items; + } + + std::vector> ToVectPairStringFloat(PyObject* value, const std::string& message) + { + std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + { + PyObject* item = PyTuple_GetItem(value, i); + if (PyTuple_Size(item) == 2 && PyNumber_Check(PyTuple_GetItem(item, 1))) + items.emplace_back(PyUnicode_AsUTF8(PyTuple_GetItem(item, 0)), (float)PyFloat_AsDouble(PyTuple_GetItem(item, 1))); + + } + + } + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + { + PyObject* item = PyList_GetItem(value, i); + if (PyList_Size(item) == 2 && PyNumber_Check(PyList_GetItem(item, 1))) + items.emplace_back(PyUnicode_AsUTF8(PyList_GetItem(item, 0)), (float)PyFloat_AsDouble(PyList_GetItem(item, 1))); + + } + } + + else + ThrowPythonException(message); + + return items; + } + + std::vector> ToVectVectFloat(PyObject* value, const std::string& message) + { + std::vector> items; + if (value == nullptr) + return items; + + + if (PyTuple_Check(value)) + { + for (Py_ssize_t i = 0; i < PyTuple_Size(value); ++i) + items.emplace_back(ToFloatVect(PyTuple_GetItem(value, i), message)); + } + + else if (PyList_Check(value)) + { + for (Py_ssize_t i = 0; i < PyList_Size(value); ++i) + items.emplace_back(ToFloatVect(PyList_GetItem(value, i), message)); + } + + return items; + } +} diff --git a/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.h b/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.h new file mode 100644 index 000000000..0752f91dd --- /dev/null +++ b/DearPyGui/src/core/PythonUtilities/mvPythonTranslator.h @@ -0,0 +1,74 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvPythonTranslator +// +// - These functions handle conversion between python/c++ types while also +// ensuring thread safety on the python interpreter +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include "mvCore.h" +#include "mvPython.h" +#include +#include + +namespace Marvel { + + // conversion to python + PyObject* GetPyNone (); + PyObject* ToPyString(const std::string& value); + PyObject* ToPyFloat (float value); + PyObject* ToPyInt (int value); + PyObject* ToPyBool (bool value); + PyObject* ToPyMPair (int x, float y); + PyObject* ToPyMTrip (int i, float x, float y); + PyObject* ToPyPair (float x, float y); + PyObject* ToPyPairII(int x, int y); + PyObject* ToPyPair (const std::string& x, const std::string& y); + PyObject* ToPyList (const std::vector& value); + PyObject* ToPyList (const std::vector& value); + PyObject* ToPyList (const std::vector& value); + PyObject* ToPyList (const std::vector>& value); + PyObject* ToPyList (const std::vector& value); + PyObject* ToPyList (const std::vector>& value); + PyObject* ToPyList (const std::vector>& value); + PyObject* ToPyList (const std::vector>& value); + PyObject* ToPyColor (const mvColor& color); + PyObject* ToPyTime (const tm& time); + + PyObject* ToPyIntList (int* value, int count); + PyObject* ToPyFloatList(float* value, int count); + + // updates + void UpdatePyIntList (PyObject* pyvalue, const std::vector& value); + void UpdatePyFloatList (PyObject* pyvalue, const std::vector& value); + void UpdatePyStringStringList(PyObject* pyvalue, const std::vector>& value); + + // conversion to c++ + int ToInt (PyObject* value, const std::string& message = "Type must be an integer."); + float ToFloat (PyObject* value, const std::string& message = "Type must be a float."); + bool ToBool (PyObject* value, const std::string& message = "Type must be a bool."); + mvColor ToColor (PyObject* value, const std::string& message = "Type must be a list or tuple of ints."); + mvVec2 ToVec2 (PyObject* value, const std::string& message = "Type must be a list or tuple of floats."); + mvVec4 ToVec4 (PyObject* value, const std::string& message = "Type must be a list or tuple of floats."); + std::string ToString(PyObject* value, const std::string& message = "Type must be a string."); + tm ToTime (PyObject* value, const std::string& message = "Type must be a dict"); + + std::vector ToVectVec2 (PyObject* value, const std::string& message = "Type must be a list/tuple of list/tuple."); + std::pair, std::vector>ToPairVec (PyObject* value, const std::string& message = "Type must be a list/tuple of two list/tuple."); + std::vector ToVectVec4 (PyObject* value, const std::string& message = "Type must be a list/tuple of list/tuple."); + std::vector ToIntVect (PyObject* value, const std::string& message = "Type must be a list or tuple of integers."); + std::vector ToFloatVect (PyObject* value, const std::string& message = "Type must be a list or tuple of floats."); + std::vector ToStringVect (PyObject* value, const std::string& message = "Type must be a list or tuple of strings."); + std::vector> ToVectInt2 (PyObject* value, const std::string& message = "Type must be an list/tuple of integer."); + std::vector> ToVectPairString (PyObject* value, const std::string& message = "Type must be an list/tuple of string pairs."); + std::vector> ToVectVectString (PyObject* value, const std::string& message = "Type must be an list/tuple of list/tuple of strings."); + std::vector> ToVectVectFloat (PyObject* value, const std::string& message = "Type must be an list/tuple of list/tuple of strings."); + std::vector> ToVectPairStringFloat(PyObject* value, const std::string& message = "Type must be an list/tuple of str,float pairs."); + + std::function BufferViewFunctions(Py_buffer& bufferView); +} diff --git a/DearPyGui/src/core/Registries/mvCallbackRegistry.cpp b/DearPyGui/src/core/Registries/mvCallbackRegistry.cpp new file mode 100644 index 000000000..d52507144 --- /dev/null +++ b/DearPyGui/src/core/Registries/mvCallbackRegistry.cpp @@ -0,0 +1,670 @@ +#include "mvCallbackRegistry.h" +#include "mvProfiler.h" +#include "mvApp.h" +#include +#include +#include "mvItemRegistry.h" +#include "mvInput.h" +#include "mvAppItemCommons.h" + +namespace Marvel { + + void mvCallbackRegistry::InsertParser(std::map* parsers) + { + + parsers->insert({ "set_start_callback", mvPythonParser({ + {mvPythonDataType::Object, "callback"}, + }, "Callback to run when starting main window.") }); + + parsers->insert({ "set_exit_callback", mvPythonParser({ + {mvPythonDataType::Object, "callback"}, + }, "Callback to run when exiting main window.") }); + + parsers->insert({ "set_accelerator_callback", mvPythonParser({ + {mvPythonDataType::Object, "callback"}, + }, "Callback similar to keypress but used for accelerator keys.") }); + + parsers->insert({ "set_mouse_move_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse move event. Data is the mouse position in local coordinates.", "None", "Input Polling") }); + + parsers->insert({ "set_resize_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "handler", "Callback will be run when window is resized (default is viewport)", "''"}, + }, "Sets a callback for a window resize event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_release_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse release event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_down_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse down event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_drag_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"}, + {mvPythonDataType::Float, "threshold"} + }, "Sets a callback for a mouse drag event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_wheel_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse wheel event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_double_click_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse double click event.", "None", "Input Polling") }); + + parsers->insert({ "set_mouse_click_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a mouse click event.", "None", "Input Polling") }); + + parsers->insert({ "set_key_down_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a key down event.", "None", "Input Polling") }), + + parsers->insert({ "set_key_press_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a key press event.", "None", "Input Polling") }); + + parsers->insert({ "set_key_release_callback", mvPythonParser({ + {mvPythonDataType::Callable, "callback", "Registers a callback"} + }, "Sets a callback for a key release event.", "None", "Input Polling") }); + } + + mvCallbackRegistry::mvCallbackRegistry() + { + mvEventBus::Subscribe(this, mvEVT_FRAME); + mvEventBus::Subscribe(this, mvEVT_PRE_RENDER); + mvEventBus::Subscribe(this, mvEVT_END_FRAME); + mvEventBus::Subscribe(this, 0, mvEVT_CATEGORY_INPUT); + } + + void mvCallbackRegistry::runTasks() + { + while (!m_tasks.empty()) + { + mvFunctionWrapper t; + m_tasks.wait_and_pop(t); + t(); + } + } + + bool mvCallbackRegistry::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvCallbackRegistry::onFrame), mvEVT_FRAME); + dispatcher.dispatch(BIND_EVENT_METH(mvCallbackRegistry::onEndFrame), mvEVT_END_FRAME); + dispatcher.dispatch(BIND_EVENT_METH(mvCallbackRegistry::onRender), mvEVT_PRE_RENDER); + dispatcher.dispatch(BIND_EVENT_METH(mvCallbackRegistry::onInputs), 0, mvEVT_CATEGORY_INPUT); + + return event.handled; + } + + bool mvCallbackRegistry::onFrame(mvEvent& event) + { + + switch (GetEInt(event, "FRAME")) + { + case 3: + addCallback(m_onStartCallback, "Main Application", nullptr); + break; + + default: + break; + } + + return false; + } + + bool mvCallbackRegistry::onEndFrame(mvEvent& event) + { + MV_PROFILE_FUNCTION() + + runTasks(); + + return false; + } + + bool mvCallbackRegistry::onRender(mvEvent& event) + { + MV_PROFILE_FUNCTION() + + runTasks(); + + return false; + } + + bool mvCallbackRegistry::onInputs(mvEvent& event) + { + std::string active = mvApp::GetApp()->getItemRegistry().getActiveWindow(); + + switch (event.type) + { + case mvEVT_KEY_PRESS: + if(m_keyPressCallback) + submitCallback([=]() mutable + { + runCallback(m_acceleratorCallback, active, ToPyInt(GetEInt(event, "KEY"))); + runCallback(m_keyPressCallback, active, ToPyInt(GetEInt(event, "KEY"))); + }); + + break; + + case mvEVT_KEY_DOWN: + if (m_keyDownCallback) + submitCallback([=]() mutable + { + runCallback(m_keyDownCallback, active, ToPyMPair(GetEInt(event, "KEY"), GetEFloat(event, "DURATION"))); + }); + if (m_acceleratorCallback) + submitCallback([=]() mutable + { + runCallback(m_acceleratorCallback, active, ToPyInt(GetEInt(event, "KEY"))); + }); + break; + + case mvEVT_KEY_RELEASE: + if (m_keyReleaseCallback) + submitCallback([=]() mutable + { + runCallback(m_keyReleaseCallback, active, ToPyInt(GetEInt(event, "KEY"))); + }); + break; + + case mvEVT_MOUSE_WHEEL: + if (m_mouseWheelCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseWheelCallback, active, ToPyInt(GetEFloat(event, "DELTA"))); + }); + break; + + case mvEVT_MOUSE_DRAG: + if (m_mouseDragCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseDragCallback, active, + ToPyMTrip(GetEInt(event, "BUTTON"), GetEFloat(event, "X"), GetEFloat(event, "Y"))); + }); + break; + + case mvEVT_MOUSE_CLICK: + if (m_mouseClickCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseClickCallback, active, ToPyInt(GetEInt(event, "BUTTON"))); + }); + break; + + case mvEVT_MOUSE_DOWN: + if (m_mouseDownCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseDownCallback, active, ToPyMPair(GetEInt(event, "BUTTON"), GetEFloat(event, "DURATION"))); + }); + break; + + case mvEVT_MOUSE_DBL_CLK: + if (m_mouseDoubleClickCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseDoubleClickCallback, active, ToPyInt(GetEInt(event, "BUTTON"))); + }); + break; + + case mvEVT_MOUSE_RELEASE: + if (m_mouseReleaseCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseReleaseCallback, active, ToPyInt(GetEInt(event, "BUTTON"))); + }); + break; + + case mvEVT_MOUSE_MOVE: + if (m_mouseMoveCallback) + submitCallback([=]() mutable + { + runCallback(m_mouseMoveCallback, active, ToPyPair(GetEFloat(event, "X"), GetEFloat(event, "Y"))); + }); + break; + + default: + return false; + } + + return true; + } + + bool mvCallbackRegistry::runCallbacks() + { + m_running = true; + + mvGlobalIntepreterLock gil; + + while (m_running) + { + mvFunctionWrapper t2; + Py_BEGIN_ALLOW_THREADS; + m_calls.wait_and_pop(t2); + Py_END_ALLOW_THREADS; + t2(); + m_callCount--; + } + + runCallback(m_onCloseCallback, "Main Application", nullptr); + return true; + } + + void mvCallbackRegistry::addCallback(mvCallable callable, const std::string& sender, mvCallableData data) + { + + if (m_callCount > s_MaxNumberOfCalls) + { + if (data != nullptr) + Py_XDECREF(data); + mvAppLog::LogWarning("[W0001] Too many callbacks already in the queue."); + return; + } + + submitCallback([=]() { + runCallback(callable, sender, data); + }); + } + + void mvCallbackRegistry::runCallback(mvCallable callable, const std::string& sender, PyObject* data) + { + + if (callable == nullptr) + { + //if (data != nullptr) + // Py_XDECREF(data); + return; + } + + if (!PyCallable_Check(callable)) + { + if (data != nullptr) + Py_XDECREF(data); + ThrowPythonException("Callable not callable."); + return; + } + + if (data == nullptr) + { + data = Py_None; + Py_XINCREF(data); + } + + Py_XINCREF(data); + + PyErr_Clear(); + + PyObject* intermediateResult = nullptr; + if (PyCallable_Check(data)) + { + intermediateResult = PyObject_CallObject(data, nullptr); + // check if call succeeded + if (intermediateResult == nullptr) + { + PyErr_Print(); + ThrowPythonException("Callable data failed"); + intermediateResult = data; + } + + // check if error occurred + if (PyErr_Occurred()) + PyErr_Print(); + } + else + intermediateResult = data; + + PyErr_Clear(); + + PyObject* fc = PyObject_GetAttrString(callable, "__code__"); + if (fc) { + PyObject* ac = PyObject_GetAttrString(fc, "co_argcount"); + if (ac) { + int count = PyLong_AsLong(ac); + + if (PyMethod_Check(callable)) + count--; + + if (count > 2) + { + mvPyObject pArgs(PyTuple_New(count)); + PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(sender.c_str())); + PyTuple_SetItem(pArgs, 1, intermediateResult); // steals data, so don't deref + + for (int i = 2; i < count; i++) + PyTuple_SetItem(pArgs, i, GetPyNone()); + + mvPyObject result(PyObject_CallObject(callable, pArgs)); + + // check if call succeeded + if (!result.isOk()) + { + PyErr_Print(); + ThrowPythonException("Callable failed"); + } + + } + else if (count == 2) + { + mvPyObject pArgs(PyTuple_New(2)); + PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(sender.c_str())); + PyTuple_SetItem(pArgs, 1, intermediateResult); // steals data, so don't deref + + mvPyObject result(PyObject_CallObject(callable, pArgs)); + + // check if call succeeded + if (!result.isOk()) + { + PyErr_Print(); + ThrowPythonException("Callable failed"); + } + + } + else if(count == 1) + { + mvPyObject pArgs(PyTuple_New(1)); + PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(sender.c_str())); + + mvPyObject result(PyObject_CallObject(callable, pArgs)); + + // check if call succeeded + if (!result.isOk()) + { + PyErr_Print(); + ThrowPythonException("Callable failed"); + } + } + else + { + mvPyObject result(PyObject_CallObject(callable, nullptr)); + + // check if call succeeded + if (!result.isOk()) + { + PyErr_Print(); + ThrowPythonException("Callable failed"); + } + + + } + Py_DECREF(ac); + + // check if error occurred + if (PyErr_Occurred()) + PyErr_Print(); + } + Py_DECREF(fc); + } + + } + + PyObject* mvCallbackRegistry::set_start_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_start_callback"].parse(args, kwargs, __FUNCTION__, &callback)) + return GetPyNone(); + + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setOnStartCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_exit_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_exit_callback"].parse(args, kwargs, __FUNCTION__, &callback)) + return GetPyNone(); + + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setOnCloseCallback(callback); + }); + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_accelerator_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_accelerator_callback"].parse(args, kwargs, __FUNCTION__, &callback)) + return GetPyNone(); + + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setAcceleratorCallback(callback); + }); + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_down_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_down_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + + if (callback) + Py_XINCREF(callback); + + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseDownCallback(callback); + }); + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_drag_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + float threshold; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_drag_callback"].parse(args, kwargs, __FUNCTION__, + &callback, &threshold)) + return GetPyNone(); + + mvInput::setMouseDragThreshold(threshold); + + if (callback) + Py_XINCREF(callback); + + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseDragCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_double_click_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_double_click_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseDoubleClickCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_click_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_click_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseClickCallback(callback); + }); + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_release_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_release_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseReleaseCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_key_down_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_key_down_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setKeyDownCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_key_press_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_key_press_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setKeyPressCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_key_release_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_key_release_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setKeyReleaseCallback(callback); + }); + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_wheel_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_wheel_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseWheelCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_mouse_move_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback; + + if (!(mvApp::GetApp()->getParsers())["set_mouse_move_callback"].parse(args, kwargs, __FUNCTION__, + &callback)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getCallbackRegistry().setMouseMoveCallback(callback); + }); + + return GetPyNone(); + } + + PyObject* mvCallbackRegistry::set_resize_callback(PyObject* self, PyObject* args, PyObject* kwargs) + { + PyObject* callback = nullptr; + const char* handler = ""; + + if (!(mvApp::GetApp()->getParsers())["set_resize_callback"].parse(args, kwargs, __FUNCTION__, + &callback, &handler)) + return GetPyNone(); + if (callback) + Py_XINCREF(callback); + + + auto fut = mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + + if (std::string(handler).empty()) + { + mvApp::GetApp()->getCallbackRegistry().setResizeCallback(callback); + return std::string(""); + } + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(handler); + + if (item) + { + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_ROOT)) + { + auto windowtype = static_cast(item.get()); + windowtype->setResizeCallback(callback); + } + else + return std::string("Resize callback can only be set for window items"); + } + return std::string(""); + }); + + auto message = fut.get(); + + if (!message.empty()) + ThrowPythonException(message); + + return GetPyNone(); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/Registries/mvCallbackRegistry.h b/DearPyGui/src/core/Registries/mvCallbackRegistry.h new file mode 100644 index 000000000..5edcdce4a --- /dev/null +++ b/DearPyGui/src/core/Registries/mvCallbackRegistry.h @@ -0,0 +1,182 @@ +#pragma once +#include +#include "mvThreadPool.h" +#include "mvApp.h" +#include "mvAppLog.h" + +namespace Marvel { + + static mvCallable SanitizeCallback(mvCallable callback) + { + if (callback == Py_None) + return nullptr; + + return callback; + } + + class mvThreadPool; + + class mvCallbackRegistry : public mvEventHandler + { + + static constexpr const int s_MaxNumberOfCalls = 50; + + struct NewCallback + { + std::string sender; + PyObject* callback; // name of function to run + PyObject* data; // any data need by the function + }; + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(set_start_callback); + MV_CREATE_EXTRA_COMMAND(set_accelerator_callback); + MV_CREATE_EXTRA_COMMAND(set_exit_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_move_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_drag_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_click_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_down_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_double_click_callback); + MV_CREATE_EXTRA_COMMAND(set_key_down_callback); + MV_CREATE_EXTRA_COMMAND(set_key_press_callback); + MV_CREATE_EXTRA_COMMAND(set_key_release_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_release_callback); + MV_CREATE_EXTRA_COMMAND(set_resize_callback); + MV_CREATE_EXTRA_COMMAND(set_mouse_wheel_callback); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(set_start_callback); + MV_ADD_EXTRA_COMMAND(set_accelerator_callback); + MV_ADD_EXTRA_COMMAND(set_exit_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_move_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_drag_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_click_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_down_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_double_click_callback); + MV_ADD_EXTRA_COMMAND(set_key_down_callback); + MV_ADD_EXTRA_COMMAND(set_key_press_callback); + MV_ADD_EXTRA_COMMAND(set_key_release_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_release_callback); + MV_ADD_EXTRA_COMMAND(set_resize_callback); + MV_ADD_EXTRA_COMMAND(set_mouse_wheel_callback); + MV_END_EXTRA_COMMANDS + + public: + + mvCallbackRegistry(); + + bool onEvent (mvEvent& event) override; + bool onFrame (mvEvent& event); + bool onEndFrame(mvEvent& event); + bool onInputs (mvEvent& event); + bool onRender (mvEvent& event); + + void runTasks(); + + void runCallback (mvCallable callback, const std::string& sender, PyObject* data = nullptr); + void addCallback (mvCallable callback, const std::string& sender, mvCallableData data); + + bool runCallbacks(); + + void stop() { m_running = false; } + + template + std::future::type> submit(F f) + { + + typedef typename std::invoke_result::type result_type; + std::packaged_task task(std::move(f)); + std::future res(task.get_future()); + + if (mvApp::IsAppStarted()) + m_tasks.push(std::move(task)); + else + task(); + + return res; + } + + template + std::future::type> submitCallback(F f) + { + + if (m_callCount > s_MaxNumberOfCalls) + { + mvAppLog::LogWarning("Too many callbacks already in the queue."); + return {}; + } + + m_callCount++; + + typedef typename std::invoke_result::type result_type; + std::packaged_task task(std::move(f)); + std::future res(task.get_future()); + + m_calls.push(std::move(task)); + + return res; + } + + //----------------------------------------------------------------------------- + // Callbacks + //----------------------------------------------------------------------------- + void setResizeCallback (mvCallable callback) { m_resizeCallback = SanitizeCallback(callback); } + void setMouseMoveCallback (mvCallable callback) { m_mouseMoveCallback = SanitizeCallback(callback); } + void setOnCloseCallback (mvCallable callback) { m_onCloseCallback = SanitizeCallback(callback); } + void setOnStartCallback (mvCallable callback) { m_onStartCallback = SanitizeCallback(callback); } + void setAcceleratorCallback (mvCallable callback) { m_acceleratorCallback = SanitizeCallback(callback); } + void setMouseClickCallback (mvCallable callback) { m_mouseClickCallback = SanitizeCallback(callback); } + void setMouseDownCallback (mvCallable callback) { m_mouseDownCallback = SanitizeCallback(callback); } + void setMouseDoubleClickCallback(mvCallable callback) { m_mouseDoubleClickCallback = SanitizeCallback(callback); } + void setMouseReleaseCallback (mvCallable callback) { m_mouseReleaseCallback = SanitizeCallback(callback); } + void setMouseWheelCallback (mvCallable callback) { m_mouseWheelCallback = SanitizeCallback(callback); } + void setMouseDragCallback (mvCallable callback) { m_mouseDragCallback = SanitizeCallback(callback); } + void setKeyDownCallback (mvCallable callback) { m_keyDownCallback = SanitizeCallback(callback); } + void setKeyPressCallback (mvCallable callback) { m_keyPressCallback = SanitizeCallback(callback); } + void setKeyReleaseCallback (mvCallable callback) { m_keyReleaseCallback = SanitizeCallback(callback); } + + [[nodiscard]] mvCallable getResizeCallback (){ return m_resizeCallback; } + [[nodiscard]] mvCallable getMouseReleaseCallback (){ return m_mouseReleaseCallback; } + [[nodiscard]] mvCallable getMouseClickCallback (){ return m_mouseClickCallback; } + [[nodiscard]] mvCallable getMouseDownCallback (){ return m_mouseDownCallback; } + [[nodiscard]] mvCallable getMouseDoubleClickCallback(){ return m_mouseDoubleClickCallback; } + [[nodiscard]] mvCallable getMouseDragCallback (){ return m_mouseDragCallback; } + [[nodiscard]] mvCallable getKeyDownCallback (){ return m_keyDownCallback; } + [[nodiscard]] mvCallable getKeyPressCallback (){ return m_keyPressCallback; } + [[nodiscard]] mvCallable getKeyReleaseCallback (){ return m_keyReleaseCallback; } + [[nodiscard]] mvCallable getMouseWheelCallback (){ return m_mouseWheelCallback; } + [[nodiscard]] mvCallable getMouseMoveCallback (){ return m_mouseMoveCallback; } + [[nodiscard]] mvCallable getOnCloseCallback (){ return m_onCloseCallback; } + [[nodiscard]] mvCallable getOnStartCallback (){ return m_onStartCallback; } + [[nodiscard]] mvCallable getAcceleratorCallback (){ return m_acceleratorCallback; } + + private: + + // new callback system + mvQueue m_tasks; + mvQueue m_calls; + std::atomic m_running; + std::atomic m_callCount = 0; + + // input callbacks + mvCallable m_mouseDownCallback = nullptr; + mvCallable m_mouseClickCallback = nullptr; + mvCallable m_mouseReleaseCallback = nullptr; + mvCallable m_mouseDoubleClickCallback = nullptr; + mvCallable m_mouseWheelCallback = nullptr; + mvCallable m_mouseDragCallback = nullptr; + mvCallable m_keyDownCallback = nullptr; + mvCallable m_keyPressCallback = nullptr; + mvCallable m_keyReleaseCallback = nullptr; + mvCallable m_resizeCallback = nullptr; + mvCallable m_mouseMoveCallback = nullptr; + mvCallable m_onCloseCallback = nullptr; + mvCallable m_onStartCallback = nullptr; + mvCallable m_acceleratorCallback = nullptr; // basically the same as the key press callback + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Registries/mvTextureStorage.cpp b/DearPyGui/src/core/Registries/mvTextureStorage.cpp new file mode 100644 index 000000000..764022daa --- /dev/null +++ b/DearPyGui/src/core/Registries/mvTextureStorage.cpp @@ -0,0 +1,495 @@ +#include "mvTextureStorage.h" +#include "mvUtilities.h" +#include +#include "mvApp.h" +#include "implot.h" + +namespace Marvel { + + void mvTextureStorage::InsertConstants(std::vector>& constants) + { + //----------------------------------------------------------------------------- + // Texture Formats + //----------------------------------------------------------------------------- + constants.emplace_back("mvTEX_RGBA_INT" , 0); + constants.emplace_back("mvTEX_RGBA_FLOAT", 1); + constants.emplace_back("mvTEX_RGB_FLOAT" , 2); + constants.emplace_back("mvTEX_RGB_INT" , 3); + constants.emplace_back("mvTEX_BGRA_INT" , 4); + constants.emplace_back("mvTEX_BGRA_FLOAT", 5); + constants.emplace_back("mvTEX_BGR_FLOAT" , 6); + constants.emplace_back("mvTEX_BGR_INT" , 7); + } + + mvTextureStorage::mvTextureStorage() + { + mvEventBus::Subscribe(this, mvEVT_FRAME); + mvEventBus::Subscribe(this, 0, mvEVT_CATEGORY_TEXTURE); + } + + mvTextureStorage::~mvTextureStorage() + { + mvEventBus::UnSubscribe(this); + } + + bool mvTextureStorage::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvTextureStorage::onDecrement), mvEVT_DEC_TEXTURE); + dispatcher.dispatch(BIND_EVENT_METH(mvTextureStorage::onFirstFrame), mvEVT_FRAME); + + return event.handled; + } + + bool mvTextureStorage::onFirstFrame(mvEvent& event) + { + if (GetEInt(event, "FRAME") != 1) + return false; + + addTexture("INTERNAL_DPG_FONT_ATLAS"); + + for (auto& item : m_delayedTextures) + { + if (item.width > 0u) + addTexture(item.name, item.data.data(), item.width, item.height, item.format); + else + addTexture(item.name); + } + + m_delayedTextures.clear(); + + return false; + } + + void mvTextureStorage::refreshAtlas() + { + m_textures.erase("INTERNAL_DPG_FONT_ATLAS"); + addTexture("INTERNAL_DPG_FONT_ATLAS"); + m_dirty = false; + } + + void mvTextureStorage::show_debugger() + { + ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Texture Storage")) + { + + static std::string selection = "INTERNAL_DPG_FONT_ATLAS"; + ImGui::Text("Textures"); + + ImGui::BeginChild("##TextureStorageChild", ImVec2(300, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); + + for (auto& texture : m_textures) + { + bool status = false; + ImGui::Image(texture.second.texture, ImVec2(25, 25)); + ImGui::SameLine(); + if (ImGui::Selectable(texture.first.c_str(), &status)) + selection = texture.first; + + + } + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::BeginGroup(); + + if (!selection.empty()) + { + + ImGui::BeginGroup(); + ImGui::Text("Width: %d", m_textures[selection].width); + ImGui::Text("Height: %d", m_textures[selection].height); + ImGui::Text("Ref Count: %d", m_textures[selection].count); + ImGui::EndGroup(); + + ImGui::SameLine(); + + ImGui::Image(m_textures[selection].texture, ImVec2(m_textures[selection].width, m_textures[selection].height)); + + ImPlot::PushStyleColor(ImPlotCol_FrameBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + if (ImPlot::BeginPlot("##texture plot", 0, 0, ImVec2(-1, -1), + ImPlotFlags_NoTitle | ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_Equal)) + { + ImPlot::PlotImage(selection.c_str(), m_textures[selection].texture, ImPlotPoint(0.0, 0.0), + ImPlotPoint(m_textures[selection].width, m_textures[selection].height)); + ImPlot::EndPlot(); + } + ImPlot::PopStyleColor(); + + } + ImGui::EndGroup(); + + + } + + ImGui::End(); + } + + bool mvTextureStorage::onDecrement(mvEvent& event) + { + decrementTexture(GetEString(event, "NAME")); + return true; + } + + void mvTextureStorage::deleteAllTextures() + { + for (auto& texture : m_textures) + UnloadTexture(texture.first); + + m_textures.clear(); + } + + void mvTextureStorage::addTexture(const std::string& name) + { + // check if texture already exists and if it does + // just increment its reference count + mvTexture* texture = getTexture(name); + if (texture) + { + incrementTexture(name); + return; + } + + if (name == "INTERNAL_DPG_FONT_ATLAS") + { + m_textures.insert({ name, {ImGui::GetIO().Fonts->TexWidth, ImGui::GetIO().Fonts->TexHeight, ImGui::GetIO().Fonts->TexID, 1} }); + } + + mvTexture newTexture = { 0, 0, nullptr, 1 }; + + if (LoadTextureFromFile(name.c_str(), newTexture)) + m_textures.insert({ name, newTexture }); + + } + + void mvTextureStorage::addTexture(const std::string& name, float* data, unsigned width, unsigned height, mvTextureFormat format) + { + // check if texture already exists and if it does + // just increment its reference count + mvTexture* texture = getTexture(name); + if (texture) + { + texture->count = 1; + decrementTexture(name); + } + + mvTexture newTexture = { 0, 0, nullptr, 1 }; + + if (LoadTextureFromArray(name.c_str(), data, width, height, newTexture, format)) + m_textures[name] = newTexture; + + } + + void mvTextureStorage::addDelayedTexture(const std::string& name) + { + m_delayedTextures.push_back({ name, {}, 0u, 0u }); + } + + void mvTextureStorage::addDelayedTexture(const std::string& name, const std::vector& data, unsigned width, unsigned height, mvTextureFormat format) + { + //m_textures.emplace_back(name, data, width, height, format); + m_delayedTextures.push_back({ name, data, width, height, format }); + } + + void mvTextureStorage::incrementTexture(const std::string& name) + { + // see if texture exists + if (m_textures.count(name) == 0) + return; + + if (name != "INTERNAL_DPG_FONT_ATLAS") + m_textures.at(name).count++; + + } + + void mvTextureStorage::decrementTexture(const std::string& name) + { + // see if texture exists + if (m_textures.count(name) == 0) + return; + + if(name != "INTERNAL_DPG_FONT_ATLAS") + m_textures.at(name).count--; + + // remove if count reaches 0 + if (m_textures.at(name).count == 0) + { + UnloadTexture(name); + FreeTexture(m_textures.at(name)); + m_textures.erase(name); + + mvEventBus::Publish(mvEVT_CATEGORY_TEXTURE, mvEVT_DELETE_TEXTURE, { CreateEventArgument("NAME", name) }); + } + } + + mvTexture* mvTextureStorage::getTexture(const std::string& name) + { + if (m_textures.count(name) == 0) + return nullptr; + + return &m_textures.at(name); + } + + unsigned mvTextureStorage::getTextureCount() + { + return (unsigned)m_textures.size(); + } + + void mvTextureStorage::InsertParser(std::map* parsers) + { + + parsers->insert({ "add_texture", mvPythonParser({ + {mvPythonDataType::String, "name"}, + {mvPythonDataType::IntList, "data", "RGBA format"}, + {mvPythonDataType::Integer, "width"}, + {mvPythonDataType::Integer, "height"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Integer, "format", "mvTEX_XXXX_XXXXX constants", "0"}, + }, "Adds a texture. Incorrect format may yield unexpected results.") }); + + parsers->insert({ "decrement_texture", mvPythonParser({ + {mvPythonDataType::String, "name"}, + }, "Decrements a texture.") }); + } + + PyObject* mvTextureStorage::add_texture(PyObject* self, PyObject* args, PyObject* kwargs) + { + // When using RGBA python data is texture data + // When using RGB we must divide out the increment to stay in bouds of the shorter python data + // When using BGRA python data must be reordered to match RGBA + // When using BGR we must divide out the increment to stay in bouds of the shorter python data and also reorder + + const char* name; + PyObject* data; + int width; + int height; + int format = 0; + + if (!(mvApp::GetApp()->getParsers())["add_texture"].parse(args, kwargs, __FUNCTION__, + &name, &data, &width, &height, &format)) + return GetPyNone(); + + mvTextureFormat tformat = (mvTextureFormat)format; + + if (PyList_Check(data)) { + + std::vector fdata; + fdata.resize(width * height * 4); + switch (tformat) + { + case mvTextureFormat::RGBA_FLOAT: + for (size_t i = 0; i < fdata.size(); ++i) + { + fdata[i] = PyFloat_AsDouble(PyList_GetItem(data, i)); + } + break; + + case mvTextureFormat::RGBA_INT: + for (size_t i = 0; i < fdata.size(); ++i) + { + fdata[i] = PyFloat_AsDouble(PyList_GetItem(data, i)) / 255.0f; + } + break; + + case mvTextureFormat::BGRA_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyLong_AsLong(PyList_GetItem(data, i + 2)); + fdata[i + 1] = PyLong_AsLong(PyList_GetItem(data, i + 1)); + fdata[i + 2] = PyLong_AsLong(PyList_GetItem(data, i)); + fdata[i + 3] = PyLong_AsLong(PyList_GetItem(data, i + 3)); + } + break; + + case mvTextureFormat::BGRA_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyLong_AsLong(PyList_GetItem(data, i + 2)) / 255.0f; + fdata[i + 1] = PyLong_AsLong(PyList_GetItem(data, i + 1)) / 255.0f; + fdata[i + 2] = PyLong_AsLong(PyList_GetItem(data, i)) / 255.0f; + fdata[i + 3] = PyLong_AsLong(PyList_GetItem(data, i + 3)) / 255.0f; + } + break; + + case mvTextureFormat::RGB_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3)); + fdata[i + 1] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3 + 1)); + fdata[i + 2] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3 + 2)); + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::RGB_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3)) / 255.0f; + fdata[i + 1] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3 + 1)) / 255.0f; + fdata[i + 2] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3 + 2)) / 255.0f; + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::BGR_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3 + 2)); + fdata[i + 1] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3 + 1)); + fdata[i + 2] = PyFloat_AsDouble(PyList_GetItem(data, (i / 4) * 3)); + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::BGR_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3 + 2)) / 255.0f; + fdata[i + 1] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3 + 1)) / 255.0f; + fdata[i + 2] = PyLong_AsLong(PyList_GetItem(data, (i / 4) * 3)) / 255.0f; + fdata[i + 3] = 1.0f; + } + break; + + default: + return GetPyNone(); + } + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + if (mvApp::IsAppStarted()) + mvApp::GetApp()->getTextureStorage().addTexture(name, fdata.data(), width, height, mvTextureFormat::BGRA_FLOAT); + else + mvApp::GetApp()->getTextureStorage().addDelayedTexture(name, fdata, width, height, mvTextureFormat::RGBA_FLOAT); + + return GetPyNone(); + } + + else if (PyObject_CheckBuffer(data)) + { + Py_buffer buffer_info; + + if (PyObject_GetBuffer(data, &buffer_info, + PyBUF_CONTIG_RO | PyBUF_FORMAT)) + { + PyBuffer_Release(&buffer_info); + return GetPyNone(); + } + + std::vector fdata; + fdata.resize(buffer_info.len / buffer_info.itemsize); + + //This will choose which function to use to interpretate the array. + //Each function interpretates it as a different type. + + auto BufferViewer = BufferViewFunctions(buffer_info); + + switch (tformat) + { + case mvTextureFormat::RGBA_FLOAT: + for (size_t i = 0; i < fdata.size(); ++i) + fdata[i] = BufferViewer(buffer_info, i); + break; + + case mvTextureFormat::RGBA_INT: + for (size_t i = 0; i < fdata.size(); ++i) + fdata[i] = BufferViewer(buffer_info, i) / 255.0f; + break; + + case mvTextureFormat::BGRA_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, i + 2); + fdata[i + 1] = BufferViewer(buffer_info, i + 1); + fdata[i + 2] = BufferViewer(buffer_info, i); + fdata[i + 3] = BufferViewer(buffer_info, i + 3); + } + break; + + case mvTextureFormat::BGRA_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, i + 2) / 255.0f; + fdata[i + 1] = BufferViewer(buffer_info, i + 1) / 255.0f; + fdata[i + 2] = BufferViewer(buffer_info, i) / 255.0f; + fdata[i + 3] = BufferViewer(buffer_info, i + 3) / 255.0f; + } + break; + + case mvTextureFormat::RGB_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, (i / 4) * 3); + fdata[i + 1] = BufferViewer(buffer_info, (i / 4) * 3 + 1); + fdata[i + 2] = BufferViewer(buffer_info, (i / 4) * 3 + 2); + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::RGB_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, (i / 4) * 3) / 255.0f; + fdata[i + 1] = BufferViewer(buffer_info, (i / 4) * 3 + 1) / 255.0f; + fdata[i + 2] = BufferViewer(buffer_info, (i / 4) * 3 + 2) / 255.0f; + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::BGR_FLOAT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, (i / 4) * 3 + 2); + fdata[i + 1] = BufferViewer(buffer_info, (i / 4) * 3 + 1); + fdata[i + 2] = BufferViewer(buffer_info, (i / 4) * 3); + fdata[i + 3] = 1.0f; + } + break; + + case mvTextureFormat::BGR_INT: + for (size_t i = 0; i < fdata.size(); i += 4) + { + fdata[i] = BufferViewer(buffer_info, (i / 4) * 3 + 2) / 255.0f; + fdata[i + 1] = BufferViewer(buffer_info, (i / 4) * 3 + 1) / 255.0f; + fdata[i + 2] = BufferViewer(buffer_info, (i / 4) * 3) / 255.0f; + fdata[i + 3] = 1.0f; + } + break; + + default: + PyBuffer_Release(&buffer_info); + return GetPyNone(); + } + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + if (mvApp::IsAppStarted()) + mvApp::GetApp()->getTextureStorage().addTexture(name, fdata.data(), width, height, tformat); + else + mvApp::GetApp()->getTextureStorage().addDelayedTexture(name, fdata, width, height, tformat); + + PyBuffer_Release(&buffer_info); + return GetPyNone(); + } + + else + { + return GetPyNone(); + } + + } + + PyObject* mvTextureStorage::decrement_texture(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* name; + + if (!(mvApp::GetApp()->getParsers())["decrement_texture"].parse(args, kwargs, __FUNCTION__, + &name)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvEventBus::PublishEndFrame(mvEVT_CATEGORY_TEXTURE, mvEVT_DEC_TEXTURE, { CreateEventArgument("NAME", std::string(name)) }); + + return GetPyNone(); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/Registries/mvTextureStorage.h b/DearPyGui/src/core/Registries/mvTextureStorage.h new file mode 100644 index 000000000..00e3683c7 --- /dev/null +++ b/DearPyGui/src/core/Registries/mvTextureStorage.h @@ -0,0 +1,112 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvTextureStorage +// +// - This class acts as a manager for texture storage. The +// texture storage system serves 2 purposes: +// +// * Allows some image based widgets to share the same textures. +// * Allows some textures to be automatically cleaned up using +// a reference counting system. +// +// - AddTexture will increment an existing texture if it already exists +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include "mvEvents.h" +#include "mvPythonParser.h" +#include "cpp.hint" +#include "mvApp.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvTexture + //----------------------------------------------------------------------------- + struct mvTexture + { + int width = 0; + int height = 0; + void* texture = nullptr; + int count = 0; + }; + + enum class mvTextureFormat + { + RGBA_INT = 0u, + RGBA_FLOAT, + RGB_FLOAT, + RGB_INT, + BGRA_INT, + BGRA_FLOAT, + BGR_FLOAT, + BGR_INT + }; + + //----------------------------------------------------------------------------- + // mvTextureStorage + //----------------------------------------------------------------------------- + class mvTextureStorage : public mvEventHandler + { + + struct CompileTimeTexture + { + std::string name; + std::vector data; + unsigned width; + unsigned height; + mvTextureFormat format; + }; + + public: + + static void InsertConstants(std::vector>& constants); + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(add_texture); + MV_CREATE_EXTRA_COMMAND(decrement_texture); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(add_texture); + MV_ADD_EXTRA_COMMAND(decrement_texture); + MV_END_EXTRA_COMMANDS + + public: + + mvTextureStorage(); + ~mvTextureStorage(); + + bool onEvent (mvEvent& event) override; + bool onFirstFrame(mvEvent& event); + bool onDecrement (mvEvent& event); + + void addTexture (const std::string& name); + void addTexture (const std::string& name, float* data, unsigned width, unsigned height, mvTextureFormat format); + void addDelayedTexture(const std::string& name); + void addDelayedTexture(const std::string& name, const std::vector& data, unsigned width, unsigned height, mvTextureFormat format); + void incrementTexture (const std::string& name); + void decrementTexture (const std::string& name); + mvTexture* getTexture (const std::string& name); + unsigned getTextureCount (); + void deleteAllTextures(); + + // new debugger window + void show_debugger(); + void refreshAtlas(); + void scheduleRefresh() { m_dirty = true; } + bool isValid() const { return !m_dirty; } + + private: + + std::unordered_map m_textures; + std::vector m_delayedTextures; + bool m_dirty = false; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvFontManager.cpp b/DearPyGui/src/core/Theming/mvFontManager.cpp new file mode 100644 index 000000000..74f5d588a --- /dev/null +++ b/DearPyGui/src/core/Theming/mvFontManager.cpp @@ -0,0 +1,455 @@ +#include "mvFontManager.h" +#include +#include +#include +#include "mvApp.h" +#include "mvAppItem.h" +#include "mvCore.h" +#include "mvItemRegistry.h" +#include "mvTextureStorage.h" +#include "mvViewport.h" + +#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) + +// Helper to display a little (?) mark which shows a tooltip when hovered. +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) +static void HelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +// [Internal] Display details for a single font, called by ShowStyleEditor(). +static void NodeFont(ImFont* font) +{ + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + bool font_details_opened = ImGui::TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)", + font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } + if (!font_details_opened) + return; + + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font + ImGui::SameLine(); HelpMarker( + "Note than the default embedded font is NOT meant to be scaled.\n\n" + "Font are currently rendered into bitmaps at a given size at the time of building the atlas. " + "You may oversample them to get some flexibility with scaling. " + "You can also render at multiple sizes and select which one to use at runtime.\n\n" + "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)"); + //ImGui::InputFloat("Font offset", &font->GlyphOffset.y, 1, 1, "%.0f"); + //ImGui::InputInt("Font offset", &font->ConfigData->GlyphOffset.y, 1, 1, "%.0f"); + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar); + ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); + const int surface_sqrt = (int)sqrtf((float)font->MetricsTotalSurface); + ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + if (font->ConfigData) + if (const ImFontConfig* cfg = &font->ConfigData[config_i]) + ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", + config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImU32 glyph_col = ImGui::GetColorU32(ImGuiCol_Text); + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) + { + base += 4096 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (font->FindGlyphNoFallback((ImWchar)(base + n))) + count++; + if (count <= 0) + continue; + if (!ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + float cell_size = font->FontSize * 1; + float cell_spacing = style.ItemSpacing.y; + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (glyph) + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base + n); + ImGui::Separator(); + ImGui::Text("Visible: %d", glyph->Visible); + ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); +} + +// Demo helper function to select among loaded fonts. +// Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one. +static void ShowCustomFontSelector(const char* label) +{ + ImGuiIO& io = ImGui::GetIO(); + ImFont* font_current = ImGui::GetFont(); + if (ImGui::BeginCombo(label, font_current->GetDebugName())) + { + for (int n = 0; n < io.Fonts->Fonts.Size; n++) + { + ImFont* font = io.Fonts->Fonts[n]; + ImGui::PushID((void*)font); + if (ImGui::Selectable(font->GetDebugName(), font == font_current)) + io.FontDefault = font; + ImGui::PopID(); + } + ImGui::EndCombo(); + } +} + +namespace Marvel { + + void mvFontManager::InValidateFontTheme() + { + auto& frontWindows = mvApp::GetApp()->getItemRegistry().getFrontWindows(); + auto& backWindows = mvApp::GetApp()->getItemRegistry().getBackWindows(); + + for (auto& window : frontWindows) + window->inValidateThemeFontCache(); + + for (auto& window : backWindows) + window->inValidateThemeFontCache(); + } + + mvFontManager::mvFontManager() + { + mvEventBus::Subscribe(this, SID("set_font"), mvEVT_CATEGORY_THEMES); + } + + bool mvFontManager::isInvalid() const + { + return m_dirty; + } + + void mvFontManager::addFont(const std::string& font, const std::string& file, int size, const std::string& rangeHint, + const std::vector& chars, const std::vector>& fontGlyphRangeCustom, + const std::vector>& charRemaps) + { + + Font newFont = {}; + newFont.key = font + std::to_string(size); + newFont.name = font; + newFont.file = file; + newFont.rangeHint = rangeHint; + newFont.size = size; + newFont.chars = chars; + newFont.fontGlyphRangeCustom = fontGlyphRangeCustom; + newFont.charRemaps = charRemaps; + newFont.fontPtr = nullptr; + + m_fonts.push_back(newFont); + + m_dirty = true; + mvApp::GetApp()->getTextureStorage().scheduleRefresh(); + } + + ImFont* mvFontManager::getFont(const std::string& font, int size) + { + + if (font.empty()) + return m_font; + + std::string key = font + std::to_string(size); + + for (auto& Font : m_fonts) + { + if (Font.key == key) + return Font.fontPtr; + } + + assert(false); + return nullptr; + } + + void mvFontManager::rebuildAtlas() + { + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->Clear(); + io.FontDefault = io.Fonts->AddFontDefault(); + + // Add character ranges and merge into the previous font + // The ranges array is not copied by the AddFont* functions and is used lazily + // so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). + const ImWchar icons_ranges[] = { 0x0370, 0x03ff, 0 }; // Will not be copied by AddFont* so keep in scope. + + for (auto& font : m_fonts) + { + ImVector ranges; + ImFontGlyphRangesBuilder builder; + + if (font.rangeHint.empty()) builder.AddRanges(io.Fonts->GetGlyphRangesDefault()); + else if (font.rangeHint == std::string("korean")) builder.AddRanges(io.Fonts->GetGlyphRangesKorean()); + else if (font.rangeHint == std::string("japanese")) builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); + else if (font.rangeHint == std::string("chinese_full")) builder.AddRanges(io.Fonts->GetGlyphRangesChineseFull()); + else if (font.rangeHint == std::string("chinese_simplified_common")) builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); + else if (font.rangeHint == std::string("cyrillic")) builder.AddRanges(io.Fonts->GetGlyphRangesCyrillic()); + else if (font.rangeHint == std::string("thai")) builder.AddRanges(io.Fonts->GetGlyphRangesThai()); + else if (font.rangeHint == std::string("vietnamese")) builder.AddRanges(io.Fonts->GetGlyphRangesVietnamese()); + else io.Fonts->AddFontDefault(); + + builder.AddRanges(icons_ranges); // Add one of the default ranges + + for (const auto& range : font.fontGlyphRangeCustom) + builder.AddRanges(range.data()); + for (const auto& charitem : font.chars) + builder.AddChar(charitem); + + builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) + + font.fontPtr = io.Fonts->AddFontFromFileTTF(font.file.c_str(), font.size, nullptr, ranges.Data); + + if (font.fontPtr == nullptr) + { + int line = PyFrame_GetLineNumber(PyEval_GetFrame()); + PyErr_Format(PyExc_Exception, + "Font file %s could not be found. %d c", font.file.c_str(), line); + PyErr_Print(); + io.Fonts->Build(); + } + + for (auto& item : font.charRemaps) + font.fontPtr->AddRemapChar(item.first, item.second); + + io.Fonts->Build(); + } + + InValidateFontTheme(); + } + + void mvFontManager::updateDefaultFont() + { + m_font = getFont(m_fontName, m_size); + m_dirty = false; + ImGuiIO& io = ImGui::GetIO(); + io.FontDefault = m_font; + } + + bool mvFontManager::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvFontManager::onSetFont), SID("set_font")); + return event.handled; + }; + + bool mvFontManager::onSetFont(mvEvent& event) + { + const std::string& widget = GetEString(event, "WIDGET"); + const std::string& font = GetEString(event, "FONT"); + int size = GetEInt(event, "SIZE"); + + if (widget.empty()) + { + InValidateFontTheme(); + m_font = getFont(font, size); + m_size = size; + m_fontName = font; + return true; + } + + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(widget); + if (item) + { + item->inValidateThemeFontCache(); + item->setFont(getFont(font, size)); + } + else + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + ThrowPythonException("Item can not be found"); + }); + } + return true; + } + + void mvFontManager::show_debugger() + { + if (ImGui::Begin("Font Manager")) + { + ShowCustomFontSelector("Fonts##Selector"); + + ImGuiIO& io = ImGui::GetIO(); + ImFontAtlas* atlas = io.Fonts; + HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); + ImGui::PushItemWidth(120); + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont* font = atlas->Fonts[i]; + ImGui::PushID(font); + NodeFont(font); + ImGui::PopID(); + } + if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), tint_col, border_col); + ImGui::TreePop(); + } + + // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. + // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + const float MIN_SCALE = 0.3f; + const float MAX_SCALE = 2.0f; + HelpMarker( + "Those are old settings provided for convenience.\n" + "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " + "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" + "Using those settings here will give you poor quality results."); + if (ImGui::DragFloat("global scale", &getGlobalFontScale(), 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything + getGlobalFontScale() = IM_MAX(getGlobalFontScale(), MIN_SCALE); + ImGui::PopItemWidth(); + } + ImGui::End(); + } + + void mvFontManager::setGlobalFontScale(float scale) + { + m_globalFontScale = scale; + } + + void mvFontManager::InsertParser(std::map* parsers) + { + parsers->insert({ "add_font", mvPythonParser({ + {mvPythonDataType::String, "font", "ttf or otf file"}, + {mvPythonDataType::String, "file", "ttf or otf file"}, + {mvPythonDataType::Optional}, + {mvPythonDataType::Float, "size", "", "13.0"}, + {mvPythonDataType::String, "glyph_ranges", "options: korean, japanese, chinese_full, chinese_simplified_common, cryillic, thai, vietnamese", "''"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::IntList, "custom_glyph_chars", "", "()"}, + {mvPythonDataType::Object, "custom_glyph_ranges", "list of ranges", "List[List[int]]"}, + {mvPythonDataType::Object, "char_remaps", "", "List[List[int]]"}, + }, "Adds additional font.", "None", "Themes and Styles") }); + + parsers->insert({ "set_font", mvPythonParser({ + {mvPythonDataType::String, "font", "ttf or otf file"}, + {mvPythonDataType::Integer, "size", "ttf or otf file"}, + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "item", "", "''"}, + }, "Adds additional font.", "None", "Themes and Styles") }); + + parsers->insert({ "set_global_font_scale", mvPythonParser({ + {mvPythonDataType::Float, "scale", "default is 1.0"} + }, "Changes the global font scale.") }); + + parsers->insert({ "get_global_font_scale", mvPythonParser({ + }, "Returns the global font scale.", "float") }); + } + + PyObject* mvFontManager::add_font(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* font; + const char* file; + float size = 13.0f; + const char* glyph_ranges = ""; + PyObject* custom_glyph_ranges = nullptr; + PyObject* custom_glyph_chars = nullptr; + PyObject* char_remaps = nullptr; + + if (!(mvApp::GetApp()->getParsers())["add_font"].parse(args, kwargs, __FUNCTION__, + &font, &file, &size, &glyph_ranges, &custom_glyph_chars, &custom_glyph_ranges, + &char_remaps)) + return GetPyNone(); + + std::vector custom_chars = ToIntVect(custom_glyph_chars); + std::vector> custom_ranges = ToVectInt2(custom_glyph_ranges); + std::vector> custom_remaps = ToVectInt2(char_remaps); + + std::vector> imgui_custom_ranges; + std::vector imgui_custom_chars; + + for (auto& item : custom_ranges) + imgui_custom_ranges.push_back({ (ImWchar)item.first, (ImWchar)item.second, 0 }); + for (auto& item : custom_chars) + imgui_custom_chars.push_back((ImWchar)item); + + mvApp::GetApp()->getFontManager().addFont(font, file, size, glyph_ranges, imgui_custom_chars, + imgui_custom_ranges, custom_remaps); + + return GetPyNone(); + } + + PyObject* mvFontManager::set_font(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* font = ""; + int size = 0; + const char* item = ""; + + if (!(mvApp::GetApp()->getParsers())["set_font"].parse(args, kwargs, __FUNCTION__, &font, &size, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + mvEventBus::Publish + ( + mvEVT_CATEGORY_THEMES, + SID("set_font"), + { + CreateEventArgument("WIDGET", std::string(item)), + CreateEventArgument("FONT", std::string(font)), + CreateEventArgument("SIZE", size) + } + ); + + return GetPyNone(); + } + + PyObject* mvFontManager::set_global_font_scale(PyObject* self, PyObject* args, PyObject* kwargs) + { + float scale; + + if (!(mvApp::GetApp()->getParsers())["set_global_font_scale"].parse(args, kwargs, __FUNCTION__, &scale)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getFontManager().setGlobalFontScale(scale); + + return GetPyNone(); + } + + PyObject* mvFontManager::get_global_font_scale(PyObject* self, PyObject* args, PyObject* kwargs) + { + return ToPyFloat(mvApp::GetApp()->getFontManager().getGlobalFontScale()); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvFontManager.h b/DearPyGui/src/core/Theming/mvFontManager.h new file mode 100644 index 000000000..e7053a8ab --- /dev/null +++ b/DearPyGui/src/core/Theming/mvFontManager.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include "mvPython.h" +#include "mvEvents.h" +#include "mvApp.h" +#include "cpp.hint" + +struct ImFont; + +namespace Marvel { + + class mvFontManager : public mvEventHandler + { + + struct Font + { + std::string key; + std::string name; + ImFont* fontPtr; + std::string file; + std::string rangeHint; + int size; + std::vector chars; + std::vector> fontGlyphRangeCustom; + std::vector> charRemaps; + }; + + public: + + static void InValidateFontTheme(); + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(add_font); + MV_CREATE_EXTRA_COMMAND(set_font); + MV_CREATE_EXTRA_COMMAND(get_global_font_scale); + MV_CREATE_EXTRA_COMMAND(set_global_font_scale); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(add_font); + MV_ADD_EXTRA_COMMAND(set_font); + MV_ADD_EXTRA_COMMAND(get_global_font_scale); + MV_ADD_EXTRA_COMMAND(set_global_font_scale); + MV_END_EXTRA_COMMANDS + + public: + + mvFontManager(); + + void addFont(const std::string& font, const std::string& file, int size, const std::string& rangeHint, + const std::vector& chars, const std::vector>& fontGlyphRangeCustom, + const std::vector>& charRemaps); + ImFont* getFont(const std::string& font, int size); + void rebuildAtlas(); + bool isInvalid() const; + void updateDefaultFont(); + float& getGlobalFontScale() { return m_globalFontScale; } + void setGlobalFontScale(float scale); + + void show_debugger(); + + private: + + bool onEvent(mvEvent& event) override; + bool onSetFont(mvEvent& event); + + private: + + std::vector m_fonts; + bool m_dirty = false; + + // default + ImFont* m_font = nullptr; + std::string m_fontName; + int m_size = 13; + float m_globalFontScale = 1.0f; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvFontScope.cpp b/DearPyGui/src/core/Theming/mvFontScope.cpp new file mode 100644 index 000000000..b7f844d16 --- /dev/null +++ b/DearPyGui/src/core/Theming/mvFontScope.cpp @@ -0,0 +1,60 @@ +#include "mvFontScope.h" +#include +#include "mvAppItem.h" +#include "mvFontManager.h" + +namespace Marvel { + + mvFontScope::mvFontScope(mvAppItem* item) + { + + if (item->isThemeFontCacheValid()) + { + ImFont* font = item->getCachedFont(); + if (font) + { + ImGui::PushFont(font); + m_valid = true; + } + } + else + { + // search through ancestor tree for font + ImFont* font = nullptr; + mvAppItem* widget = item; + font = widget->getCachedFont(); + while (!mvAppItem::DoesItemHaveFlag(widget, MV_ITEM_DESC_ROOT)) + { + widget = widget->getParent(); + + if (font = widget->getCachedFont()) + break; + } + + if (font == nullptr) + font = mvApp::GetApp()->getFontManager().getFont("", 0); + + if (font) + { + ImGui::PushFont(font); + item->setFont(font); + m_valid = true; + } + + item->setThemeFontCacheValid(); + } + + } + + mvFontScope::~mvFontScope() + { + cleanup(); + } + + void mvFontScope::cleanup() + { + if (m_valid) + ImGui::PopFont(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvFontScope.h b/DearPyGui/src/core/Theming/mvFontScope.h new file mode 100644 index 000000000..7e21ebeda --- /dev/null +++ b/DearPyGui/src/core/Theming/mvFontScope.h @@ -0,0 +1,23 @@ +#pragma once + +namespace Marvel { + + class mvAppItem; + + class mvFontScope + { + + public: + + mvFontScope(mvAppItem* item); + + ~mvFontScope(); + + void cleanup(); + + private: + + bool m_valid = false; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvImGuiThemeScope.h b/DearPyGui/src/core/Theming/mvImGuiThemeScope.h new file mode 100644 index 000000000..b90c39da7 --- /dev/null +++ b/DearPyGui/src/core/Theming/mvImGuiThemeScope.h @@ -0,0 +1,87 @@ +#pragma once + +#include +#include "mvEvents.h" +#include "mvAppItem.h" +#include "composite/mvStyleWindow.h" +#include "mvThemeManager.h" + +namespace Marvel { + + template + class mvImGuiThemeScope + { + + public: + + mvImGuiThemeScope(T* item) + { + + mvThemeColors& colors = item->getCachedThemeColors(); + std::unordered_map& styles = item->getCachedThemeStyles(); + std::unordered_map& styles1 = item->getCachedThemeStyles1(); + std::unordered_map& styles2 = item->getCachedThemeStyles2(); + + if (!item->isThemeColorCacheValid()) + { + SearchAncestorTreeForColors(item, colors); + item->setThemeColorCacheValid(); + } + + if (!item->isThemeStyleCacheValid()) + { + SearchAncestorTreeForStyles(item, styles, styles1, styles2); + item->setThemeStyleCacheValid(); + } + + // decode and push colors to ImGui + libIDCount = colors.size(); + static ImGuiCol imColorID; + if (item->isEnabled()) + { + for (const auto& color : colors) + { + DecodelibID(color.first, &imColorID); + ImGui::PushStyleColor(imColorID, color.second.first.toVec4()); + } + } + else + { + for (const auto& color : colors) + { + DecodelibID(color.first, &imColorID); + ImGui::PushStyleColor(imColorID, color.second.second.toVec4()); + } + } + + // push styles2 and its matching style1 vect to ImGui then push the remaining float styles + StyleIDCount = styles2.size() + styles.size(); + for (const auto& style : styles2) + ImGui::PushStyleVar(style.first, { styles1[style.first], styles2[style.first] }); + + for (const auto& style : styles) + ImGui::PushStyleVar(style.first, style.second); + } + + ~mvImGuiThemeScope() + { + cleanup(); + } + + void cleanup() + { + if (libIDCount > 0) + ImGui::PopStyleColor(libIDCount); + libIDCount = 0; + if (StyleIDCount > 0) + ImGui::PopStyleVar(StyleIDCount); + StyleIDCount = 0; + } + + private: + + int libIDCount = 0; + int StyleIDCount = 0; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvImNodesThemeScope.h b/DearPyGui/src/core/Theming/mvImNodesThemeScope.h new file mode 100644 index 000000000..45994956b --- /dev/null +++ b/DearPyGui/src/core/Theming/mvImNodesThemeScope.h @@ -0,0 +1,76 @@ +#pragma once + +#include +#include "mvEvents.h" +#include "mvAppItem.h" +#include "composite/mvStyleWindow.h" +#include "mvThemeManager.h" +#include + +namespace Marvel { + + template + class mvImNodesThemeScope + { + + public: + + mvImNodesThemeScope(T* item) + { + + mvThemeColors& colors = item->getCachedThemeColors(); + std::unordered_map& styles = item->getCachedThemeStyles(); + std::unordered_map& styles1 = item->getCachedThemeStyles1(); + std::unordered_map& styles2 = item->getCachedThemeStyles2(); + + if (!item->isThemeColorCacheValid()) + { + SearchAncestorTreeForColors(item, colors); + item->setThemeColorCacheValid(); + } + + if (!item->isThemeStyleCacheValid()) + { + SearchAncestorTreeForStyles(item, styles, styles1, styles2); + item->setThemeStyleCacheValid(); + } + + libIDCount = colors.size(); + static int imColorID; + for (auto& color : colors) + { + DecodelibID(color.first, &imColorID); + imnodes::PushColorStyle((imnodes::ColorStyle)imColorID, color.second.first); + } + + StyleIDCount = styles.size(); + + for (const auto& style : styles) + imnodes::PushStyleVar((imnodes::StyleVar)style.first, style.second); + } + + ~mvImNodesThemeScope() + { + cleanup(); + } + + void cleanup() + { + while (libIDCount > 0) + { + imnodes::PopColorStyle(); + --libIDCount; + } + while (StyleIDCount > 0) + { + imnodes::PopStyleVar(); + --StyleIDCount; + } + } + + private: + int libIDCount = 0; + int StyleIDCount = 0; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvImPlotThemeScope.h b/DearPyGui/src/core/Theming/mvImPlotThemeScope.h new file mode 100644 index 000000000..336fd3efe --- /dev/null +++ b/DearPyGui/src/core/Theming/mvImPlotThemeScope.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include "mvEvents.h" +#include "mvAppItem.h" +#include "composite/mvStyleWindow.h" +#include "mvThemeManager.h" + +namespace Marvel { + + template + class mvImPlotThemeScope + { + + public: + + mvImPlotThemeScope(T* item) + { + + mvThemeColors& colors = item->getCachedThemeColors(); + std::unordered_map& styles = item->getCachedThemeStyles(); + std::unordered_map& styles1 = item->getCachedThemeStyles1(); + std::unordered_map& styles2 = item->getCachedThemeStyles2(); + + if (!item->isThemeColorCacheValid()) + { + SearchAncestorTreeForColors(item, colors); + item->setThemeColorCacheValid(); + } + + if (!item->isThemeStyleCacheValid()) + { + SearchAncestorTreeForStyles(item, styles, styles1, styles2); + item->setThemeStyleCacheValid(); + } + + libIDCount = colors.size(); + static ImPlotCol imColorID; + for (const auto& color : colors) + { + DecodelibID(color.first, &imColorID); + ImPlot::PushStyleColor(imColorID, color.second.first.toVec4()); + } + + StyleIDCount = styles2.size() + styles.size(); + for (const auto& style : styles2) + ImPlot::PushStyleVar((ImPlotStyleVar)style.first, { styles1[style.first], styles2[style.first] }); + + for (const auto& style : styles) + { + if((ImPlotStyleVar)style.first == ImPlotStyleVar_Marker) + ImPlot::PushStyleVar((ImPlotStyleVar)style.first, (int)style.second); + else + ImPlot::PushStyleVar((ImPlotStyleVar)style.first, style.second); + } + } + + ~mvImPlotThemeScope() + { + cleanup(); + } + + void cleanup() + { + if (libIDCount > 0) + ImPlot::PopStyleColor(libIDCount); + libIDCount = 0; + if (StyleIDCount > 0) + ImPlot::PopStyleVar(StyleIDCount); + StyleIDCount = 0; + } + + private: + int libIDCount = 0; + int StyleIDCount = 0; + + }; +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvThemeManager.cpp b/DearPyGui/src/core/Theming/mvThemeManager.cpp new file mode 100644 index 000000000..f23cbf003 --- /dev/null +++ b/DearPyGui/src/core/Theming/mvThemeManager.cpp @@ -0,0 +1,265 @@ +#include "mvThemeManager.h" +#include "imgui.h" +#include "mvAppItemCommons.h" +#include "mvCore.h" +#include "mvItemRegistry.h" + +namespace Marvel { + + std::vector> mvThemeManager::s_acolors; + std::vector> mvThemeManager::s_astyles; + std::unordered_map mvThemeManager::s_colors; + std::unordered_map mvThemeManager::s_styles; + + void mvThemeManager::InsertParser(std::map* parsers) + { + + parsers->insert({ "set_theme_color", mvPythonParser({ + {mvPythonDataType::Integer, "constant", "mvThemeCol_* constants"}, + {mvPythonDataType::FloatList, "color"}, + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "item", "", "''"} + }, "Sets a color of a theme item for when the item is enabled.", "None", "Themes and Styles") }); + + parsers->insert({ "set_theme_color_disabled", mvPythonParser({ + {mvPythonDataType::Integer, "constant", "mvThemeCol_* constants"}, + {mvPythonDataType::FloatList, "color"}, + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "item", "", "''"} + }, "Sets a color of a theme item for when the item is disabled.", "None", "Themes and Styles") }); + + parsers->insert({ "set_theme_style", mvPythonParser({ + {mvPythonDataType::Integer, "constant", "mvThemeStyle_* constants"}, + {mvPythonDataType::Float, "style"}, + {mvPythonDataType::Optional}, + {mvPythonDataType::String, "item", "", "''"} + }, "Sets a style of a theme item.", "None", "Themes and Styles") }); + + } + + void mvThemeManager::InValidateColorTheme() + { + auto& frontWindows = mvApp::GetApp()->getItemRegistry().getFrontWindows(); + auto& backWindows = mvApp::GetApp()->getItemRegistry().getBackWindows(); + + for (auto& window : frontWindows) + window->inValidateThemeColorCache(); + + for (auto& window : backWindows) + window->inValidateThemeColorCache(); + } + + void mvThemeManager::InValidateStyleTheme() + { + auto& frontWindows = mvApp::GetApp()->getItemRegistry().getFrontWindows(); + auto& backWindows = mvApp::GetApp()->getItemRegistry().getBackWindows(); + + for (auto& window : frontWindows) + window->inValidateThemeStyleCache(); + + for (auto& window : backWindows) + window->inValidateThemeStyleCache(); + } + + mvThemeManager::mvThemeManager() + { + mvEventBus::Subscribe(this, SID("color_change"), mvEVT_CATEGORY_THEMES); + mvEventBus::Subscribe(this, SID("style_change"), mvEVT_CATEGORY_THEMES); + } + + mvThemeManager::~mvThemeManager() + { + mvEventBus::UnSubscribe(this); + } + + bool mvThemeManager::onEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvThemeManager::add_style), SID("style_change")); + dispatcher.dispatch(BIND_EVENT_METH(mvThemeManager::add_color), SID("color_change")); + return event.handled; + }; + + bool mvThemeManager::add_color(mvEvent& event) + { + static mvAppItemType type; + long mvThemeConstant = GetELong(event, "ID"); + DecodeType(mvThemeConstant, &type); + mvColor color = GetEColor(event, "COLOR"); + const std::string& widget = GetEString(event, "WIDGET"); + bool enabled = GetEBool(event, "ENABLED"); + + //fills out the app's root theme if no item was given + if (widget.empty()) + { + if (enabled) GetColors()[type][mvThemeConstant].first = color; + else GetColors()[type][mvThemeConstant].second = color; + InValidateColorTheme(); + return true; + } + + //check widget can take color and apply + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(widget); + if (item) + { + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER) || item->getType() == type) + { + if (enabled) item->getColors()[type][mvThemeConstant].first = color; + else item->getColors()[type][mvThemeConstant].second = color; + + item->inValidateThemeColorCache(); + } + else + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + ThrowPythonException("Item type does not except this color constant."); + }); + } + } + else + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + ThrowPythonException("Item can not be found"); + }); + } + return true; + } + + bool mvThemeManager::add_style(mvEvent& event) + { + static mvAppItemType type; + long mvThemeConstant = GetELong(event, "ID"); + DecodeType(mvThemeConstant, &type); + float style = GetEFloat(event, "STYLE"); + const std::string& widget = GetEString(event, "WIDGET"); + + //fills out the app's root theme if no item was given + if (widget.empty()) + { + GetStyles()[type][mvThemeConstant] = style; + InValidateStyleTheme(); + return true; + } + + //check widget can take style and apply + mvRef item = mvApp::GetApp()->getItemRegistry().getItem(widget); + if (item) + { + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER) || item->getType() == type) + { + item->getStyles()[type][mvThemeConstant] = style; + item->inValidateThemeStyleCache(); + } + else + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + ThrowPythonException("Item type does not except this style constant."); + }); + } + } + else + { + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + ThrowPythonException("Item can not be found"); + }); + } + return true; + } + + PyObject* mvThemeManager::set_theme_color(PyObject* self, PyObject* args, PyObject* kwargs) + { + long constant; + PyObject* color; + const char* item = ""; + + if (!(mvApp::GetApp()->getParsers())["set_theme_color"].parse(args, kwargs, __FUNCTION__, &constant, &color, &item)) + return GetPyNone(); + + Py_XINCREF(color); + std::lock_guard lk(mvApp::GetApp()->getMutex()); + + mvEventBus::Publish + ( + mvEVT_CATEGORY_THEMES, + SID("color_change"), + { + CreateEventArgument("WIDGET", std::string(item)), + CreateEventArgument("ID", constant), + CreateEventArgument("COLOR", ToColor(color)), + CreateEventArgument("ENABLED", true) + } + ); + + Py_XDECREF(color); + + + return GetPyNone(); + } + + PyObject* mvThemeManager::set_theme_color_disabled(PyObject* self, PyObject* args, PyObject* kwargs) + { + long constant; + PyObject* color; + const char* item = ""; + + if (!(mvApp::GetApp()->getParsers())["set_theme_color_disabled"].parse(args, kwargs, __FUNCTION__, &constant, &color, &item)) + return GetPyNone(); + + Py_XINCREF(color); + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvEventBus::Publish + ( + mvEVT_CATEGORY_THEMES, + SID("color_change"), + { + CreateEventArgument("WIDGET", std::string(item)), + CreateEventArgument("ID", constant), + CreateEventArgument("COLOR", ToColor(color)), + CreateEventArgument("ENABLED", false) + } + ); + + // to ensure the decrement happens on the python thread + mvApp::GetApp()->getCallbackRegistry().submitCallback([=]() + { + Py_XDECREF(color); + }); + + }); + + return GetPyNone(); + } + + PyObject* mvThemeManager::set_theme_style(PyObject* self, PyObject* args, PyObject* kwargs) + { + long constant; + float style; + const char* item = ""; + + if (!(mvApp::GetApp()->getParsers())["set_theme_style"].parse(args, kwargs, __FUNCTION__, &constant, &style, &item)) + return GetPyNone(); + + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvEventBus::Publish + ( + mvEVT_CATEGORY_THEMES, + SID("style_change"), + { + CreateEventArgument("WIDGET", std::string(item)), + CreateEventArgument("ID", constant), + CreateEventArgument("STYLE", style) + } + ); + }); + + return GetPyNone(); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/Theming/mvThemeManager.h b/DearPyGui/src/core/Theming/mvThemeManager.h new file mode 100644 index 000000000..38da53a71 --- /dev/null +++ b/DearPyGui/src/core/Theming/mvThemeManager.h @@ -0,0 +1,174 @@ +#pragma once + +#include +#include "mvEvents.h" +#include "mvAppItem.h" +#include "composite/mvStyleWindow.h" + +namespace Marvel { + + class mvThemeManager : public mvEventHandler + { + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(set_theme_color); + MV_CREATE_EXTRA_COMMAND(set_theme_color_disabled); + MV_CREATE_EXTRA_COMMAND(set_theme_style); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(set_theme_color); + MV_ADD_EXTRA_COMMAND(set_theme_color_disabled); + MV_ADD_EXTRA_COMMAND(set_theme_style); + MV_END_EXTRA_COMMANDS + + static void InValidateColorTheme(); + static void InValidateStyleTheme(); + + static std::vector>& GetColorsPtr() { return s_acolors; } + static std::vector>& GetStylesPtr() { return s_astyles; } + static std::unordered_map& GetColors() { return s_colors; } + static std::unordered_map& GetStyles() { return s_styles; } + + public: + + mvThemeManager(); + ~mvThemeManager(); + + private: + + bool onEvent(mvEvent& event) override; + bool add_color(mvEvent& event); + bool add_style(mvEvent& event); + + static std::vector> s_acolors; + static std::vector> s_astyles; + static std::unordered_map s_colors; + static std::unordered_map s_styles; + + }; + + template + void SearchAncestorTreeForColors(T* item, mvThemeColors& colors) + { + const std::vector>& color_constants = T::GetColorConstants(); + + std::unordered_map colors_found; + for (const auto& color_pair : color_constants) + colors_found[std::get<1>(color_pair)] = false; + + // check local colors and styles first + if (item->getColors().find(item->getType()) != item->getColors().end()) + { + for (const auto& color : item->getColors()[item->getType()]) + { + colors_found[color.first] = true; + colors[color.first] = color.second; + } + } + + // search through ancestor tree for unfound colors + mvAppItem* widget = item; + while (!mvAppItem::DoesItemHaveFlag(widget, MV_ITEM_DESC_ROOT)) + { + widget = widget->getParent(); + + if (widget->getColors().find(item->getType()) != widget->getColors().end()) + { + for (const auto& color : widget->getColors()[item->getType()]) + { + // only apply if it wasn't found yet + if (!colors_found[color.first]) + { + colors[color.first] = color.second; + colors_found[color.first] = true; + } + } + } + } + + for (auto& color : mvThemeManager::GetColors()[item->getType()]) + { + // only apply if it wasn't found yet + if (!colors_found[color.first]) + { + colors[color.first] = color.second; + colors_found[color.first] = true; + } + } + + } + + template + void SearchAncestorTreeForStyles(T* item, std::unordered_map& styles, std::unordered_map& styles1, std::unordered_map& styles2) + { + + const std::vector>& style_constants = T::GetStyleConstants(); + + // style is were we place all zero first position floats + // style2 is where we place a const that may have a second position for pushing ImVec2 constants + static int styleID; + std::unordered_map styles_found; + for (const auto& style_pair : style_constants) + styles_found[std::get<1>(style_pair)] = false; + + if (item->getStyles().find(item->getType()) != item->getStyles().end()) + { + for (const auto& style : item->getStyles()[item->getType()]) + { + styles_found[style.first] = true; + DecodelibID(style.first, &styleID); + if (DecodeIndex(style.first) > 0) + styles2[styleID] = style.second; + else + styles1[styleID] = style.second; + } + } + + // search through ancestor tree for unfound styles + mvAppItem* widget = item; + while (!mvAppItem::DoesItemHaveFlag(widget, MV_ITEM_DESC_ROOT)) + { + widget = widget->getParent(); + + if (widget->getStyles().find(item->getType()) != widget->getStyles().end()) + { + for (auto& style : widget->getStyles()[item->getType()]) + { + // only apply if it wasn't found yet + if (!styles_found[style.first]) + { + styles_found[style.first] = true; + DecodelibID(style.first, &styleID); + if (DecodeIndex(style.first) > 0) + styles2[styleID] = style.second; + else + styles1[styleID] = style.second; + } + } + } + } + + for (auto& style : mvThemeManager::GetStyles()[item->getType()]) + { + // only apply if it wasn't found yet + if (!styles_found[style.first]) + { + styles_found[style.first] = true; + DecodelibID(style.first, &styleID); + if (DecodeIndex(style.first) > 0) + styles2[styleID] = style.second; + else + styles1[styleID] = style.second; + } + } + + styles = styles1; + + for (const auto& style : styles2) + styles.erase(style.first); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/cpp.hint b/DearPyGui/src/core/cpp.hint new file mode 100644 index 000000000..513188ac6 --- /dev/null +++ b/DearPyGui/src/core/cpp.hint @@ -0,0 +1,60 @@ +// Hint files help the Visual Studio IDE interpret Visual C++ identifiers +// such as names of functions and macros. +// For more information see https://go.microsoft.com/fwlink/?linkid=865984 + +#define MV_REGISTER_WIDGET(x, y, z, w) class x;\ +template<> struct mvItemTypeMap<(int)mvAppItemType::x>\ +{typedef x type;static constexpr const int flags = y;static constexpr const StorageValueTypes value_type = z;static constexpr const int target = w;};\ +template<>struct mvItemTypeReverseMap{static constexpr mvAppItemType type = mvAppItemType::x;}; + +#define MV_APPLY_WIDGET_REGISTRATION(x, parser)\ +static constexpr const long s_internal_type = (long)x;\ +static constexpr const char* const s_internal_id = #x;\ +static constexpr const char* const s_command = #parser;\ +mvAppItemType getType() const override { return x; }\ +int getTarget() const override { return mvItemTypeMap<(int)x>::target; }\ +int getDescFlags() const override { return mvItemTypeMap<(int)x>::flags; }\ +StorageValueTypes getValueType() const override { return mvItemTypeMap<(int)x>::value_type; }\ +static PyObject* parser(PyObject* self, PyObject* args, PyObject* kwargs)\ +{\ + static int i = 0; i++;\ + std::string name = std::string(std::string("$$DPG_") + s_internal_id + std::to_string(i));\ + auto [parent, before] = mvAppItem::GetNameFromArgs(name, args, kwargs);\ + auto item = CreateRef::type>(name);\ + item->checkConfigDict(kwargs);\ + item->setConfigArgs(args);\ + item->setConfigDict(kwargs);\ + item->setExtraConfigDict(kwargs);\ + if(mvApp::GetApp()->getItemRegistry().addItemWithRuntimeChecks(item, parent.c_str(), before.c_str()))\ + {\ + if (mvAppItem::DoesItemHaveFlag(item.get(), MV_ITEM_DESC_CONTAINER))\ + mvApp::GetApp()->getItemRegistry().pushParent(item);\ + }\ + return ToPyString(name);\ +}\ +static PyMethodDef GetMethodDefinition(){return { s_command, (PyCFunction)parser, METH_VARARGS | METH_KEYWORDS, mvApp::GetApp()->getParsers()[s_command].getDocumentation() };} + + +#define MV_CREATE_EXTRA_COMMAND(x) static PyObject* x(PyObject* self, PyObject* args, PyObject* kwargs) +#define MV_START_EXTRA_COMMANDS static void FillExtraCommands(std::vector& methods){ +#define MV_ADD_EXTRA_COMMAND(x) methods.push_back({ #x, (PyCFunction)x, METH_VARARGS | METH_KEYWORDS, mvApp::GetApp()->getParsers()[#x].getDocumentation() }); +#define MV_END_EXTRA_COMMANDS } + +#define MV_START_GENERAL_CONSTANTS public: static const std::vector>& GetGeneralConstants()\ +{static std::vector> constants ={ + +#define MV_END_GENERAL_CONSTANTS };return constants;} + +#define MV_START_COLOR_CONSTANTS public: static const std::vector>& GetColorConstants()\ +{static std::vector> constants ={ + +#define MV_END_COLOR_CONSTANTS };return constants;} +#define MV_START_STYLE_CONSTANTS public: static const std::vector>& GetStyleConstants()\ +{static std::vector> constants ={ + +#define MV_END_STYLE_CONSTANTS };return constants;} +#define MV_ADD_GENERAL_CONSTANT(x) {#x, x} +#define MV_CREATE_CONSTANT_PAIR(x, y) {#x, x, y, y} +#define MV_ADD_CONSTANT(x, y, z) {#x, x, y, z} +#define MV_ENCODE_CONSTANT(z, i) s_internal_type*1000L+z*10L+i +#define MV_CREATE_CONSTANT(y, z, i) static constexpr const long y = MV_ENCODE_CONSTANT(z, i); diff --git a/DearPyGui/src/core/mvApp.cpp b/DearPyGui/src/core/mvApp.cpp new file mode 100644 index 000000000..7e7697fcd --- /dev/null +++ b/DearPyGui/src/core/mvApp.cpp @@ -0,0 +1,385 @@ +#include "mvApp.h" +#include "mvModule_Core.h" +#include "mvViewport.h" +#include "mvCallbackRegistry.h" +#include "mvInput.h" +#include +#include +#include +#include "mvThreadPool.h" +#include "mvAppItemCommons.h" +#include "mvProfiler.h" +#include +#include "mvEventListener.h" +#include "mvImGuiThemeScope.h" +#include "mvCallbackRegistry.h" +#include "mvTextureStorage.h" +#include "mvItemRegistry.h" +#include "mvLog.h" +#include "mvFontManager.h" + +namespace Marvel { + + mvApp* mvApp::s_instance = nullptr; + std::atomic_bool mvApp::s_started = false; + + + // utility structure for realtime plot + struct ScrollingBuffer { + int MaxSize; + int Offset; + ImVector Data; + ScrollingBuffer() { + MaxSize = 2000; + Offset = 0; + Data.reserve(MaxSize); + } + void AddPoint(float x, float y) { + if (Data.size() < MaxSize) + Data.push_back(ImVec2(x, y)); + else { + Data[Offset] = ImVec2(x, y); + Offset = (Offset + 1) % MaxSize; + } + } + void Erase() { + if (!Data.empty()) + { + Data.shrink(0); + Offset = 0; + } + } + }; + + mvApp* mvApp::GetApp() + { + mvLog::Init(); + + if (s_instance) + return s_instance; + + s_instance = new mvApp(); + return s_instance; + } + + void mvApp::DeleteApp() + { + if (s_instance) + { + delete s_instance; + s_instance = nullptr; + } + + s_started = false; + } + + void mvApp::SetAppStopped() + { + + GetApp()->getCallbackRegistry().stop(); + GetApp()->getCallbackRegistry().addCallback(nullptr, "null", nullptr); + GetApp()->m_future.get(); + s_started = false; + auto viewport = s_instance->getViewport(); + if (viewport) + viewport->stop(); + } + + void mvApp::cleanup() + { + getCallbackRegistry().stop(); + + getCallbackRegistry().addCallback(nullptr, "null", nullptr); + + m_future.get(); + delete m_viewport; + s_started = false; + } + + mvApp::mvApp() + { + + // info + mvAppLog::Clear(); + mvAppLog::AddLog("[DearPyGui Version] %0s\n", mvApp::GetVersion()); + mvAppLog::AddLog("[DearImGui Version] %0s\n", IMGUI_VERSION); + mvAppLog::AddLog("[Python Version] %0s\n", PY_VERSION); + + + m_mainThreadID = std::this_thread::get_id(); + +#if defined(MV_DEBUG) + new mvEventListener(); +#endif // MV_PROFILE + + // create managers + m_itemRegistry = CreateOwnedPtr(); + m_textureStorage = CreateOwnedPtr(); + m_themeManager = CreateOwnedPtr(); + m_callbackRegistry = CreateOwnedPtr(); + m_fontManager = CreateOwnedPtr(); + + } + + mvCallbackRegistry& mvApp::getCallbackRegistry() + { + return *m_callbackRegistry; + } + + mvItemRegistry& mvApp::getItemRegistry() + { + return *m_itemRegistry; + } + + mvTextureStorage& mvApp::getTextureStorage() + { + return *m_textureStorage; + } + + mvThemeManager& mvApp::getThemeManager() + { + return *m_themeManager; + } + + mvFontManager& mvApp::getFontManager() + { + return *m_fontManager; + } + + mvApp::~mvApp() + { + m_itemRegistry->clearRegistry(); + + mvApp::GetApp()->getTextureStorage().deleteAllTextures(); + + mvLog::Cleanup(); + + } + + void mvApp::turnOnDocking(bool shiftOnly, bool dockSpace) + { + m_docking = true; + m_dockingShiftOnly = shiftOnly; + m_dockingViewport = dockSpace; + } + + void mvApp::render() + { + + // update timing + m_deltaTime = ImGui::GetIO().DeltaTime; + m_time = ImGui::GetTime(); + ImGui::GetIO().FontGlobalScale = m_fontManager->getGlobalFontScale(); + + if (m_dockingViewport) + ImGui::DockSpaceOverViewport(); + + mvEventBus::Publish(mvEVT_CATEGORY_APP, mvEVT_FRAME, {CreateEventArgument("FRAME", ImGui::GetFrameCount() )}); + + mvAppLog::render(); + + // route input callbacks + mvInput::CheckInputs(); + + //m_textureStorage->show_debugger(); + //m_fontManager->show_debugger(); + + std::lock_guard lk(m_mutex); + mvEventBus::Publish(mvEVT_CATEGORY_APP, mvEVT_PRE_RENDER); + mvEventBus::Publish(mvEVT_CATEGORY_APP, mvEVT_PRE_RENDER_RESET); + mvEventBus::Publish(mvEVT_CATEGORY_APP, mvEVT_RENDER); + mvEventBus::Publish(mvEVT_CATEGORY_APP, mvEVT_END_FRAME); + +#if defined(MV_PROFILE) && defined(MV_DEBUG) + //mvEventBus::ShowDebug(); + postProfile(); +#endif // MV_PROFILE + } + + bool mvApp::checkIfMainThread() const + { + if (std::this_thread::get_id() != m_mainThreadID) + { + int line = PyFrame_GetLineNumber(PyEval_GetFrame()); + PyErr_Format(PyExc_Exception, + "DearPyGui command on line %d can not be called asynchronously", line); + PyErr_Print(); + return false; + } + return true; + } + + void mvApp::postProfile() + { + static std::map buffers; + static float t = 0; + t += ImGui::GetIO().DeltaTime; + + const auto& results = mvInstrumentor::Get().getResults(); + + for (const auto& item : results) + buffers[item.first].AddPoint(t, item.second.count()); + + //ImGui::SetNextWindowFocus(); + ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_FirstUseEver); + if (!ImGui::Begin("Profiling", nullptr)) + { + ImGui::End(); + return; + } + + static float history = 10.0f; + ImGui::SliderFloat("History", &history, 1, 30, "%.1f s"); + + static ImPlotAxisFlags rt_axis = ImPlotAxisFlags_NoTickLabels; + ImPlot::SetNextPlotLimitsX(t - history, t, ImGuiCond_Always); + if (ImPlot::BeginPlot("##Scrolling", nullptr, nullptr, ImVec2(-1, -1), 0, rt_axis, 0 | ImPlotAxisFlags_LockMin)) { + + for (const auto& item : results) + ImPlot::PlotLine(item.first.c_str(), &buffers[item.first].Data[0].x, &buffers[item.first].Data[0].y, buffers[item.first].Data.size(), buffers[item.first].Offset, 2 * sizeof(float)); + ImPlot::EndPlot(); + } + + ImGui::End(); + + } + + void mvApp::InsertParser(std::map* parsers) + { + + parsers->insert({ "end", mvPythonParser({ + }, "Ends a container.", "None", "Containers") }); + + parsers->insert({ "enable_docking", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "shift_only", "press shift for docking", "True"}, + {mvPythonDataType::Bool, "dock_space", "add explicit dockspace over viewport", "False"}, + }, "Decrements a texture.") }); + + parsers->insert({ "is_dearpygui_running", mvPythonParser({ + }, "Checks if dearpygui is still running", "bool") }); + + parsers->insert({ "setup_dearpygui", mvPythonParser({ + }, "Sets up DearPyGui for user controlled rendering. Only call once and you must call cleanup_deapygui when finished.") }); + + parsers->insert({ "render_dearpygui_frame", mvPythonParser({ + }, "Renders a DearPyGui frame. Should be called within a user's event loop. Must first call setup_dearpygui outside of event loop.") }); + + parsers->insert({ "cleanup_dearpygui", mvPythonParser({ + }, "Cleans up DearPyGui after calling setup_dearpygui.") }); + + parsers->insert({ "stop_dearpygui", mvPythonParser({ + }, "Stops DearPyGui.") }); + + parsers->insert({ "get_total_time", mvPythonParser({ + }, "Returns total time since app started.", "float") }); + + parsers->insert({ "get_delta_time", mvPythonParser({ + }, "Returns time since last frame.", "float") }); + + parsers->insert({ "get_dearpygui_version", mvPythonParser({ + }, "Returns the current version of Dear PyGui.", "str") }); + + } + + PyObject* mvApp::end(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getItemRegistry().popParent(); + return GetPyNone(); + } + + PyObject* mvApp::enable_docking(PyObject* self, PyObject* args, PyObject* kwargs) + { + int shift_only = true; + int dockspace = false; + + if (!(mvApp::GetApp()->getParsers())["enable_docking"].parse(args, kwargs, __FUNCTION__, + &shift_only, &dockspace)) + return GetPyNone(); + + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->turnOnDocking(shift_only, dockspace); + }); + + return GetPyNone(); + } + + PyObject* mvApp::is_dearpygui_running(PyObject* self, PyObject* args, PyObject* kwargs) + { + return ToPyBool(mvApp::IsAppStarted()); + } + + PyObject* mvApp::setup_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs) + { + Py_BEGIN_ALLOW_THREADS; + mvLog::Init(); + + if (mvApp::IsAppStarted()) + { + ThrowPythonException("Cannot call \"setup_dearpygui\" while a Dear PyGUI app is already running."); + return GetPyNone(); + } + + s_started = true; + GetApp()->m_future = std::async(std::launch::async, []() {return GetApp()->m_callbackRegistry->runCallbacks(); }); + + MV_CORE_INFO("application starting"); + + Py_END_ALLOW_THREADS; + + return GetPyNone(); + } + + PyObject* mvApp::render_dearpygui_frame(PyObject* self, PyObject* args, PyObject* kwargs) + { + + Py_BEGIN_ALLOW_THREADS; + auto window = mvApp::GetApp()->getViewport(); + window->renderFrame(); + Py_END_ALLOW_THREADS; + + return GetPyNone(); + } + + PyObject* mvApp::cleanup_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs) + { + Py_BEGIN_ALLOW_THREADS; + mvApp::GetApp()->cleanup(); + mvApp::DeleteApp(); + mvEventBus::Reset(); + mvAppLog::Clear(); + Py_END_ALLOW_THREADS; + + return GetPyNone(); + } + + PyObject* mvApp::stop_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs) + { + mvApp::StopApp(); + auto viewport = mvApp::GetApp()->getViewport(); + if (viewport) + viewport->stop(); + return GetPyNone(); + } + + PyObject* mvApp::get_total_time(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + return ToPyFloat((float)mvApp::GetApp()->getTotalTime()); + } + + PyObject* mvApp::get_delta_time(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + return ToPyFloat(mvApp::GetApp()->getDeltaTime()); + + } + + PyObject* mvApp::get_dearpygui_version(PyObject* self, PyObject* args, PyObject* kwargs) + { + return ToPyString(mvApp::GetApp()->GetVersion()); + } + +} diff --git a/DearPyGui/src/core/mvApp.h b/DearPyGui/src/core/mvApp.h new file mode 100644 index 000000000..558874528 --- /dev/null +++ b/DearPyGui/src/core/mvApp.h @@ -0,0 +1,181 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvApp +// +// - This class acts as the primary manager for a DearPyGui app, +// with the following responsibilities: +// +// * Callback routing +// +// - This class can eventually just contain all static members & methods +// +//----------------------------------------------------------------------------- + +#include "mvPython.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "mvEvents.h" +#include +#include "mvModule_Core.h" +#include "cpp.hint" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // Forward Declarations + //----------------------------------------------------------------------------- + class mvWindowAppItem; + class mvTextEditor; + class mvViewport; + class mvThemeManager; + class mvFontManager; + class mvItemRegistry; + class mvTextureStorage; + class mvCallbackRegistry; + struct mvColor; + enum class mvAppItemType; + + //----------------------------------------------------------------------------- + // mvApp + //----------------------------------------------------------------------------- + class mvApp + { + + friend class mvViewport; + friend class mvWindowsViewport; + friend class mvLinuxViewport; + friend class mvAppleViewport; + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(enable_docking); + MV_CREATE_EXTRA_COMMAND(get_dearpygui_version); + MV_CREATE_EXTRA_COMMAND(setup_dearpygui); + MV_CREATE_EXTRA_COMMAND(render_dearpygui_frame); + MV_CREATE_EXTRA_COMMAND(cleanup_dearpygui); + MV_CREATE_EXTRA_COMMAND(get_delta_time); + MV_CREATE_EXTRA_COMMAND(get_total_time); + MV_CREATE_EXTRA_COMMAND(stop_dearpygui); + MV_CREATE_EXTRA_COMMAND(is_dearpygui_running); + MV_CREATE_EXTRA_COMMAND(end); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(enable_docking); + MV_ADD_EXTRA_COMMAND(get_dearpygui_version); + MV_ADD_EXTRA_COMMAND(setup_dearpygui); + MV_ADD_EXTRA_COMMAND(render_dearpygui_frame); + MV_ADD_EXTRA_COMMAND(cleanup_dearpygui); + MV_ADD_EXTRA_COMMAND(get_delta_time); + MV_ADD_EXTRA_COMMAND(get_total_time); + MV_ADD_EXTRA_COMMAND(stop_dearpygui); + MV_ADD_EXTRA_COMMAND(is_dearpygui_running); + MV_ADD_EXTRA_COMMAND(end); + MV_END_EXTRA_COMMANDS + + public: + + mvApp (const mvApp& other) = delete; + mvApp (mvApp&& other) = delete; + mvApp operator=(const mvApp& other) = delete; + mvApp operator=(mvApp&& other) = delete; + + static mvApp* GetApp (); + static void DeleteApp (); + static const char* GetVersion () { return MV_SANDBOX_VERSION; } + static bool IsAppStarted () { return s_started; } + static void SetAppStopped (); + static void StopApp () { s_started = false; } // ugly + + void cleanup(); + + ~mvApp(); + + //----------------------------------------------------------------------------- + // Rendering + //----------------------------------------------------------------------------- + void render (); // actual render loop + + //----------------------------------------------------------------------------- + // Managers + //----------------------------------------------------------------------------- + mvItemRegistry& getItemRegistry (); + mvTextureStorage& getTextureStorage (); + mvCallbackRegistry& getCallbackRegistry(); + mvThemeManager& getThemeManager (); + mvFontManager& getFontManager (); + + //----------------------------------------------------------------------------- + // App Settings + //----------------------------------------------------------------------------- + void turnOnDocking (bool shiftOnly, bool dockSpace); + void setViewport (mvViewport* viewport) { m_viewport = viewport; } + + mvViewport* getViewport () { return m_viewport; } + + //----------------------------------------------------------------------------- + // Concurrency + //----------------------------------------------------------------------------- + bool checkIfMainThread () const; + + //----------------------------------------------------------------------------- + // Timing + //----------------------------------------------------------------------------- + float getDeltaTime() const { return m_deltaTime; } + double getTotalTime() const { return m_time; } + + //----------------------------------------------------------------------------- + // Other + //----------------------------------------------------------------------------- + std::map& getParsers() { return const_cast&>(mvModule_Core::GetModuleParsers()); } + std::mutex& getMutex() const { return m_mutex; } + + private: + + //----------------------------------------------------------------------------- + // Post Rendering Methods + // - actually performs queued operations + //----------------------------------------------------------------------------- + void postProfile (); + + mvApp(); + + private: + + static mvApp* s_instance; + static std::atomic_bool s_started; + + // managers + mvOwnedPtr m_itemRegistry; + mvOwnedPtr m_textureStorage; + mvOwnedPtr m_themeManager; + mvOwnedPtr m_fontManager; + mvOwnedPtr m_callbackRegistry; + + + // docking + bool m_docking = false; + bool m_dockingShiftOnly = true; + bool m_dockingViewport = false; + + mvViewport* m_viewport = nullptr; + + // timing + float m_deltaTime = 0.0f; // time since last frame + double m_time = 0.0; // total time since starting + + std::thread::id m_mainThreadID; + mutable std::mutex m_mutex; + std::future m_future; + + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvAppLog.cpp b/DearPyGui/src/core/mvAppLog.cpp new file mode 100644 index 000000000..e3675606e --- /dev/null +++ b/DearPyGui/src/core/mvAppLog.cpp @@ -0,0 +1,368 @@ +#include "mvAppLog.h" +#include +#include +#include "mvApp.h" +#include "mvInput.h" +#include "mvItemRegistry.h" + +typedef std::chrono::high_resolution_clock clock_; +typedef std::chrono::duration > second_; + +namespace Marvel { +#if defined (_WIN32) + std::chrono::steady_clock::time_point mvAppLog::s_start = clock_::now(); +#elif defined(__APPLE__) + std::chrono::steady_clock::time_point mvAppLog::s_start = clock_::now(); +#else + std::chrono::system_clock::time_point mvAppLog::s_start = clock_::now(); +#endif + + ImGuiTextBuffer mvAppLog::Buf; + bool mvAppLog::show = false; + bool mvAppLog::mainmode = false; + ImGuiTextFilter mvAppLog::Filter; + ImVector mvAppLog::LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines + bool mvAppLog::AutoScroll = true; // Keep scrolling if already at the bottom + int mvAppLog::s_loglevel = 1; + unsigned mvAppLog::s_width = 500; + unsigned mvAppLog::s_height = 500; + std::string mvAppLog::s_title = "Dear PyGui Logger"; + ImGuiWindowFlags mvAppLog::s_flags = ImGuiWindowFlags_NoSavedSettings; + int mvAppLog::s_xpos = 200; + int mvAppLog::s_ypos = 200; + bool mvAppLog::s_dirty_pos = true; + bool mvAppLog::s_dirty_size = true; + bool mvAppLog::s_focus = false; + + void mvAppLog::SetConfigDict(PyObject* dict) + { + + if (PyObject* item = PyDict_GetItemString(dict, "width")) s_width = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "height")) s_height = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "x_pos")) s_xpos = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "y_pos")) s_ypos = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "show")) show = ToBool(item); + } + + void mvAppLog::GetConfigDict(PyObject* dict) + { + + PyDict_SetItemString(dict, "width", ToPyInt(s_width)); + PyDict_SetItemString(dict, "height", ToPyInt(s_height)); + PyDict_SetItemString(dict, "x_pos", ToPyInt(s_xpos)); + PyDict_SetItemString(dict, "y_pos", ToPyInt(s_ypos)); + PyDict_SetItemString(dict, "show", ToPyBool(show)); + } + + unsigned mvAppLog::getLogLevel() + { + return s_loglevel; + } + + void mvAppLog::Show() + { + show = true; + } + + void mvAppLog::ShowMain() + { + show = true; + mainmode = true; + } + + void mvAppLog::SetWindowPos(float x, float y) + { + s_xpos = (int)x; + s_ypos = (int)y; + s_dirty_pos = true; + } + + void mvAppLog::SetWidth(int width) + { + s_width = width; + s_dirty_size = true; + } + + void mvAppLog::SetHeight(int height) + { + s_height = height; + s_dirty_size = true; + } + + void mvAppLog::setLogLevel(int level) + { + s_loglevel = level; + } + + unsigned mvAppLog::GetWindowWidth() + { + return s_width; + } + + unsigned mvAppLog::GetWindowHeight() + { + return s_height; + } + + void mvAppLog::Focus() + { + s_focus = true; + } + + void mvAppLog::Clear() + { + Buf.clear(); + LineOffsets.clear(); + LineOffsets.push_back(0); + } + + void mvAppLog::AddLog(const char* fmt, ...) + { + static std::mutex mutex; + + std::lock_guard lock(mutex); + if (LineOffsets.size() > 100000) + Clear(); + + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendfv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size + 1); + } + + mvVec2 mvAppLog::GetWindowPos() + { + return { (float)s_xpos, (float)s_ypos }; + } + + void mvAppLog::render() + { + if (!show) + return; + + if (mainmode) + { + ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); + ImGui::SetNextWindowSize(ImVec2((float)s_width, (float)s_height)); + + s_flags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings + | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; + } + + else if (s_dirty_pos) + { + ImGui::SetNextWindowPos(ImVec2((float)s_xpos, (float)s_ypos)); + s_dirty_pos = false; + } + + if (s_dirty_size) + { + ImGui::SetNextWindowSize(ImVec2((float)s_width, (float)s_height)); + s_dirty_size = false; + } + + + if (s_focus) + { + ImGui::SetNextWindowFocus(); + s_focus = false; + } + + if (!ImGui::Begin(s_title.c_str(), &show, s_flags)) + { + ImGui::End(); + return; + } + + // Options menu + if (ImGui::BeginPopup("Options")) + { + ImGui::Checkbox("Auto-scroll", &AutoScroll); + ImGui::EndPopup(); + } + + // Main window + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + bool clear = ImGui::Button("Clear"); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); + + if (clear) + Clear(); + if (copy) + ImGui::LogToClipboard(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + const char* buf = Buf.begin(); + const char* buf_end = Buf.end(); + if (Filter.IsActive()) + { + // In this example we don't use the clipper when Filter is enabled. + // This is because we don't have a random access on the result on our filter. + // A real application processing logs with ten of thousands of entries may want to store the result of search/filter. + // especially if the filtering function is not trivial (e.g. reg-exp). + for (int line_no = 0; line_no < LineOffsets.Size; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + if (Filter.PassFilter(line_start, line_end)) + ImGui::TextUnformatted(line_start, line_end); + } + } + else + { + + + // The simplest and easy way to display the entire buffer: + // ImGui::TextUnformatted(buf_begin, buf_end); + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines. + // Here we instead demonstrate using the clipper to only process lines that are within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended. + // Using ImGuiListClipper requires A) random access into your data, and B) items all being the same height, + // both of which we can handle since we an array pointing to the beginning of each line of text. + // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper. + // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries) + ImGuiListClipper clipper; + clipper.Begin(LineOffsets.Size); + while (clipper.Step()) + { + for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) + { + + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + + std::string mystring = line_start; + + std::string splitstring = mystring.substr(0, 20); + + if (strstr(splitstring.c_str(), "[ERROR]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + + else if (strstr(splitstring.c_str(), "[WARNING]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogramHovered)); + + else if (strstr(splitstring.c_str(), "[TRACE]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); + + else if (strstr(splitstring.c_str(), "[INFO]")) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + + else if (strstr(splitstring.c_str(), "[DEBUG]")) + + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.25f, 0.50f, 1.0f, 1.0f)); + + else + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + + ImGui::TextUnformatted(line_start, line_end); + ImGui::PopStyleColor(); + } + } + clipper.End(); + } + ImGui::PopStyleVar(); + + if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) + ImGui::SetScrollHereY(1.0f); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "logger##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("logger##standard")) }); + + } + + ImGui::EndChild(); + + if (ImGui::IsWindowFocused()) + { + + float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); + + // update mouse + ImVec2 mousePos = ImGui::GetMousePos(); + float x = mousePos.x - ImGui::GetWindowPos().x; + float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; + mvInput::setMousePosition(x, y); + if (mvApp::GetApp()->getItemRegistry().getActiveWindow() != "logger##standard") + mvEventBus::Publish(mvEVT_CATEGORY_ITEM, mvEVT_ACTIVE_WINDOW, { CreateEventArgument("WINDOW", std::string("logger##standard")) }); + + } + + s_width = (int)ImGui::GetWindowWidth(); + s_height = (int)ImGui::GetWindowHeight(); + s_xpos = (int)ImGui::GetWindowPos().x; + s_ypos = (int)ImGui::GetWindowPos().y; + + ImGui::End(); + } + + void mvAppLog::Log(const std::string& text, const std::string& level) + { + if (s_loglevel < 1) + { + AddLog("[%0.2f] [%1s] %2s\n", std::chrono::duration_cast(clock_::now()-s_start).count(), + level.c_str(), text.c_str()); + } + } + + void mvAppLog::LogDebug(const std::string& text) + { + if (s_loglevel < 2) + AddLog("[%0.2f] [DEBUG] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvAppLog::LogInfo(const std::string& text) + { + if (s_loglevel < 3) + AddLog("[%0.2f] [INFO] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvAppLog::LogWarning(const std::string& text) + { + if (s_loglevel < 4) + AddLog("[%0.2f] [WARNING] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvAppLog::LogError(const std::string& text) + { + if (s_loglevel < 5) + AddLog("[%0.2f] [ERROR] %1s\n", std::chrono::duration_cast(clock_::now() - s_start).count(), + text.c_str()); + } + + void mvAppLog::ClearLog() + { + Clear(); + } + + void mvAppLog::setSize(unsigned width, unsigned height) + { + s_width = width; + s_height = height; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvAppLog.h b/DearPyGui/src/core/mvAppLog.h new file mode 100644 index 000000000..ee513fecc --- /dev/null +++ b/DearPyGui/src/core/mvAppLog.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include "mvCore.h" +#include "mvPython.h" + +namespace Marvel { + + + + class mvAppLog + { + + public: + + static void AddLog (const char* fmt, ...); + static void Clear (); + static void setLogLevel (int level); + static void Log (const std::string& text, const std::string& level = "TRACE"); + static void LogDebug (const std::string& text); + static void LogInfo (const std::string& text); + static void LogWarning (const std::string& text); + static void LogError (const std::string& text); + static void ClearLog (); + static void render (); + static void setSize (unsigned width, unsigned height); + static unsigned getLogLevel (); + static void Show (); + static void ShowMain (); + static void SetWindowPos (float x, float y); + static void SetWidth (int width); + static void SetHeight (int height); + [[nodiscard]] static unsigned GetWindowWidth (); + [[nodiscard]] static unsigned GetWindowHeight(); + static mvVec2 GetWindowPos (); + static void SetConfigDict(PyObject* dict); + static void GetConfigDict(PyObject* dict); + static void Focus (); + static void setTitle (const std::string& title) { s_title = title; } + + private: + + mvAppLog() = default; + + private: + + static ImGuiTextBuffer Buf; + static ImGuiTextFilter Filter; + static ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines + static bool AutoScroll; // Keep scrolling if already at the bottom + //static bool ScrollToBottom; // Keep scrolling if already at the bottom + static bool show; // Keep scrolling if already at the bottom + static bool mainmode; + static int s_loglevel; + static unsigned s_width; + static unsigned s_height; + static ImGuiWindowFlags s_flags; + static int s_xpos; + static int s_ypos; + static bool s_dirty_pos; + static bool s_dirty_size; + static bool s_focus; + static std::string s_title; + +#if defined (_WIN32) + static std::chrono::steady_clock::time_point s_start; +#elif defined(__APPLE__) + static std::chrono::steady_clock::time_point s_start; +#else + static std::chrono::system_clock::time_point s_start; +#endif + }; + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvCompileTimeCRC32.h b/DearPyGui/src/core/mvCompileTimeCRC32.h new file mode 100644 index 000000000..e726ab825 --- /dev/null +++ b/DearPyGui/src/core/mvCompileTimeCRC32.h @@ -0,0 +1,100 @@ +// this is from https://gist.github.com/oktal/5573082 + +constexpr unsigned int crc32_table[] = { + 0, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D +}; + +template struct Crc32Impl { +}; + +template struct Crc32Impl { + static constexpr unsigned int value = Crc32Impl< + crc32_table[static_cast(CRC) ^ static_cast(Head)] + ^ (CRC >> 8), Tail...>::value; +}; + +template struct Crc32Impl { + static constexpr unsigned int value = CRC ^ 0xFFFFFFFF; +}; + + +template using Crc32 = Crc32Impl<0xFFFFFFFF, Chars...>; + +constexpr unsigned int crc32_rec(unsigned int crc, const char* s) { + return *s == 0 ? crc ^ 0xFFFFFFFF : + crc32_rec(crc32_table[static_cast(crc) ^ + static_cast(*s)] + ^ (crc >> 8), s + 1); +} + +constexpr unsigned int operator "" _crc32(const char* s, size_t len) { + return crc32_rec(0xFFFFFFFF, s); +} + +static_assert("Hello"_crc32 == Crc32<'H', 'e', 'l', 'l', 'o'>::value, + "CRC32 values don't match"); +static_assert("0"_crc32 == Crc32<'0'>::value, + "CRC32 values don't match"); \ No newline at end of file diff --git a/DearPyGui/src/core/mvCore.h b/DearPyGui/src/core/mvCore.h new file mode 100644 index 000000000..2cf168f9b --- /dev/null +++ b/DearPyGui/src/core/mvCore.h @@ -0,0 +1,194 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvCore +// +// - This file contains commonly used items throughout the core library +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +namespace Marvel { + + template + using mvOwnedPtr = std::unique_ptr; + template + constexpr mvOwnedPtr CreateOwnedPtr(Args&& ... args) + { + return std::make_unique(std::forward(args)...); + } + + template + using mvRef = std::shared_ptr; + template + constexpr mvRef CreateRef(Args&& ... args) + { + return std::make_shared(std::forward(args)...); + } + + //----------------------------------------------------------------------------- + // mvFunctionWrapper + // - Reguired because packaged_task reguires movable function objects + //----------------------------------------------------------------------------- + class mvFunctionWrapper + { + struct impl_base { + virtual void call() = 0; + virtual ~impl_base() = default; + }; + + template + struct impl_type : impl_base + { + F f; + explicit impl_type(F&& f) : f(std::move(f)) {} + void call() override { f(); } + }; + + public: + + mvFunctionWrapper() = default; + + template + mvFunctionWrapper(F&& f) : m_impl(new impl_type(std::move(f))) {} + + mvFunctionWrapper(mvFunctionWrapper&& other) noexcept + : m_impl(std::move(other.m_impl)) + { + + } + + mvFunctionWrapper& operator=(mvFunctionWrapper&& other) + { + m_impl = std::move(other.m_impl); + return *this; + } + + // delete copy constructor and assignment operator + mvFunctionWrapper(const mvFunctionWrapper&) = delete; + mvFunctionWrapper(mvFunctionWrapper&) = delete; + mvFunctionWrapper& operator=(const mvFunctionWrapper&) = delete; + + void operator()() + { + m_impl->call(); + } + + private: + + std::unique_ptr m_impl; + + }; + + //----------------------------------------------------------------------------- + // mvVec2 + //----------------------------------------------------------------------------- + struct mvVec2 + { + float x, y; + + operator ImVec2() + { + return ImVec2{ x, y }; + } + + mvVec2 operator+(const ImVec2& other) + { + return mvVec2{ x + other.x, y + other.y }; + } + }; + + //----------------------------------------------------------------------------- + // mvVec4 + //----------------------------------------------------------------------------- + struct mvVec4 + { + float x, y, z, w; + + operator ImVec4() + { + if (x < 0 || y < 0 || z < 0 || w < 0) + return ImVec4(0, 0, 0, -1); + return ImVec4{ x, y , z, w}; + } + + mvVec4 operator+(const ImVec4& other) + { + return mvVec4{ x + other.x, y + other.y, z + other.z, w + other.w }; + } + }; + + //----------------------------------------------------------------------------- + // mvColor + //----------------------------------------------------------------------------- + struct mvColor + { + float r = -1.0f, g = -1.0f, b = -1.0f, a = -1.0f; + + mvColor() = default; + + mvColor(float r, float g, float b, float a) + : r(r), g(g), b(b), a(a) + { + } + + mvColor(int r, int g, int b, int a) + : r(r/255.0f), g(g/255.0f), b(b/255.0f), a(a/255.0f) + { + } + + explicit mvColor(ImVec4 color) + { + r = color.x; + g = color.y; + b = color.z; + a = color.w; + } + + operator ImU32() + { + return ImGui::ColorConvertFloat4ToU32(toVec4()); + } + + operator float* () + { + return &r; + } + + operator ImVec4() + { + return { r, g, b, a }; + } + + const ImVec4 toVec4() const + { + return { r, g, b, a }; + } + + }; + + //----------------------------------------------------------------------------- + // Constant Expression for loop + //----------------------------------------------------------------------------- + template + constexpr void constexpr_for(F&& f) + { + if constexpr (Start < End) + { + f(std::integral_constant()); + constexpr_for(f); + } + } + + typedef std::unordered_map> mvThemeColors; + typedef std::unordered_map mvThemeStyles; + + inline void DecodelibID(long encoded_constant, int* libID) { *libID = (int)((encoded_constant / 10) % 100); } + inline int DecodeIndex(long encoded_constant) { return (int)(encoded_constant % 10); } +} + +#define MV_DEFAULT_COLOR Marvel::mvColor(1.0f, 1.0f, 1.0f, 1.0f) \ No newline at end of file diff --git a/DearPyGui/src/core/mvEventListener.h b/DearPyGui/src/core/mvEventListener.h new file mode 100644 index 000000000..0bb7a8457 --- /dev/null +++ b/DearPyGui/src/core/mvEventListener.h @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include "mvEvents.h" +#include "mvLog.h" + +#define MV_ELT_MESSAGE(CODE) MV_EVENT_TRACE("{} : {}", #CODE, CODE) +#define MV_EL_MESSAGE(CODE) MV_EVENT_TRACE("{} : {}", #CODE, CODE) + +namespace Marvel { + + class mvEventListener : public mvEventHandler + { + + public: + + mvEventListener() + { + mvEventBus::Subscribe(this); + } + + bool onEvent(mvEvent& event) override + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(BIND_EVENT_METH(mvEventListener::onInput), 0, mvEVT_CATEGORY_INPUT); + dispatcher.dispatch(BIND_EVENT_METH(mvEventListener::onResize), mvEVT_VIEWPORT_RESIZE); + + return false; + } + + bool onResize(mvEvent& event) + { + MV_EL_MESSAGE(mvEVT_VIEWPORT_RESIZE); + return false; + } + + bool onInput(mvEvent& event) + { + switch (event.type) + { + case mvEVT_KEY_PRESS: + MV_EL_MESSAGE(mvEVT_KEY_PRESS); + break; + + case mvEVT_KEY_DOWN: + MV_EL_MESSAGE(mvEVT_KEY_DOWN); + break; + + case mvEVT_KEY_RELEASE: + MV_EL_MESSAGE(mvEVT_KEY_RELEASE); + break; + + case mvEVT_MOUSE_WHEEL: + MV_EL_MESSAGE(mvEVT_MOUSE_WHEEL); + break; + + case mvEVT_MOUSE_DRAG: + MV_EL_MESSAGE(mvEVT_MOUSE_DRAG); + break; + + case mvEVT_MOUSE_CLICK: + MV_EL_MESSAGE(mvEVT_MOUSE_CLICK); + break; + + case mvEVT_MOUSE_DOWN: + MV_EL_MESSAGE(mvEVT_MOUSE_DOWN); + break; + + case mvEVT_MOUSE_DBL_CLK: + MV_EL_MESSAGE(mvEVT_MOUSE_DBL_CLK); + break; + + case mvEVT_MOUSE_RELEASE: + MV_EL_MESSAGE(mvEVT_MOUSE_RELEASE); + break; + + case mvEVT_MOUSE_MOVE: + MV_ELT_MESSAGE(mvEVT_MOUSE_MOVE); + break; + + default: + return false; + } + return false; + } + + }; + +} diff --git a/DearPyGui/src/core/mvEventMacros.h b/DearPyGui/src/core/mvEventMacros.h new file mode 100644 index 000000000..abf03d33d --- /dev/null +++ b/DearPyGui/src/core/mvEventMacros.h @@ -0,0 +1,53 @@ +#pragma once + +// Event Categories +//----------------------------------------------------------------------------- +#define mvEVT_CATEGORY_APP SID("GLOBAL") +#define mvEVT_CATEGORY_ITEM SID("APP_ITEM_EVENTS") +#define mvEVT_CATEGORY_TEXTURE SID("TEXTURE_EVENTS") +#define mvEVT_CATEGORY_INPUT SID("INPUT_EVENTS") +#define mvEVT_CATEGORY_VIEWPORT SID("VIEWPORT_EVENTS") +#define mvEVT_CATEGORY_VALUES SID("VALUE_EVENTS") +#define mvEVT_CATEGORY_THEMES SID("THEME_EVENTS") + +// mvEVT_CATEGORY_APP Events +//----------------------------------------------------------------------------- +#define mvEVT_FRAME SID("SPECIFIC_FRAME") +#define mvEVT_END_FRAME SID("END_FRAME") +#define mvEVT_PRE_RENDER SID("PRE_RENDER") +#define mvEVT_PRE_RENDER_RESET SID("PRE_RENDER_RESET") +#define mvEVT_RENDER SID("RENDER") + +// mvEVT_CATEGORY_VALUES Events +//----------------------------------------------------------------------------- +#define mvEVT_PY_SET_VALUE SID("PY_SET_VALUE") + +// mvEVT_CATEGORY_VIEWPORT Events +//----------------------------------------------------------------------------- +#define mvEVT_VIEWPORT_RESIZE SID("VIEWPORT_RESIZE") + +// mvEVT_CATEGORY_INPUT Events +//----------------------------------------------------------------------------- +#define mvEVT_KEY_PRESS SID("KEY_PRESS") +#define mvEVT_KEY_DOWN SID("KEY_DOWN") +#define mvEVT_KEY_RELEASE SID("KEY_RELEASE") +#define mvEVT_MOUSE_WHEEL SID("MOUSE_WHEEL") +#define mvEVT_MOUSE_DRAG SID("MOUSE_DRAG") +#define mvEVT_MOUSE_CLICK SID("MOUSE_CLICK") +#define mvEVT_MOUSE_DOWN SID("MOUSE_DOWN") +#define mvEVT_MOUSE_DBL_CLK SID("MOUSE_DOUBLE_CLICK") +#define mvEVT_MOUSE_RELEASE SID("MOUSE_RELEASE") +#define mvEVT_MOUSE_MOVE SID("MOUSE_MOVE") + +// mvEVT_CATEGORY_ITEM Events +//----------------------------------------------------------------------------- +//#define mvEVT_MOVE_ITEM SID("MOVE_ITEM") +//#define mvEVT_MOVE_ITEM_UP SID("MOVE_ITEM_UP") +//#define mvEVT_MOVE_ITEM_DOWN SID("MOVE_ITEM_DOWN") +//#define mvEVT_DELETE_ITEM SID("DELETE_ITEM") +#define mvEVT_ACTIVE_WINDOW SID("ACTIVE_WINDOW_CHANGE") + +// mvEVT_CATEGORY_TEXTURE Events +//----------------------------------------------------------------------------- +#define mvEVT_DEC_TEXTURE SID("DECREMENT_TEXTURE") +#define mvEVT_DELETE_TEXTURE SID("DELETE_TEXTURE") \ No newline at end of file diff --git a/DearPyGui/src/core/mvEvents.cpp b/DearPyGui/src/core/mvEvents.cpp new file mode 100644 index 000000000..540d92c3e --- /dev/null +++ b/DearPyGui/src/core/mvEvents.cpp @@ -0,0 +1,222 @@ +#include "mvEvents.h" +#include "imgui.h" +#include +#include "mvProfiler.h" + +namespace Marvel { + + const std::string& GetEString(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + bool GetEBool(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + int GetEInt(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + long GetELong(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + float GetEFloat(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + mvColor GetEColor(mvEvent& event, const char* name) + { + return std::get(event.arguments.at(SID(name))); + } + + void mvEventBus::ShowDebug() + { + if (ImGui::Begin("Event Bus")) + { + std::unordered_map>& handlerGroups = mvEventBus::GetEventHandlers(); + + for (auto& group : handlerGroups) + { + if (ImGui::CollapsingHeader(std::to_string(group.first).c_str())) + { + for (auto handler : group.second) + { + ImGui::Text("%d", handler); + } + + } + + } + } + ImGui::End(); + } + + bool mvEventBus::OnEvent(mvEvent& event) + { + mvEventDispatcher dispatcher(event); + dispatcher.dispatch(mvEventBus::OnFrame, SID("END_FRAME")); + + return false; + } + + bool mvEventBus::OnFrame(mvEvent& event) + { + while (!GetEndFrameEvents().empty()) + { + Publish(GetEndFrameEvents().front()); + GetEndFrameEvents().pop(); + } + + return false; + } + + void mvEventBus::PublishEndFrame(mvID category, mvID type, std::unordered_map arguments) + { + GetEndFrameEvents().push({ type, std::move(arguments), category }); + } + + void mvEventBus::Publish(mvID category, mvID type, std::unordered_map arguments) + { + Publish({ type, std::move(arguments), category }); + } + + void mvEventBus::Publish(mvEvent event) + { + + for (mvEventHandler* handler : GetEventHandlers()[0]) + handler->onEvent(event); + + if (event.category == SID("GLOBAL")) + OnEvent(event); + + if (event.type == 0) + return; + + if (GetEventHandlers().find(event.type) != GetEventHandlers().end()) + { + for (mvEventHandler* handler : GetEventHandlers()[event.type]) + { + if (handler->onEvent(event)) + break; + } + } + + if (event.category == 0) + return; + + if (GetEventCategoryHandlers().find(event.category) != GetEventCategoryHandlers().end()) + { + for (mvEventHandler* handler : GetEventCategoryHandlers()[event.category]) + { + if (handler->onEvent(event)) + break; + } + } + + } + + void mvEventBus::Subscribe(mvEventHandler* handler, mvID type, mvID category) + { + if (type == 0 && category == 0) + { + if (GetEventHandlers().find(0) == GetEventHandlers().end()) + GetEventHandlers()[0] = { handler }; + else + GetEventHandlers()[0].push_back(handler); + + if (GetEventCategoryHandlers().find(0) == GetEventCategoryHandlers().end()) + GetEventCategoryHandlers()[0] = { handler }; + else + GetEventCategoryHandlers()[0].push_back(handler); + return; + } + + if (type != 0) + { + if (GetEventHandlers().find(type) == GetEventHandlers().end()) + GetEventHandlers()[type] = { handler }; + else + GetEventHandlers()[type].push_back(handler); + } + + if (category == 0) + return; + + if (GetEventCategoryHandlers().find(category) == GetEventCategoryHandlers().end()) + GetEventCategoryHandlers()[category] = { handler }; + else + GetEventCategoryHandlers()[category].push_back(handler); + } + + void mvEventBus::UnSubscribe(mvEventHandler* handler) + { + + for (auto& eventHandlerBucket : GetEventHandlers()) + { + std::vector old = eventHandlerBucket.second; + eventHandlerBucket.second.clear(); + + for (mvEventHandler* eventHandler : old) + { + if (eventHandler != handler) + eventHandlerBucket.second.push_back(eventHandler); + } + } + + for (auto& eventHandlerBucket : GetEventCategoryHandlers()) + { + std::vector old = eventHandlerBucket.second; + eventHandlerBucket.second.clear(); + + for (mvEventHandler* eventHandler : old) + { + if (eventHandler != handler) + eventHandlerBucket.second.push_back(eventHandler); + } + } + + } + + void mvEventBus::Reset() + { + GetEventHandlers().clear(); + GetEventCategoryHandlers().clear(); + while (!GetEndFrameEvents().empty()) + GetEndFrameEvents().pop(); + } + + std::queue& mvEventBus::GetEndFrameEvents() + { + static std::queue events; + return events; + } + + std::unordered_map>& mvEventBus::GetEventHandlers() + { + static std::unordered_map> eventHandlers; + return eventHandlers; + } + + std::unordered_map>& mvEventBus::GetEventCategoryHandlers() + { + static std::unordered_map> eventCategoryHandlers; + return eventCategoryHandlers; + } + + std::deque mvEventBus::GetMessages() + { + static std::deque messages; + return messages; + } + + mvEventHandler::~mvEventHandler() + { + mvEventBus::UnSubscribe(this); + } +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvEvents.h b/DearPyGui/src/core/mvEvents.h new file mode 100644 index 000000000..3d8edf785 --- /dev/null +++ b/DearPyGui/src/core/mvEvents.h @@ -0,0 +1,168 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include "mvCore.h" +#include "mvCompileTimeCRC32.h" +#include "mvEventMacros.h" + +#define BIND_EVENT_METH(x) [this](auto&& event){ return x(std::forward(event));} + +namespace Marvel { + + // forward declarations + struct mvEvent; + + // type alias + using mvID = size_t; + using mvVariant = std::variant< + int, + long, + std::string, + bool, + float, + mvColor, + void* + >; // more types can be added + + // hashing function + constexpr const mvID SID(const char* value) + { + return crc32_rec(0, value); + } + + + //----------------------------------------------------------------------------- + // variant helpers + //----------------------------------------------------------------------------- + const std::string& GetEString(mvEvent& event, const char* name); + bool GetEBool (mvEvent& event, const char* name); + int GetEInt (mvEvent& event, const char* name); + long GetELong (mvEvent& event, const char* name); + float GetEFloat (mvEvent& event, const char* name); + mvColor GetEColor (mvEvent& event, const char* name); + + //----------------------------------------------------------------------------- + // mvEvent + //----------------------------------------------------------------------------- + struct mvEvent + { + + mvID type = 0; + std::unordered_map arguments; + mvID category = 0; + bool handled = false; + }; + + // variant helpers + template + T GetEPtr(mvEvent& event, const char* name) + { + return static_cast(std::get(event.arguments.at(SID(name)))); + } + + //----------------------------------------------------------------------------- + // event argument creation helpers + //----------------------------------------------------------------------------- + template + std::pair CreateEventArgument(const char* name, T value) + { + return std::make_pair(SID(name), value); + } + + template + std::pair CreateEventPtrArgument(const char* name, T value) + { + return std::make_pair(SID(name), static_cast(value)); + } + + //----------------------------------------------------------------------------- + // mvEventHandler + //----------------------------------------------------------------------------- + class mvEventHandler + { + + public: + + virtual bool onEvent(mvEvent& event) = 0; + virtual ~mvEventHandler(); + + }; + + //----------------------------------------------------------------------------- + // mvEventBus + //----------------------------------------------------------------------------- + class mvEventBus + { + + public: + + static void PublishEndFrame(mvID category, mvID type, std::unordered_map arguments = {}); + static void Publish (mvID category, mvID type, std::unordered_map arguments = {}); + static void Subscribe (mvEventHandler* handler, mvID type = 0, mvID category = 0); + static void UnSubscribe (mvEventHandler* handler); + + // event bus events + static bool OnEvent(mvEvent& event); + static bool OnFrame(mvEvent& event); + + static void ShowDebug(); + + static void Reset(); + + private: + + static void Publish(mvEvent event); + static std::queue& GetEndFrameEvents(); + static std::unordered_map>& GetEventHandlers(); + static std::unordered_map>& GetEventCategoryHandlers(); + + static std::deque GetMessages(); + }; + + //----------------------------------------------------------------------------- + // mvEventDispatcher + //----------------------------------------------------------------------------- + class mvEventDispatcher + { + + public: + + mvEventDispatcher(mvEvent& event) + : m_event(event) + { + } + + template + bool dispatch(const F& func, mvID type = 0, mvID category = 0) + { + + if (m_event.handled) + return true; + + if (m_event.type == type && type != 0) + { + m_event.handled = func(m_event); + return true; + } + + if (m_event.category == category && category != 0) + { + m_event.handled = func(m_event); + return true; + } + return false; + } + + private: + + mvEvent& m_event; + + }; +} + diff --git a/DearPyGui/src/core/mvImGuiConfig.h b/DearPyGui/src/core/mvImGuiConfig.h new file mode 100644 index 000000000..d7895a5ad --- /dev/null +++ b/DearPyGui/src/core/mvImGuiConfig.h @@ -0,0 +1,8 @@ +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +#define IMGUI_ENABLE_FREETYPE + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +#define ImDrawIdx unsigned int \ No newline at end of file diff --git a/DearPyGui/src/core/mvInput.cpp b/DearPyGui/src/core/mvInput.cpp new file mode 100644 index 000000000..bbc148fc3 --- /dev/null +++ b/DearPyGui/src/core/mvInput.cpp @@ -0,0 +1,688 @@ +#include "mvInput.h" +#include "mvApp.h" +#include "mvProfiler.h" +#include "mvCallbackRegistry.h" +#include "mvItemRegistry.h" +#include "containers/mvWindowAppItem.h" + +namespace Marvel { + + mvInput::AtomicVec2 mvInput::s_mousePos = {0, 0}; + mvInput::AtomicVec2 mvInput::s_mouseGlobalPos = {0, 0}; + mvInput::AtomicFloatVec2 mvInput::s_mousePlotPos = {0, 0}; + mvInput::AtomicVec2 mvInput::s_mouseDrawingPos = {0, 0}; + std::atomic_int mvInput::s_mouseDragThreshold = 20; + mvInput::AtomicVec2 mvInput::s_mouseDragDelta = { 0, 0 }; + std::atomic_bool mvInput::s_keysdown[512]; + std::atomic_int mvInput::s_keysdownduration[512]; // 1/100 seconds + std::atomic_bool mvInput::s_keyspressed[512]; + std::atomic_bool mvInput::s_keysreleased[512]; + std::atomic_int mvInput::s_mousewheel; + std::atomic_bool mvInput::s_mousedown[5]; + std::atomic_bool mvInput::s_mouseDragging[5]; + std::atomic_int mvInput::s_mousedownduration[5]; // 1/100 seconds + std::atomic_bool mvInput::s_mouseclick[5]; + std::atomic_bool mvInput::s_mousedoubleclick[5]; + std::atomic_bool mvInput::s_mousereleased[5]; + + void mvInput::CheckInputs() + { + MV_PROFILE_FUNCTION(); + + // update mouse + // mouse move event + ImVec2 mousepos = ImGui::GetMousePos(); + if (ImGui::IsMousePosValid(&mousepos)) + { + if (s_mouseGlobalPos.x != mousepos.x || s_mouseGlobalPos.y !=mousepos.y) + { + mvInput::setGlobalMousePosition(mousepos.x, mousepos.y); + + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_MOVE, + { + CreateEventArgument("X", mousepos.x), + CreateEventArgument("Y", mousepos.y) + }); + } + } + + + // route key events + for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().KeysDown); i++) + { + s_keysdown[i] = ImGui::GetIO().KeysDown[i]; + + // route key pressed event + if (s_keyspressed[i] = ImGui::IsKeyPressed(i)) + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_KEY_PRESS, { CreateEventArgument("KEY", i) }); + + // route key down event + if (ImGui::GetIO().KeysDownDuration[i] >= 0.0f) + { + s_keysdownduration[i] = (int)(ImGui::GetIO().KeysDownDuration[i] * 100.0); + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_KEY_DOWN, + { CreateEventArgument("KEY", i), CreateEventArgument("DURATION", ImGui::GetIO().KeysDownDuration[i]) }); + } + + // route key released event + if (s_keysreleased[i] = ImGui::IsKeyReleased(i)) + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_KEY_RELEASE, { CreateEventArgument("KEY", i) }); + } + + // route mouse wheel event + if (ImGui::GetIO().MouseWheel != 0.0f) + { + s_mousewheel = (int)ImGui::GetIO().MouseWheel; + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_WHEEL, { CreateEventArgument("DELTA", ImGui::GetIO().MouseWheel) }); + } + + // route mouse dragging event + for (int i = 0; i < 3; i++) + { + s_mouseDragging[i] = ImGui::IsMouseDragging(i, mvInput::getMouseDragThreshold()); + + if (ImGui::IsMouseDragging(i, mvInput::getMouseDragThreshold())) + { + mvInput::setMouseDragDelta({ ImGui::GetMouseDragDelta().x, ImGui::GetMouseDragDelta().y }); + // TODO: send delta + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_DRAG, + { CreateEventArgument("BUTTON", i), + CreateEventArgument("X", ImGui::GetMouseDragDelta().x), + CreateEventArgument("Y", ImGui::GetMouseDragDelta().y) + }); + ImGui::ResetMouseDragDelta(i); + break; + } + + } + + // route other mouse events (note mouse move callbacks are handled in mvWindowAppItem) + for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) + { + s_mousedown[i] = ImGui::GetIO().MouseDown[i]; + + // route mouse click event + if (s_mouseclick[i] = ImGui::IsMouseClicked(i)) + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_CLICK, { CreateEventArgument("BUTTON", i) }); + + // route mouse down event + if (ImGui::GetIO().MouseDownDuration[i] >= 0.0f) + { + s_mousedownduration[i] = (int)(ImGui::GetIO().MouseDownDuration[i] * 100.0); + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_DOWN, + { CreateEventArgument("BUTTON", i), CreateEventArgument("DURATION", ImGui::GetIO().MouseDownDuration[i]) }); + } + else + s_mousedownduration[i] = 0; + + // route mouse double clicked event + if (s_mousedoubleclick[i] = ImGui::IsMouseDoubleClicked(i)) + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_DBL_CLK, { CreateEventArgument("BUTTON", i) }); + + // route mouse released event + if (s_mousereleased[i] = ImGui::IsMouseReleased(i)) + mvEventBus::Publish(mvEVT_CATEGORY_INPUT, mvEVT_MOUSE_RELEASE, { CreateEventArgument("BUTTON", i) }); + } + } + + void mvInput::setMousePosition(float x, float y) + { + s_mousePos.x = (int)x; + s_mousePos.y = (int)y; + } + + void mvInput::setGlobalMousePosition(float x, float y) + { + s_mouseGlobalPos.x = (int)x; + s_mouseGlobalPos.y = (int)y; + } + + void mvInput::setPlotMousePosition(float x, float y) + { + s_mousePlotPos.x = x; + s_mousePlotPos.y = y; + } + + void mvInput::setDrawingMousePosition(float x, float y) + { + s_mouseDrawingPos.x = (int)x; + s_mouseDrawingPos.y = (int)y; + } + + void mvInput::setMouseDragThreshold(float threshold) + { + s_mouseDragThreshold = threshold; + } + + void mvInput::setMouseDragDelta(const mvVec2& delta) + { + s_mouseDragDelta.x = delta.x; + s_mouseDragDelta.y = delta.y; + } + + int mvInput::getMouseDragThreshold() + { + return s_mouseDragThreshold; + } + + mvVec2 mvInput::getMouseDragDelta() + { + return { (float)s_mouseDragDelta.x, (float)s_mouseDragDelta.y }; + } + + mvVec2 mvInput::getMousePosition() + { + return { (float)s_mousePos.x, (float)s_mousePos.y }; + } + + mvVec2 mvInput::getGlobalMousePosition() + { + return { (float)s_mouseGlobalPos.x, (float)s_mouseGlobalPos.y }; + } + + mvVec2 mvInput::getPlotMousePosition() + { + return { (float)s_mousePlotPos.x, (float)s_mousePlotPos.y }; + } + + mvVec2 mvInput::getDrawingMousePosition() + { + return { (float)s_mouseDrawingPos.x, (float)s_mouseDrawingPos.y }; + } + + bool mvInput::isMouseDragging(int button, float threshold) + { + return s_mousedownduration[button]/100.0f >= threshold; + } + + bool mvInput::isMouseButtonDown(int button) + { + return s_mousedown[button]; + } + + bool mvInput::isMouseButtonClicked(int button) + { + return s_mouseclick[button]; + } + + bool mvInput::isMouseButtonDoubleClicked(int button) + { + return s_mousedoubleclick[button]; + } + + bool mvInput::isMouseButtonReleased(int button) + { + return s_mousereleased[button]; + } + + bool mvInput::isKeyPressed(int keycode) + { + return s_keyspressed[keycode]; + } + + bool mvInput::isKeyReleased(int keycode) + { + return s_keysreleased[keycode]; + } + + bool mvInput::isKeyDown(int keycode) + { + return s_keysdown[keycode]; + } + + void mvInput::InsertConstants(std::vector>& constants) + { + + //----------------------------------------------------------------------------- + // Mouse Codes + //----------------------------------------------------------------------------- + constants.emplace_back("mvMouseButton_Left", 0); + constants.emplace_back("mvMouseButton_Right", 1); + constants.emplace_back("mvMouseButton_Middle", 2); + constants.emplace_back("mvMouseButton_X1", 3); + constants.emplace_back("mvMouseButton_X2", 4); + + //----------------------------------------------------------------------------- + // Key Codes + //----------------------------------------------------------------------------- + constants.emplace_back("mvKey_0" , 0x30); + constants.emplace_back("mvKey_1" , 0x31); + constants.emplace_back("mvKey_2" , 0x32); + constants.emplace_back("mvKey_3" , 0x33); + constants.emplace_back("mvKey_4" , 0x34); + constants.emplace_back("mvKey_5" , 0x35); + constants.emplace_back("mvKey_6" , 0x36); + constants.emplace_back("mvKey_7" , 0x37); + constants.emplace_back("mvKey_8" , 0x38); + constants.emplace_back("mvKey_9" , 0x39); + constants.emplace_back("mvKey_A" , 0x41); + constants.emplace_back("mvKey_B" , 0x42); + constants.emplace_back("mvKey_C" , 0x43); + constants.emplace_back("mvKey_D" , 0x44); + constants.emplace_back("mvKey_E" , 0x45); + constants.emplace_back("mvKey_F" , 0x46); + constants.emplace_back("mvKey_G" , 0x47); + constants.emplace_back("mvKey_H" , 0x48); + constants.emplace_back("mvKey_I" , 0x49); + constants.emplace_back("mvKey_J" , 0x4A); + constants.emplace_back("mvKey_K" , 0x4B); + constants.emplace_back("mvKey_L" , 0x4C); + constants.emplace_back("mvKey_M" , 0x4D); + constants.emplace_back("mvKey_N" , 0x4E); + constants.emplace_back("mvKey_O" , 0x4F); + constants.emplace_back("mvKey_P" , 0x50); + constants.emplace_back("mvKey_Q" , 0x51); + constants.emplace_back("mvKey_R" , 0x52); + constants.emplace_back("mvKey_S" , 0x53); + constants.emplace_back("mvKey_T" , 0x54); + constants.emplace_back("mvKey_U" , 0x55); + constants.emplace_back("mvKey_V" , 0x56); + constants.emplace_back("mvKey_W" , 0x57); + constants.emplace_back("mvKey_X" , 0x58); + constants.emplace_back("mvKey_Y" , 0x59); + constants.emplace_back("mvKey_Z" , 0x5A); + +#if defined (_WIN32) + constants.emplace_back("mvKey_Back" , 0x08); + constants.emplace_back("mvKey_Tab" , 0x09); + constants.emplace_back("mvKey_Clear" , 0x0C); + constants.emplace_back("mvKey_Return" , 0x0D); + constants.emplace_back("mvKey_Shift" , 0x10); + constants.emplace_back("mvKey_Control" , 0x11); + constants.emplace_back("mvKey_Alt" , 0x12); + constants.emplace_back("mvKey_Pause" , 0x13); + constants.emplace_back("mvKey_Capital" , 0x14); + constants.emplace_back("mvKey_Escape" , 0x1B); + constants.emplace_back("mvKey_Spacebar" , 0x20); + constants.emplace_back("mvKey_Prior" , 0x21); + constants.emplace_back("mvKey_Next" , 0x22); + constants.emplace_back("mvKey_End" , 0x23); + constants.emplace_back("mvKey_Home" , 0x24); + constants.emplace_back("mvKey_Left" , 0x25); + constants.emplace_back("mvKey_Up" , 0x26); + constants.emplace_back("mvKey_Right" , 0x27); + constants.emplace_back("mvKey_Down" , 0x28); + constants.emplace_back("mvKey_Select" , 0x29); + constants.emplace_back("mvKey_Print" , 0x2A); + constants.emplace_back("mvKey_Execute" , 0x2B); + constants.emplace_back("mvKey_PrintScreen" , 0x2C); + constants.emplace_back("mvKey_Insert" , 0x2D); + constants.emplace_back("mvKey_Delete" , 0x2E); + constants.emplace_back("mvKey_Help" , 0x2F); + constants.emplace_back("mvKey_LWin" , 0x5B); + constants.emplace_back("mvKey_RWin" , 0x5C); + constants.emplace_back("mvKey_Apps" , 0x5D); + constants.emplace_back("mvKey_Sleep" , 0x5F); + constants.emplace_back("mvKey_NumPad0" , 0x60); + constants.emplace_back("mvKey_NumPad1" , 0x61); + constants.emplace_back("mvKey_NumPad2" , 0x62); + constants.emplace_back("mvKey_NumPad3" , 0x63); + constants.emplace_back("mvKey_NumPad4" , 0x64); + constants.emplace_back("mvKey_NumPad5" , 0x65); + constants.emplace_back("mvKey_NumPad6" , 0x66); + constants.emplace_back("mvKey_NumPad7" , 0x67); + constants.emplace_back("mvKey_NumPad8" , 0x68); + constants.emplace_back("mvKey_NumPad9" , 0x69); + constants.emplace_back("mvKey_Multiply" , 0x6A); + constants.emplace_back("mvKey_Add" , 0x6B); + constants.emplace_back("mvKey_Separator" , 0x6C); + constants.emplace_back("mvKey_Subtract" , 0x6D); + constants.emplace_back("mvKey_Decimal" , 0x6E); + constants.emplace_back("mvKey_Divide" , 0x6F); + constants.emplace_back("mvKey_F1" , 0x70); + constants.emplace_back("mvKey_F2" , 0x71); + constants.emplace_back("mvKey_F3" , 0x72); + constants.emplace_back("mvKey_F4" , 0x73); + constants.emplace_back("mvKey_F5" , 0x74); + constants.emplace_back("mvKey_F6" , 0x75); + constants.emplace_back("mvKey_F7" , 0x76); + constants.emplace_back("mvKey_F8" , 0x77); + constants.emplace_back("mvKey_F9" , 0x78); + constants.emplace_back("mvKey_F10" , 0x79); + constants.emplace_back("mvKey_F11" , 0x7A); + constants.emplace_back("mvKey_F12" , 0x7B); + constants.emplace_back("mvKey_F13" , 0x7C); + constants.emplace_back("mvKey_F14" , 0x7D); + constants.emplace_back("mvKey_F15" , 0x7E); + constants.emplace_back("mvKey_F16" , 0x7F); + constants.emplace_back("mvKey_F17" , 0x80); + constants.emplace_back("mvKey_F18" , 0x81); + constants.emplace_back("mvKey_F19" , 0x82); + constants.emplace_back("mvKey_F20" , 0x83); + constants.emplace_back("mvKey_F21" , 0x84); + constants.emplace_back("mvKey_F22" , 0x85); + constants.emplace_back("mvKey_F23" , 0x86); + constants.emplace_back("mvKey_F24" , 0x87); + constants.emplace_back("mvKey_NumLock" , 0x90); + constants.emplace_back("mvKey_ScrollLock" , 0x91); + constants.emplace_back("mvKey_LShift" , 0xA0); + constants.emplace_back("mvKey_RShift" , 0xA1); + constants.emplace_back("mvKey_LControl" , 0xA2); + constants.emplace_back("mvKey_RControl" , 0xA3); + constants.emplace_back("mvKey_LMenu" , 0xA4); + constants.emplace_back("mvKey_RMenu" , 0xA5); + constants.emplace_back("mvKey_Browser_Back" , 0xA6); + constants.emplace_back("mvKey_Browser_Forward" , 0xA7); + constants.emplace_back("mvKey_Browser_Refresh" , 0xA8); + constants.emplace_back("mvKey_Browser_Stop" , 0xA9); + constants.emplace_back("mvKey_Browser_Search" , 0xAA); + constants.emplace_back("mvKey_Browser_Favorites" , 0xAB); + constants.emplace_back("mvKey_Browser_Home" , 0xAC); + constants.emplace_back("mvKey_Volume_Mute" , 0xAD); + constants.emplace_back("mvKey_Volume_Down" , 0xAE); + constants.emplace_back("mvKey_Volume_Up" , 0xAF); + constants.emplace_back("mvKey_Media_Next_Track" , 0xB0); + constants.emplace_back("mvKey_Media_Prev_Track" , 0xB1); + constants.emplace_back("mvKey_Media_Stop" , 0xB2); + constants.emplace_back("mvKey_Media_Play_Pause" , 0xB3); + constants.emplace_back("mvKey_Launch_Mail" , 0xB4); + constants.emplace_back("mvKey_Launch_Media_Select", 0xB5); + constants.emplace_back("mvKey_Launch_App1" , 0xB6); + constants.emplace_back("mvKey_Launch_App2" , 0xB7); + constants.emplace_back("mvKey_Colon" , 0xBA); + constants.emplace_back("mvKey_Plus" , 0xBB); + constants.emplace_back("mvKey_Comma" , 0xBC); + constants.emplace_back("mvKey_Minus" , 0xBD); + constants.emplace_back("mvKey_Period" , 0xBE); + constants.emplace_back("mvKey_Slash" , 0xBF); + constants.emplace_back("mvKey_Tilde" , 0xC0); + constants.emplace_back("mvKey_Open_Brace" , 0xDB); + constants.emplace_back("mvKey_Backslash" , 0xDC); + constants.emplace_back("mvKey_Close_Brace" , 0xDD); + constants.emplace_back("mvKey_Quote" , 0xDE); +#else + constants.emplace_back("mvKey_Back", 259); + constants.emplace_back("mvKey_Tab", 258); + constants.emplace_back("mvKey_Clear", 259); + constants.emplace_back("mvKey_Return", 257); + constants.emplace_back("mvKey_Shift", 340); + constants.emplace_back("mvKey_Control", 241); + constants.emplace_back("mvKey_Alt", 342); + constants.emplace_back("mvKey_Pause", 284); + constants.emplace_back("mvKey_Capital", 280); + constants.emplace_back("mvKey_Escape", 256); + constants.emplace_back("mvKey_Spacebar", 32); + constants.emplace_back("mvKey_Prior", 266); + constants.emplace_back("mvKey_Next", 267); + constants.emplace_back("mvKey_End", 269); + constants.emplace_back("mvKey_Home", 268); + constants.emplace_back("mvKey_Left", 263); + constants.emplace_back("mvKey_Up", 265); + constants.emplace_back("mvKey_Right", 262); + constants.emplace_back("mvKey_Down", 264); + constants.emplace_back("mvKey_Select", -1); + constants.emplace_back("mvKey_Print", -1); + constants.emplace_back("mvKey_Execute", -1); + constants.emplace_back("mvKey_PrintScreen", 286); + constants.emplace_back("mvKey_Insert", 260); + constants.emplace_back("mvKey_Delete", 261); + constants.emplace_back("mvKey_Help", -1); + constants.emplace_back("mvKey_LWin", 343); + constants.emplace_back("mvKey_RWin", 347); + constants.emplace_back("mvKey_Apps", -1); + constants.emplace_back("mvKey_Sleep", -1); + constants.emplace_back("mvKey_NumPad0", 320); + constants.emplace_back("mvKey_NumPad1", 321); + constants.emplace_back("mvKey_NumPad2", 322); + constants.emplace_back("mvKey_NumPad3", 323); + constants.emplace_back("mvKey_NumPad4", 324); + constants.emplace_back("mvKey_NumPad5", 325); + constants.emplace_back("mvKey_NumPad6", 326); + constants.emplace_back("mvKey_NumPad7", 327); + constants.emplace_back("mvKey_NumPad8", 328); + constants.emplace_back("mvKey_NumPad9", 329); + constants.emplace_back("mvKey_Multiply", 332); + constants.emplace_back("mvKey_Add", 334); + constants.emplace_back("mvKey_Separator", -1); + constants.emplace_back("mvKey_Subtract", 333); + constants.emplace_back("mvKey_Decimal", 330); + constants.emplace_back("mvKey_Divide", 331); + constants.emplace_back("mvKey_F1", 290); + constants.emplace_back("mvKey_F2", 291); + constants.emplace_back("mvKey_F3", 292); + constants.emplace_back("mvKey_F4", 293); + constants.emplace_back("mvKey_F5", 294); + constants.emplace_back("mvKey_F6", 295); + constants.emplace_back("mvKey_F7", 296); + constants.emplace_back("mvKey_F8", 297); + constants.emplace_back("mvKey_F9", 298); + constants.emplace_back("mvKey_F10", 299); + constants.emplace_back("mvKey_F11", 300); + constants.emplace_back("mvKey_F12", 301); + constants.emplace_back("mvKey_F13", 302); + constants.emplace_back("mvKey_F14", 303); + constants.emplace_back("mvKey_F15", 304); + constants.emplace_back("mvKey_F16", 305); + constants.emplace_back("mvKey_F17", 306); + constants.emplace_back("mvKey_F18", 307); + constants.emplace_back("mvKey_F19", 308); + constants.emplace_back("mvKey_F20", 309); + constants.emplace_back("mvKey_F21", 310); + constants.emplace_back("mvKey_F22", 311); + constants.emplace_back("mvKey_F23", 312); + constants.emplace_back("mvKey_F24", 313); + constants.emplace_back("mvKey_F24", 314); + constants.emplace_back("mvKey_NumLock", 282); + constants.emplace_back("mvKey_ScrollLock", 281); + constants.emplace_back("mvKey_LShift", 340); + constants.emplace_back("mvKey_RShift", 344); + constants.emplace_back("mvKey_LControl", 341); + constants.emplace_back("mvKey_RControl", 345); + constants.emplace_back("mvKey_LMenu", -1); + constants.emplace_back("mvKey_RMenu", -1); + constants.emplace_back("mvKey_Browser_Back", -1); + constants.emplace_back("mvKey_Browser_Forward", -1); + constants.emplace_back("mvKey_Browser_Refresh", -1); + constants.emplace_back("mvKey_Browser_Stop", -1); + constants.emplace_back("mvKey_Browser_Search", -1); + constants.emplace_back("mvKey_Browser_Favorites", -1); + constants.emplace_back("mvKey_Browser_Home", -1); + constants.emplace_back("mvKey_Volume_Mute", -1); + constants.emplace_back("mvKey_Volume_Down", -1); + constants.emplace_back("mvKey_Volume_Up", -1); + constants.emplace_back("mvKey_Media_Next_Track", -1); + constants.emplace_back("mvKey_Media_Prev_Track", -1); + constants.emplace_back("mvKey_Media_Stop", -1); + constants.emplace_back("mvKey_Media_Play_Pause", -1); + constants.emplace_back("mvKey_Launch_Mail", -1); + constants.emplace_back("mvKey_Launch_Media_Select", -1); + constants.emplace_back("mvKey_Launch_App1", -1); + constants.emplace_back("mvKey_Launch_App2", -1); + constants.emplace_back("mvKey_Colon", 59); + constants.emplace_back("mvKey_Plus", 61); + constants.emplace_back("mvKey_Comma", 44); + constants.emplace_back("mvKey_Minus", 45); + constants.emplace_back("mvKey_Period", 46); + constants.emplace_back("mvKey_Slash", 47); + constants.emplace_back("mvKey_Tilde", 96); + constants.emplace_back("mvKey_Open_Brace", 91); + constants.emplace_back("mvKey_Backslash", 92); + constants.emplace_back("mvKey_Close_Brace", 93); + constants.emplace_back("mvKey_Quote", 39); +#endif + } + + void mvInput::InsertParser(std::map* parsers) + { + + parsers->insert({ "get_mouse_pos", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "local", "", "True"} + }, "Returns the current mouse position in relation to the active window (minus titlebar) unless local flag is unset.", + "(int, int)", "Input Polling") }); + + parsers->insert({ "get_plot_mouse_pos", mvPythonParser({ + }, "Returns the current mouse position in the currently hovered plot.", + "(int, int)", "Input Polling") }); + + parsers->insert({ "get_drawing_mouse_pos", mvPythonParser({ + }, "Returns the current mouse position in the currently hovered drawing.", + "(int, int)", "Input Polling") }); + + parsers->insert({ "get_mouse_drag_delta", mvPythonParser({ + }, "Returns the current mouse drag delta in pixels", "(float, float)", "Input Polling") }); + + parsers->insert({ "is_mouse_button_dragging", mvPythonParser({ + {mvPythonDataType::Integer, "button"}, + {mvPythonDataType::Float, "threshold"}, + }, "Checks if the mouse is dragging.", "bool", "Input Polling") }); + + parsers->insert({ "is_mouse_button_down", mvPythonParser({ + {mvPythonDataType::Integer, "button"} + }, "Checks if the mouse button is pressed.", "bool", "Input Polling") }); + + parsers->insert({ "is_mouse_button_clicked", mvPythonParser({ + {mvPythonDataType::Integer, "button"} + }, "Checks if the mouse button is clicked.", "bool", "Input Polling") }); + + parsers->insert({ "is_mouse_button_released", mvPythonParser({ + {mvPythonDataType::Integer, "button"} + }, "Checks if the mouse button is released.", "bool", "Input Polling") }); + + parsers->insert({ "is_mouse_button_double_clicked", mvPythonParser({ + {mvPythonDataType::Integer, "button"} + }, "Checks if the mouse button is double clicked.", "bool", "Input Polling") }); + + parsers->insert({ "is_key_pressed", mvPythonParser({ + {mvPythonDataType::Integer, "key"} + }, "Checks if the key is pressed.", "bool", "Input Polling") }); + + parsers->insert({ "is_key_released", mvPythonParser({ + {mvPythonDataType::Integer, "key"} + }, "Checks if the key is released.", "bool", "Input Polling") }); + + parsers->insert({ "is_key_down", mvPythonParser({ + {mvPythonDataType::Integer, "key"} + }, "Checks if the key is down.", "bool", "Input Polling") }); + + } + + PyObject* mvInput::get_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) + { + int local = true; + + if (!(mvApp::GetApp()->getParsers())["get_mouse_pos"].parse(args, kwargs, __FUNCTION__, &local)) + return GetPyNone(); + + mvVec2 pos; + + if (local) + pos = mvInput::getMousePosition(); + else + pos = mvInput::getGlobalMousePosition(); + + return ToPyPair(pos.x, pos.y); + } + + PyObject* mvInput::get_plot_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) + { + + if (!(mvApp::GetApp()->getParsers())["get_plot_mouse_pos"].parse(args, kwargs, __FUNCTION__)) + return GetPyNone(); + + mvVec2 pos = mvInput::getPlotMousePosition(); + + return ToPyPair(pos.x, pos.y); + } + + PyObject* mvInput::get_drawing_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) + { + + if (!(mvApp::GetApp()->getParsers())["get_drawing_mouse_pos"].parse(args, kwargs, __FUNCTION__)) + return GetPyNone(); + + mvVec2 pos = mvInput::getDrawingMousePosition(); + + return ToPyPair(pos.x, pos.y); + } + + PyObject* mvInput::get_mouse_drag_delta(PyObject* self, PyObject* arg, PyObject* kwargss) + { + + mvVec2 pos = mvInput::getMouseDragDelta(); + return ToPyPair(pos.x, pos.y); + } + + PyObject* mvInput::is_key_pressed(PyObject* self, PyObject* args, PyObject* kwargs) + { + int key; + + if (!(mvApp::GetApp()->getParsers())["is_key_pressed"].parse(args, kwargs, __FUNCTION__, &key)) + return GetPyNone(); + + return ToPyBool(mvInput::isKeyPressed(key)); + } + + PyObject* mvInput::is_key_released(PyObject* self, PyObject* args, PyObject* kwargs) + { + int key; + + if (!(mvApp::GetApp()->getParsers())["is_key_released"].parse(args, kwargs, __FUNCTION__, &key)) + return GetPyNone(); + + return ToPyBool(mvInput::isKeyReleased(key)); + } + + PyObject* mvInput::is_key_down(PyObject* self, PyObject* args, PyObject* kwargs) + { + int key; + + if (!(mvApp::GetApp()->getParsers())["is_key_down"].parse(args, kwargs, __FUNCTION__, &key)) + return GetPyNone(); + + return ToPyBool(mvInput::isKeyDown(key)); + } + + PyObject* mvInput::is_mouse_button_dragging(PyObject* self, PyObject* args, PyObject* kwargs) + { + int button; + float threshold; + + if (!(mvApp::GetApp()->getParsers())["is_mouse_button_dragging"].parse(args, kwargs, __FUNCTION__, &button, &threshold)) + return GetPyNone(); + + return ToPyBool(mvInput::isMouseDragging(button, threshold)); + } + + PyObject* mvInput::is_mouse_button_down(PyObject* self, PyObject* args, PyObject* kwargs) + { + int button; + + if (!(mvApp::GetApp()->getParsers())["is_mouse_button_down"].parse(args, kwargs, __FUNCTION__, &button)) + return GetPyNone(); + + return ToPyBool(mvInput::isMouseButtonDown(button)); + } + + PyObject* mvInput::is_mouse_button_clicked(PyObject* self, PyObject* args, PyObject* kwargs) + { + int button; + + if (!(mvApp::GetApp()->getParsers())["is_mouse_button_clicked"].parse(args, kwargs, __FUNCTION__, &button)) + return GetPyNone(); + + return ToPyBool(mvInput::isMouseButtonClicked(button)); + } + + PyObject* mvInput::is_mouse_button_double_clicked(PyObject* self, PyObject* args, PyObject* kwargs) + { + int button; + + if (!(mvApp::GetApp()->getParsers())["is_mouse_button_double_clicked"].parse(args, kwargs, __FUNCTION__, &button)) + return GetPyNone(); + + return ToPyBool(mvInput::isMouseButtonDoubleClicked(button)); + } + + PyObject* mvInput::is_mouse_button_released(PyObject* self, PyObject* args, PyObject* kwargs) + { + int button; + + if (!(mvApp::GetApp()->getParsers())["is_mouse_button_released"].parse(args, kwargs, __FUNCTION__, &button)) + return GetPyNone(); + + return ToPyBool(mvInput::isMouseButtonReleased(button)); + } + + +} diff --git a/DearPyGui/src/core/mvInput.h b/DearPyGui/src/core/mvInput.h new file mode 100644 index 000000000..2ae99a05a --- /dev/null +++ b/DearPyGui/src/core/mvInput.h @@ -0,0 +1,130 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvInput +// +// - This class is used for input polling. +// +// - When querying, it checks to make sure that the app is actually +// running to prevent invalid ImGui calls outside New/End Frame calls +// +// - May be able to remove storage and rely entirely on ImGui. Will test +// for this soon. +// +//----------------------------------------------------------------------------- + +#include "mvCore.h" +#include +#include "mvPythonParser.h" +#include "cpp.hint" +#include "mvApp.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvInput + //----------------------------------------------------------------------------- + class mvInput + { + + struct AtomicVec2 + { + std::atomic_int x; + std::atomic_int y; + }; + + struct AtomicFloatVec2 + { + std::atomic x; + std::atomic y; + }; + + public: + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(get_drawing_mouse_pos); + MV_CREATE_EXTRA_COMMAND(is_mouse_button_dragging); + MV_CREATE_EXTRA_COMMAND(is_mouse_button_down); + MV_CREATE_EXTRA_COMMAND(is_mouse_button_clicked); + MV_CREATE_EXTRA_COMMAND(is_mouse_button_double_clicked); + MV_CREATE_EXTRA_COMMAND(is_mouse_button_released); + MV_CREATE_EXTRA_COMMAND(get_mouse_drag_delta); + MV_CREATE_EXTRA_COMMAND(get_mouse_pos); + MV_CREATE_EXTRA_COMMAND(get_plot_mouse_pos); + MV_CREATE_EXTRA_COMMAND(is_key_pressed); + MV_CREATE_EXTRA_COMMAND(is_key_released); + MV_CREATE_EXTRA_COMMAND(is_key_down); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(get_drawing_mouse_pos); + MV_ADD_EXTRA_COMMAND(is_mouse_button_dragging); + MV_ADD_EXTRA_COMMAND(is_mouse_button_down); + MV_ADD_EXTRA_COMMAND(is_mouse_button_clicked); + MV_ADD_EXTRA_COMMAND(is_mouse_button_double_clicked); + MV_ADD_EXTRA_COMMAND(is_mouse_button_released); + MV_ADD_EXTRA_COMMAND(get_mouse_drag_delta); + MV_ADD_EXTRA_COMMAND(get_mouse_pos); + MV_ADD_EXTRA_COMMAND(get_plot_mouse_pos); + MV_ADD_EXTRA_COMMAND(is_key_pressed); + MV_ADD_EXTRA_COMMAND(is_key_released); + MV_ADD_EXTRA_COMMAND(is_key_down); + MV_END_EXTRA_COMMANDS + + + public: + + static void setMousePosition (float x, float y); + static void setGlobalMousePosition (float x, float y); + static void setPlotMousePosition (float x, float y); + static void setDrawingMousePosition(float x, float y); + static void setMouseDragThreshold (float threshold); + static void setMouseDragDelta (const mvVec2& delta); + + static int getMouseDragThreshold (); + static mvVec2 getMouseDragDelta (); + static mvVec2 getMousePosition (); + static mvVec2 getGlobalMousePosition (); + static mvVec2 getPlotMousePosition (); + static mvVec2 getDrawingMousePosition(); + + static bool isMouseDragging (int button, float threshold); + static bool isMouseButtonDown (int button); + static bool isMouseButtonClicked (int button); + static bool isMouseButtonDoubleClicked(int button); + static bool isMouseButtonReleased (int button); + static bool isKeyDown (int keycode); + static bool isKeyPressed (int keycode); + static bool isKeyReleased (int keycode); + + static void InsertConstants(std::vector>& constants); + + static void CheckInputs(); + + private: + + static AtomicVec2 s_mousePos; + static AtomicVec2 s_mouseGlobalPos; + static AtomicFloatVec2 s_mousePlotPos; + static AtomicVec2 s_mouseDrawingPos; + static std::atomic_int s_mouseDragThreshold; + static AtomicVec2 s_mouseDragDelta; + + // keys + static std::atomic_bool s_keysdown[512]; + static std::atomic_int s_keysdownduration[512]; // 1/100 seconds + static std::atomic_bool s_keyspressed[512]; + static std::atomic_bool s_keysreleased[512]; + + // mouse + static std::atomic_int s_mousewheel; + static std::atomic_bool s_mousedown[5]; + static std::atomic_bool s_mouseDragging[5]; + static std::atomic_int s_mousedownduration[5]; // 1/100 seconds + static std::atomic_bool s_mouseclick[5]; + static std::atomic_bool s_mousedoubleclick[5]; + static std::atomic_bool s_mousereleased[5]; + + }; + +} diff --git a/DearPyGui/src/core/mvLog.cpp b/DearPyGui/src/core/mvLog.cpp new file mode 100644 index 000000000..e8f17f125 --- /dev/null +++ b/DearPyGui/src/core/mvLog.cpp @@ -0,0 +1,45 @@ +#include "mvLog.h" + +namespace Marvel { + + bool mvLog::s_initialized = false; + + void mvLog::Init() + { +#ifdef MV_LOG + s_initialized = true; + spdlog::set_pattern("%^[%T] %t %n:%$ %v"); + GetCoreLogger()->set_level(spdlog::level::trace); + GetEventLogger()->set_level(spdlog::level::info); + GetItemRegistryLogger()->set_level(spdlog::level::info); +#endif // MV_LOG + } + + void mvLog::Cleanup() + { + s_initialized = false; +#ifdef MV_LOG + spdlog::shutdown(); +#endif // MV_LOG + } + +#ifdef MV_LOG + std::shared_ptr& mvLog::GetCoreLogger() + { + static auto coreLogger = spdlog::create_async("[CORE]"); + return coreLogger; + } + + std::shared_ptr& mvLog::GetEventLogger() + { + static auto eventLogger = spdlog::create_async("[EVENT]"); + return eventLogger; + } + + std::shared_ptr& mvLog::GetItemRegistryLogger() + { + static auto eventLogger = spdlog::create_async("[ITEM REGISTRY]"); + return eventLogger; + } +#endif // MV_LOG +} diff --git a/DearPyGui/src/core/mvLog.h b/DearPyGui/src/core/mvLog.h new file mode 100644 index 000000000..bc00f6ac4 --- /dev/null +++ b/DearPyGui/src/core/mvLog.h @@ -0,0 +1,71 @@ +#pragma once +#include +#include + +#ifdef MV_LOG +#include "spdlog/spdlog.h" +#include "spdlog/async.h" +#include "spdlog/fmt/ostr.h" +#include "spdlog/sinks/stdout_color_sinks.h" +#endif // MV_LOG + +namespace Marvel { + + class mvLog + { + + public: + + static void Init(); + static void Cleanup(); + static bool IsInitialized() { return s_initialized; } + +#ifdef MV_LOG + static std::shared_ptr& GetCoreLogger(); + static std::shared_ptr& GetEventLogger(); + static std::shared_ptr& GetItemRegistryLogger(); +#endif // MV_LOG + + private: + + static bool s_initialized; + }; +} + +#ifdef MV_LOG + #define MV_CORE_TRACE(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetCoreLogger()->trace(__VA_ARGS__) + #define MV_CORE_INFO(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetCoreLogger()->info(__VA_ARGS__) + #define MV_CORE_WARN(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetCoreLogger()->warn(__VA_ARGS__) + #define MV_CORE_ERROR(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetCoreLogger()->error(__VA_ARGS__) + #define MV_CORE_FATAL(...) if(Marvel::mvLog::IsInitialized()){Marvel::mvLog::GetCoreLogger()->critical(__VA_ARGS__);assert(false);} + + #define MV_EVENT_TRACE(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetEventLogger()->trace(__VA_ARGS__) + #define MV_EVENT_INFO(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetEventLogger()->info(__VA_ARGS__) + #define MV_EVENT_WARN(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetEventLogger()->warn(__VA_ARGS__) + #define MV_EVENT_ERROR(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetEventLogger()->error(__VA_ARGS__) + #define MV_EVENT_FATAL(...) if(Marvel::mvLog::IsInitialized()){Marvel::mvLog::GetEventLogger()->critical(__VA_ARGS__);assert(false);} + + #define MV_ITEM_REGISTRY_TRACE(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetItemRegistryLogger()->trace(__VA_ARGS__) + #define MV_ITEM_REGISTRY_INFO(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetItemRegistryLogger()->info(__VA_ARGS__) + #define MV_ITEM_REGISTRY_WARN(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetItemRegistryLogger()->warn(__VA_ARGS__) + #define MV_ITEM_REGISTRY_ERROR(...) if(Marvel::mvLog::IsInitialized())Marvel::mvLog::GetItemRegistryLogger()->error(__VA_ARGS__) + #define MV_ITEM_REGISTRY_FATAL(...) if(Marvel::mvLog::IsInitialized()){Marvel::mvLog::GetItemRegistryLogger()->critical(__VA_ARGS__);assert(false);} +#else + #define MV_CORE_TRACE(...) // + #define MV_CORE_INFO(...) // + #define MV_CORE_WARN(...) // + #define MV_CORE_ERROR(...) // + #define MV_CORE_FATAL(...) // + + #define MV_EVENT_TRACE(...) // + #define MV_EVENT_INFO(...) // + #define MV_EVENT_WARN(...) // + #define MV_EVENT_ERROR(...) // + #define MV_EVENT_FATAL(...) // + + #define MV_ITEM_REGISTRY_TRACE(...) // + #define MV_ITEM_REGISTRY_INFO(...) // + #define MV_ITEM_REGISTRY_WARN(...) // + #define MV_ITEM_REGISTRY_ERROR(...) // + #define MV_ITEM_REGISTRY_FATAL(...) // +#endif diff --git a/DearPyGui/src/core/mvProfiler.cpp b/DearPyGui/src/core/mvProfiler.cpp new file mode 100644 index 000000000..5490904c8 --- /dev/null +++ b/DearPyGui/src/core/mvProfiler.cpp @@ -0,0 +1,74 @@ +#include "mvProfiler.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvInstrumentor + //----------------------------------------------------------------------------- + void mvInstrumentor::BeginSession(const std::string& name) + { + if (m_CurrentSession) + { + // If there is already a current session, then close it before beginning new one. + // Subsequent profiling output meant for the original session will end up in the + // newly opened session instead. That's better than having badly formatted + // profiling output. + + InternalEndSession(); + } + + } + + void mvInstrumentor::EndSession() + { + InternalEndSession(); + } + + void mvInstrumentor::WriteProfile(const mvProfileResult& result) + { + + m_results[result.Name] = result.ElapsedTime; + + } + + mvInstrumentor& mvInstrumentor::Get() + { + static mvInstrumentor instance; + return instance; + } + + void mvInstrumentor::InternalEndSession() { + if (m_CurrentSession) + { + delete m_CurrentSession; + m_CurrentSession = nullptr; + } + } + + //----------------------------------------------------------------------------- + // mvInstrumentationTimer + //----------------------------------------------------------------------------- + mvInstrumentationTimer::mvInstrumentationTimer(const char* name) + : m_Name(name), m_Stopped(false) + { + m_StartTimepoint = std::chrono::steady_clock::now(); + } + + mvInstrumentationTimer::~mvInstrumentationTimer() + { + if (!m_Stopped) + Stop(); + } + + void mvInstrumentationTimer::Stop() + { + auto endTimepoint = std::chrono::steady_clock::now(); + auto highResStart = FloatingPointMicroseconds{ m_StartTimepoint.time_since_epoch() }; + auto elapsedTime = std::chrono::time_point_cast(endTimepoint).time_since_epoch() - std::chrono::time_point_cast(m_StartTimepoint).time_since_epoch(); + + mvInstrumentor::Get().WriteProfile({ m_Name, highResStart, elapsedTime }); + + m_Stopped = true; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvProfiler.h b/DearPyGui/src/core/mvProfiler.h new file mode 100644 index 000000000..1d22ac443 --- /dev/null +++ b/DearPyGui/src/core/mvProfiler.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include + +namespace Marvel { + + using FloatingPointMicroseconds = std::chrono::duration; + + //----------------------------------------------------------------------------- + // Useful structs + //----------------------------------------------------------------------------- + struct mvProfileResult + { + std::string Name; + FloatingPointMicroseconds Start; + std::chrono::microseconds ElapsedTime; + }; + + struct mvInstrumentationSession + { + std::string Name; + }; + + //----------------------------------------------------------------------------- + // mvInstrumentor + //----------------------------------------------------------------------------- + class mvInstrumentor + { + + public: + + mvInstrumentor() : m_CurrentSession(nullptr) {} + + // Call to begin recording profile data (must call end session at a later time) + void BeginSession(const std::string& name); + + // Call to end recording profile data + void EndSession(); + + // Used to write data to the profiling file + void WriteProfile(const mvProfileResult& result); + + const std::map& getResults() const { return m_results; } + + static mvInstrumentor& Get(); + + private: + + // Note: you must already own lock on m_Mutex before + // calling InternalEndSession() + void InternalEndSession(); + + private: + + mvInstrumentationSession* m_CurrentSession; + std::map m_results; + + }; + + //----------------------------------------------------------------------------- + // mvInstrumentationTimer + //----------------------------------------------------------------------------- + class mvInstrumentationTimer + { + + public: + + mvInstrumentationTimer(const char* name); + + ~mvInstrumentationTimer(); + + void Stop(); + + private: + + const char* m_Name; + bool m_Stopped; + std::chrono::time_point m_StartTimepoint; + + }; + +} + +#if defined(MV_PROFILE) && defined(MV_DEBUG) + +#define MV_PROFILE_BEGIN_SESSION(name) ::Marvel::mvInstrumentor::Get().BeginSession(name) +#define MV_PROFILE_END_SESSION() ::Marvel::mvInstrumentor::Get().EndSession() +#define MV_PROFILE_SCOPE(name) ::Marvel::mvInstrumentationTimer timer##__LINE__(name); +#define MV_PROFILE_FUNCTION() MV_PROFILE_SCOPE(__FUNCSIG__) + +#else + #define MV_PROFILE_BEGIN_SESSION(name) + #define MV_PROFILE_END_SESSION() + #define MV_PROFILE_SCOPE(name) + #define MV_PROFILE_FUNCTION() +#endif \ No newline at end of file diff --git a/DearPyGui/src/core/mvPython.h b/DearPyGui/src/core/mvPython.h new file mode 100644 index 000000000..a6b4ce3b5 --- /dev/null +++ b/DearPyGui/src/core/mvPython.h @@ -0,0 +1,14 @@ +#pragma once +#include "mvCore.h" + +class PyContextManager {}; +#define mvCallable PyObject* +#define mvCallableData PyObject* +#define PY_SSIZE_T_CLEAN +#include +#include +#include "mvPyObject.h" +#include "mvPythonExceptions.h" +#include "mvPythonParser.h" +#include "mvPythonTranslator.h" +#include "mvGlobalIntepreterLock.h" diff --git a/DearPyGui/src/core/mvThreadPool.h b/DearPyGui/src/core/mvThreadPool.h new file mode 100644 index 000000000..412cdd9ea --- /dev/null +++ b/DearPyGui/src/core/mvThreadPool.h @@ -0,0 +1,368 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvThreadPool +// +// - This is a simple thread pool implementation from our repository at +// https://github.com/hoffstadt/mvThreadPool +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mvCore.h" + +namespace Marvel { + + //----------------------------------------------------------------------------- + // mvQueue + //----------------------------------------------------------------------------- + template + class mvQueue + { + + public: + + struct node + { + std::shared_ptr data; + std::unique_ptr next; + }; + + public: + + mvQueue() : m_head(new node), m_tail(m_head.get()) {} + + // copy assignment and constructor deleted + mvQueue(const mvQueue& other) = delete; + mvQueue& operator=(const mvQueue& other) = delete; + + std::shared_ptr wait_and_pop() + { + std::unique_ptr const old_head = wait_pop_head(); + return old_head->data; + } + + std::shared_ptr try_pop() + { + std::unique_ptr const old_head = try_pop_head(); + return old_head ? old_head->data : std::shared_ptr(); + } + + void wait_and_pop(T& value) + { + std::unique_ptr const old_head = wait_pop_head(value); + } + + bool try_pop(T& value) + { + std::unique_ptr const old_head = try_pop_head(value); + if (old_head) + return true; + return false; + } + + void push(T value) + { + std::shared_ptr new_data = std::make_shared(std::move(value)); + auto p = std::make_unique(); + + // scoped in order to unlock tail mutex before notifying other threads + { + std::lock_guard tail_lock(m_tail_mutex); + m_tail->data = new_data; + node* const new_tail = p.get(); + m_tail->next = std::move(p); + m_tail = new_tail; + } + + m_data_cond.notify_one(); + } + + bool empty() + { + std::lock_guard head_lock(m_head_mutex); + return (m_head.get() == get_tail()); + } + + private: + + node* get_tail() + { + std::lock_guard tail_lock(m_tail_mutex); + return m_tail; + } + + std::unique_ptr pop_head() + { + std::unique_ptr old_head = std::move(m_head); + m_head = std::move(old_head->next); + return old_head; + } + + std::unique_ptr try_pop_head() + { + std::lock_guard head_lock(m_head_mutex); + if (m_head.get() == get_tail()) + return std::unique_ptr(); + return pop_head(); + } + + std::unique_ptr try_pop_head(T& value) + { + std::lock_guard head_lock(m_head_mutex); + if (m_head.get() == get_tail()) + return std::unique_ptr(); + + value = std::move(*m_head->data); + return pop_head(); + } + + std::unique_ptr wait_pop_head() + { + std::unique_lock head_lock(wait_for_data()); + return pop_head(); + } + + std::unique_ptr wait_pop_head(T& value) + { + std::unique_lock head_lock(wait_for_data()); + value = std::move(*m_head->data); + return pop_head(); + } + + std::unique_lock wait_for_data() + { + std::unique_lock head_lock(m_head_mutex); + m_data_cond.wait(head_lock, [&] {return m_head.get() != get_tail(); }); + return head_lock; + } + + private: + + std::mutex m_head_mutex; + std::mutex m_tail_mutex; + std::unique_ptr m_head; + node* m_tail; + std::condition_variable m_data_cond; + + }; + + //----------------------------------------------------------------------------- + // mvThreadJoiner + //----------------------------------------------------------------------------- + class mvThreadJoiner + { + + public: + + explicit mvThreadJoiner(std::vector& threads) + : m_threads(threads) + { + + } + + ~mvThreadJoiner() + { + for(auto& thread : m_threads) + if(thread.joinable()) + thread.join(); + } + + private: + + std::vector& m_threads; + + }; + + //----------------------------------------------------------------------------- + // mvWorkStealingQueue + //----------------------------------------------------------------------------- + class mvWorkStealingQueue + { + + public: + + mvWorkStealingQueue() {} + ~mvWorkStealingQueue() = default; + + // deleted copy constructor/assignment operator. + mvWorkStealingQueue(const mvWorkStealingQueue& other) = delete; + mvWorkStealingQueue& operator=(const mvWorkStealingQueue& other) = delete; + + void push(mvFunctionWrapper data) + { + std::lock_guard lock(m_mutex); + m_queue.push_front(std::move(data)); + } + + bool empty() const + { + std::lock_guard lock(m_mutex); + return m_queue.empty(); + } + + bool try_pop(mvFunctionWrapper& res) + { + std::lock_guard lock(m_mutex); + if (m_queue.empty()) + return false; + + res = std::move(m_queue.front()); + m_queue.pop_front(); + return true; + } + + bool try_steal(mvFunctionWrapper& res) + { + std::lock_guard lock(m_mutex); + if (m_queue.empty()) + return false; + + res = std::move(m_queue.back()); + m_queue.pop_back(); + return true; + } + + private: + + std::deque m_queue; + mutable std::mutex m_mutex; + + }; + + //----------------------------------------------------------------------------- + // mvThreadPool + //----------------------------------------------------------------------------- + class mvThreadPool + { + + typedef mvFunctionWrapper task_type; + + public: + + explicit mvThreadPool(unsigned threadcount) : + m_done(false), m_joiner(m_threads) + { + + unsigned thread_count = threadcount; + + if (threadcount == 0) + thread_count = std::thread::hardware_concurrency(); + + try + { + + for (unsigned i = 0; i < thread_count; ++i) + m_queues.push_back(std::make_unique()); + + for (unsigned i = 0; i < thread_count; ++i) + m_threads.emplace_back( + &mvThreadPool::worker_thread, this, i); + + } + catch (...) + { + m_done = true; + throw; + } + } + + ~mvThreadPool() { m_done = true; } + + bool isReadyToDelete() const { return m_taskCount == 0; } + + void setDone() { m_done = true; } + + static const char* getVersion() { return "v0.2"; } + + template + std::future::type> submit(F f) + { + typedef typename std::invoke_result::type result_type; + std::packaged_task task(std::move(f)); + std::future res(task.get_future()); + m_done = false; + m_taskCount++; + if (m_local_work_queue) + m_local_work_queue->push(std::move(task)); + else + m_pool_work_queue.push(std::move(task)); + + return res; + } + + private: + + void worker_thread(unsigned index) + { + m_index = index; + + m_local_work_queue = m_queues[m_index].get(); + + while (!m_done || !isReadyToDelete()) + run_pending_task(); + } + + void run_pending_task() + { + task_type task; + if (pop_task_from_local_queue(task) || + pop_task_from_pool_queue(task) || + pop_task_from_other_thread_queue(task)) + { + task(); + m_taskCount--; + } + + else + std::this_thread::yield(); + + + } + + bool pop_task_from_local_queue(task_type& task) + { + return m_local_work_queue && m_local_work_queue->try_pop(task); + } + + bool pop_task_from_pool_queue(task_type& task) + { + return m_pool_work_queue.try_pop(task); + } + + bool pop_task_from_other_thread_queue(task_type& task) + { + for (unsigned i = 0; i < m_queues.size(); i++) + { + const unsigned index = (m_index + i + 1) % m_queues.size(); + if (m_queues[index]->try_steal(task)) + return true; + } + + return false; + } + + private: + + std::atomic_bool m_done; + mvQueue m_pool_work_queue; + std::vector > m_queues; + std::vector m_threads; + mvThreadJoiner m_joiner; + static thread_local mvWorkStealingQueue* m_local_work_queue; + static thread_local unsigned m_index; + std::atomic_int m_taskCount = 0; + + }; + + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvUtilities.h b/DearPyGui/src/core/mvUtilities.h new file mode 100644 index 000000000..3490d2b86 --- /dev/null +++ b/DearPyGui/src/core/mvUtilities.h @@ -0,0 +1,22 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvUtilities +// +// - This file contains typically platform specific functions. May need +// to rename to a more appropriate name. +// +//----------------------------------------------------------------------------- + +#include +#include +#include "mvTextureStorage.h" + +namespace Marvel { + + bool UnloadTexture (const std::string& filename); + bool LoadTextureFromArray(const char* name, float* data, unsigned width, unsigned height, mvTexture& storage, mvTextureFormat format); + bool LoadTextureFromFile (const char* filename, mvTexture& storage); + void FreeTexture (mvTexture& storage); + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvViewport.cpp b/DearPyGui/src/core/mvViewport.cpp new file mode 100644 index 000000000..ddfeb5155 --- /dev/null +++ b/DearPyGui/src/core/mvViewport.cpp @@ -0,0 +1,190 @@ +#include "mvViewport.h" +#include "mvApp.h" +#include "mvCallbackRegistry.h" +#include +#include + +namespace Marvel { + + mvViewport::mvViewport(unsigned width, unsigned height, bool error) : + m_error(error), m_width(width), m_height(height) + { + + m_app = mvApp::GetApp(); + + if (m_error) + { + mvAppLog::ShowMain(); + mvAppLog::setSize(width, height); + } + + } + + void mvViewport::InsertParser(std::map* parsers) + { + parsers->insert({ "create_viewport", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::String, "title"}, + {mvPythonDataType::Integer, "width"}, + {mvPythonDataType::Integer, "height"}, + {mvPythonDataType::Integer, "x_pos"}, + {mvPythonDataType::Integer, "y_pos"}, + {mvPythonDataType::Bool, "resizable"}, + {mvPythonDataType::Bool, "vsync"}, + {mvPythonDataType::Bool, "always_on_top"}, + {mvPythonDataType::Bool, "maximized_box"}, + {mvPythonDataType::Bool, "minimized_box"}, + {mvPythonDataType::Bool, "border"}, + {mvPythonDataType::Bool, "caption"}, + {mvPythonDataType::Bool, "overlapped"}, + {mvPythonDataType::Integer, "min_width"}, + {mvPythonDataType::Integer, "max_width"}, + {mvPythonDataType::Integer, "min_height"}, + {mvPythonDataType::Integer, "max_height"}, + }, "Creates a viewport") }); + + parsers->insert({ "show_viewport", mvPythonParser({ + {mvPythonDataType::KeywordOnly}, + {mvPythonDataType::Bool, "minimized"}, + {mvPythonDataType::Bool, "maximized"}, + }, "Shows viewport") }); + + parsers->insert({ "configure_viewport", mvPythonParser({ + {mvPythonDataType::Kwargs, "**Kwargs"}, + }, "Shows viewport") }); + + parsers->insert({ "maximize_viewport", mvPythonParser({ + }, "Maximizes viewport", "None") }); + + parsers->insert({ "minimize_viewport", mvPythonParser({ + }, "Minimizes viewport", "None") }); + + } + + void mvViewport::onResizeEvent() + { + mvApp::GetApp()->getCallbackRegistry().addCallback( + mvApp::GetApp()->getCallbackRegistry().getResizeCallback(), + "Main Application", nullptr); + } + + void mvViewport::setConfigDict(PyObject* dict) + { + if (dict == nullptr) + return; + + if (PyObject* item = PyDict_GetItemString(dict, "x_pos")) { m_posDirty = true; m_xpos = ToInt(item);} + if (PyObject* item = PyDict_GetItemString(dict, "y_pos")) { m_posDirty = true; m_ypos = ToInt(item);} + if (PyObject* item = PyDict_GetItemString(dict, "width")) { m_sizeDirty = true; m_actualWidth = ToInt(item);} + if (PyObject* item = PyDict_GetItemString(dict, "height")) { m_sizeDirty = true; m_actualHeight = ToInt(item);} + if (PyObject* item = PyDict_GetItemString(dict, "resizable")) m_resizable = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "vsync")) m_vsync = ToBool(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_width")) m_minwidth = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_width")) m_maxwidth = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "min_height")) m_minheight = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "max_height")) m_maxheight = ToInt(item); + if (PyObject* item = PyDict_GetItemString(dict, "always_on_top")) { m_modesDirty = true; m_alwaysOnTop = ToBool(item); } + if (PyObject* item = PyDict_GetItemString(dict, "maximized_box")) { m_modesDirty = true; m_maximizeBox = ToBool(item); } + if (PyObject* item = PyDict_GetItemString(dict, "minimized_box")) { m_modesDirty = true; m_minimizeBox = ToBool(item); } + if (PyObject* item = PyDict_GetItemString(dict, "border")) { m_modesDirty = true; m_border = ToBool(item); } + if (PyObject* item = PyDict_GetItemString(dict, "title")) { m_modesDirty = true; m_title = ToString(item); } + if (PyObject* item = PyDict_GetItemString(dict, "caption")) { m_modesDirty = true; m_caption = ToBool(item); } + if (PyObject* item = PyDict_GetItemString(dict, "overlapped")) { m_modesDirty = true; m_overlapped = ToBool(item); } + + if (m_sizeDirty) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, { + CreateEventArgument("actual_width", m_actualWidth), + CreateEventArgument("actual_height", m_actualHeight), + CreateEventArgument("client_width", m_actualWidth), + CreateEventArgument("client_height", m_actualHeight) + }); + } + + } + + PyObject* mvViewport::create_viewport(PyObject* self, PyObject* args, PyObject* kwargs) + { + const char* title = "Dear PyGui"; + int width = 1280; + int height = 800; + int x_pos = 100; + int y_pos = 100; + int resizable = true; + int vsync = true; + int always_on_top = true; + int maximized_box = true; + int minimized_box = true; + int border = true; + int caption = true; + int overlapped = true; + int min_width = 250; + int max_width = 10000; + int min_height = 250; + int max_height = 10000; + + + if (!(mvApp::GetApp()->getParsers())["create_viewport"].parse(args, kwargs, __FUNCTION__, + &title, &width, &height, &x_pos, &y_pos, &resizable, &vsync, &always_on_top, + &maximized_box, &minimized_box, &border, &caption, &overlapped, + &min_width, &max_width, &min_height, &max_height)) + return GetPyNone(); + + mvViewport* viewport = CreateViewport(width, height, false); + viewport->setConfigDict(kwargs); + + mvApp::GetApp()->setViewport(viewport); + + return GetPyNone(); + } + + PyObject* mvViewport::show_viewport(PyObject* self, PyObject* args, PyObject* kwargs) + { + int minimized = false; + int maximized = false; + + if (!(mvApp::GetApp()->getParsers())["show_viewport"].parse(args, kwargs, __FUNCTION__, + &minimized, &maximized)) + return GetPyNone(); + + mvViewport* viewport = mvApp::GetApp()->getViewport(); + if (viewport) + viewport->show(minimized, maximized); + + return GetPyNone(); + } + + PyObject* mvViewport::configure_viewport(PyObject* self, PyObject* args, PyObject* kwargs) + { + + mvViewport* viewport = mvApp::GetApp()->getViewport(); + if (viewport) + viewport->setConfigDict(kwargs); + + return GetPyNone(); + } + + PyObject* mvViewport::maximize_viewport(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getViewport()->maximize(); + }); + + return GetPyNone(); + } + + PyObject* mvViewport::minimize_viewport(PyObject* self, PyObject* args, PyObject* kwargs) + { + std::lock_guard lk(mvApp::GetApp()->getMutex()); + mvApp::GetApp()->getCallbackRegistry().submit([=]() + { + mvApp::GetApp()->getViewport()->minimize(); + }); + + return GetPyNone(); + } + +} \ No newline at end of file diff --git a/DearPyGui/src/core/mvViewport.h b/DearPyGui/src/core/mvViewport.h new file mode 100644 index 000000000..d7aa3f27d --- /dev/null +++ b/DearPyGui/src/core/mvViewport.h @@ -0,0 +1,114 @@ +#pragma once + +//----------------------------------------------------------------------------- +// mvWindow +// +// - This abstract class is just a light wrapper for a platform specific +// window. It's quite lacking so may need to be extended later. +// +// - This class may need to be renamed to remove confusion between this +// window and the mvWindowAppItem class (maybe to viewport?) +// +//----------------------------------------------------------------------------- + +#include "mvApp.h" +#include "mvEvents.h" +#include "mvPython.h" +#include "cpp.hint" + +namespace Marvel { + + class mvApp; + + //----------------------------------------------------------------------------- + // mvViewport + //----------------------------------------------------------------------------- + class mvViewport + { + + public: + + + static void InsertParser(std::map* parsers); + + MV_CREATE_EXTRA_COMMAND(show_viewport); + MV_CREATE_EXTRA_COMMAND(create_viewport); + MV_CREATE_EXTRA_COMMAND(configure_viewport); + + // viewport operations + MV_CREATE_EXTRA_COMMAND(maximize_viewport); + MV_CREATE_EXTRA_COMMAND(minimize_viewport); + + MV_START_EXTRA_COMMANDS + MV_ADD_EXTRA_COMMAND(show_viewport) + MV_ADD_EXTRA_COMMAND(create_viewport) + MV_ADD_EXTRA_COMMAND(configure_viewport) + MV_ADD_EXTRA_COMMAND(maximize_viewport) + MV_ADD_EXTRA_COMMAND(minimize_viewport) + MV_END_EXTRA_COMMANDS + + static mvViewport* CreateViewport(unsigned width, unsigned height, bool error = false); + + mvViewport(unsigned width, unsigned height, bool error = false); + virtual ~mvViewport() = default; + + void setConfigDict(PyObject* dict); + + virtual void invalidateObjects() {} + + virtual void show (bool minimized, bool maximized) {} + virtual void run () {} + virtual void setup () {} + virtual void renderFrame() {} + + virtual void maximize() {} + virtual void minimize() {} + virtual void restore() {} + + void stop() { m_running = false; } + bool running() const { return m_running; } + + // for use by primary window + int getClientWidth() const { return (int)m_clientWidth; } + int getClientHeight() const { return (int)m_clientHeight; } + void onResizeEvent(); + + protected: + + bool m_running = true; + mvApp* m_app = nullptr; + bool m_error = false; + std::string m_title = "DearPyGui"; + + + // window modes + bool m_modesDirty = false; + bool m_vsync = true; + bool m_resizable = true; + bool m_alwaysOnTop = false; + bool m_maximizeBox = true; + bool m_minimizeBox = true; + bool m_border = true; + bool m_caption = true; + bool m_overlapped = true; + + // position/size + bool m_sizeDirty = false; + bool m_posDirty = false; + unsigned m_width; + unsigned m_minwidth = 250; + unsigned m_maxwidth = 10000; + unsigned m_height; + unsigned m_minheight = 250; + unsigned m_maxheight = 10000; + int m_actualWidth = 1280; + int m_actualHeight = 800; + int m_clientWidth = 1280; + int m_clientHeight = 800; + int m_xpos = 100; + int m_ypos = 100; + + + }; + +} diff --git a/DearPyGui/src/platform/Apple/mvAppleUtilities.mm b/DearPyGui/src/platform/Apple/mvAppleUtilities.mm new file mode 100644 index 000000000..179b376e8 --- /dev/null +++ b/DearPyGui/src/platform/Apple/mvAppleUtilities.mm @@ -0,0 +1,87 @@ +#include "mvUtilities.h" +#include "mvAppleViewport.h" + +#define STB_IMAGE_IMPLEMENTATION +#include + +#include +#include +#include +#include +#include + +// this is necessary to keep objective-c's reference counts +// from reaching 0. +static std::vector>> g_textures; + +namespace Marvel { + + bool LoadTextureFromArray(const char* name, float* data, unsigned width, unsigned height, mvTexture& storage, mvTextureFormat format) + { + + MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:width height:height mipmapped:NO]; + + + textureDescriptor.usage = MTLTextureUsageShaderRead; + textureDescriptor.storageMode = MTLStorageModeManaged; + + id texture = [mvAppleViewport::GetDevice() newTextureWithDescriptor:textureDescriptor]; + [texture replaceRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0 withBytes:data bytesPerRow:width * 4 * 4]; + + g_textures.push_back({name, texture}); + + storage.texture = (__bridge void*)g_textures.back().second; + storage.width = width; + storage.height = height; + + return true; + } + + bool LoadTextureFromFile(const char* filename, mvTexture& storage) + { + int width, height; + + unsigned char* image_data = stbi_load(filename, &width, &height, nullptr, 4); + if (image_data == nullptr) + return false; + + MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:width + height:height + mipmapped:NO]; + textureDescriptor.usage = MTLTextureUsageShaderRead; + textureDescriptor.storageMode = MTLStorageModeManaged; + + id texture = [mvAppleViewport::GetDevice() newTextureWithDescriptor:textureDescriptor]; + [texture replaceRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0 withBytes:image_data bytesPerRow:width * 4]; + + g_textures.push_back({filename, texture}); + + storage.texture = (__bridge void*)g_textures.back().second; + storage.width = width; + storage.height = height; + + return true; + } + + bool UnloadTexture(const std::string& filename) + { + std::vector>> oldtextures = g_textures; + g_textures.clear(); + for(auto& texture : oldtextures) + { + if(texture.first != filename) + g_textures.push_back(texture); + } + return true; + } + + void FreeTexture(mvTexture& storage) + { + id out_srv = (__bridge id )storage.texture; + + // ARC should take care of this but I'm not sure. This needs to be checked. + + } + +} diff --git a/DearPyGui/src/platform/Apple/mvAppleViewport.h b/DearPyGui/src/platform/Apple/mvAppleViewport.h new file mode 100644 index 000000000..128e8a67f --- /dev/null +++ b/DearPyGui/src/platform/Apple/mvAppleViewport.h @@ -0,0 +1,38 @@ +#pragma once + +#include "mvViewport.h" +#import +#import + +struct GLFWwindow; + +namespace Marvel { + + class mvAppleViewport : public mvViewport + { + + public: + + mvAppleViewport(unsigned width, unsigned height, bool error = false); + ~mvAppleViewport(); + + void show(bool minimized, bool maximized) override; + void renderFrame() override; + void maximize() override; + void minimize() override; + void restore() override; + + static id GetDevice() { return device; } + + private: + + float m_clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + + GLFWwindow *m_window; + CAMetalLayer *m_layer; + MTLRenderPassDescriptor *m_renderPassDescriptor; + id m_commandQueue; + static id device; + + }; +} diff --git a/DearPyGui/src/platform/Apple/mvAppleViewport.mm b/DearPyGui/src/platform/Apple/mvAppleViewport.mm new file mode 100644 index 000000000..385a72a7d --- /dev/null +++ b/DearPyGui/src/platform/Apple/mvAppleViewport.mm @@ -0,0 +1,263 @@ +#include "mvAppleViewport.h" +#include "mvAppLog.h" +#include +#include "imnodes.h" +#include "mvTextureStorage.h" +#include "mvFontManager.h" + +#define GLFW_INCLUDE_NONE +#define GLFW_EXPOSE_NATIVE_COCOA +#include +#include + +#include "imgui.h" +#include "implot.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_metal.h" +#include + +namespace Marvel { + + id mvAppleViewport::device; + + mvViewport* mvViewport::CreateViewport(unsigned width, unsigned height, bool error) + { + return new mvAppleViewport(width, height, error); + } + + static void window_close_callback(GLFWwindow* window) + { + mvApp::StopApp(); + } + + static void window_size_callback(GLFWwindow* window, int width, int height) + { + + mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, { + CreateEventArgument("actual_width", width), + CreateEventArgument("actual_height", height), + CreateEventArgument("client_width", width), + CreateEventArgument("client_height", height) + }); + } + + static void glfw_error_callback(int error, const char *description) + { + fprintf(stderr, "Glfw Error %d: %s\n", error, description); + } + + mvAppleViewport::mvAppleViewport(unsigned width, unsigned height, bool error) + : mvViewport(width, height, error) + { + } + + mvAppleViewport::~mvAppleViewport() + { + // Cleanup + ImGui_ImplMetal_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + imnodes::Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + glfwDestroyWindow(m_window); + glfwTerminate(); + + } + + void mvAppleViewport::show(bool minimized, bool maximized) + { + + // Setup window + glfwSetErrorCallback(glfw_error_callback); + glfwInit(); + + if (!m_resizable) + glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); + if(m_alwaysOnTop) + glfwWindowHint(GLFW_FLOATING, GLFW_TRUE); + if(maximized) + glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE); + else if(minimized) + glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE); + if(!m_caption) + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); + glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GLFW_FALSE); + + + // Create window with graphics context + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE); + m_window = glfwCreateWindow((int)m_actualWidth, (int)m_actualHeight, m_title.c_str(), nullptr, nullptr); + glfwSetWindowPos(m_window, m_xpos, m_ypos); + glfwSetWindowSizeLimits(m_window, (int)m_minwidth, (int)m_minheight, (int)m_maxwidth, (int)m_maxheight); + + + mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, { + CreateEventArgument("actual_width", (int)m_actualWidth), + CreateEventArgument("actual_height", (int)m_actualHeight), + CreateEventArgument("client_width", (int)m_actualWidth), + CreateEventArgument("client_height", (int)m_actualHeight) + }); + + device = MTLCreateSystemDefaultDevice();; + m_commandQueue = [device newCommandQueue]; + + // Setup Dear ImGui binding + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + imnodes::Initialize(); + ImGuiIO &io = ImGui::GetIO(); + io.ConfigWindowsMoveFromTitleBarOnly = true; + io.IniFilename = nullptr; + (void) io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + if(mvApp::GetApp()->m_docking) + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + if (mvApp::GetApp()->m_dockingShiftOnly) + io.ConfigDockingWithShift = true; + + // Setup style + ImGui::StyleColorsDark(); + + ImGui_ImplGlfw_InitForOpenGL(m_window, true); + ImGui_ImplMetal_Init(device); + + NSWindow *nswin = glfwGetCocoaWindow(m_window); + m_layer = [CAMetalLayer layer]; + m_layer.device = device; + m_layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + nswin.contentView.layer = m_layer; + nswin.contentView.wantsLayer = YES; + + m_renderPassDescriptor = [MTLRenderPassDescriptor new]; + + // Setup callbacks + glfwSetWindowSizeCallback(m_window, window_size_callback); + //glfwSetFramebufferSizeCallback(m_window, window_size_callback); + glfwSetWindowCloseCallback(m_window, window_close_callback); + } + + void mvAppleViewport::maximize() + { + glfwMaximizeWindow(m_window); + } + + void mvAppleViewport::minimize() + { + glfwIconifyWindow(m_window); + } + + void mvAppleViewport::restore() + { + glfwRestoreWindow(m_window); + } + + void mvAppleViewport::renderFrame() + { + m_running = !glfwWindowShouldClose(m_window); + + if(m_posDirty) + { + glfwSetWindowPos(m_window, m_xpos, m_ypos); + m_posDirty = false; + } + + if(m_sizeDirty) + { + glfwSetWindowSizeLimits(m_window, (int)m_minwidth, (int)m_minheight, (int)m_maxwidth, (int)m_maxheight); + glfwSetWindowSize(m_window, m_actualWidth, m_actualHeight); + m_sizeDirty = false; + } + + if(m_modesDirty) + { + glfwSetWindowTitle(m_window, m_title.c_str()); + glfwSetWindowAttrib(m_window, GLFW_RESIZABLE, m_resizable ? GLFW_TRUE : GLFW_FALSE); + glfwSetWindowAttrib(m_window, GLFW_DECORATED, m_caption ? GLFW_TRUE : GLFW_FALSE); + glfwSetWindowAttrib(m_window, GLFW_FLOATING, m_alwaysOnTop ? GLFW_TRUE : GLFW_FALSE); + m_modesDirty = false; + } + + if(glfwGetWindowAttrib(m_window, GLFW_ICONIFIED)) + { + glfwWaitEvents(); + return; + } + + @autoreleasepool { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + if (mvApp::GetApp()->getFontManager().isInvalid()) + { + mvApp::GetApp()->getFontManager().rebuildAtlas(); + ImGui_ImplMetal_DestroyFontsTexture(); + mvApp::GetApp()->getFontManager().updateDefaultFont(); + ImGui_ImplMetal_CreateFontsTexture(device); + } + + NSWindow *nswin = glfwGetCocoaWindow(m_window); + if(nswin.isVisible && (nswin.occlusionState & NSWindowOcclusionStateVisible) == 0) + usleep(16u); + + m_layer.displaySyncEnabled = m_vsync; + + int width; + int height; + glfwGetFramebufferSize(m_window, &width, &height); + m_layer.drawableSize = CGSizeMake(width, height); + id drawable = [m_layer nextDrawable]; + + m_width = (unsigned)width; + m_height = (unsigned)height; + + id commandBuffer = [m_commandQueue commandBuffer]; + m_renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(m_clear_color[0], + m_clear_color[1], + m_clear_color[2], + m_clear_color[3]); + m_renderPassDescriptor.colorAttachments[0].texture = drawable.texture; + m_renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; + m_renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + id m_renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:m_renderPassDescriptor]; + [m_renderEncoder pushDebugGroup:@"ImGui demo"]; + + // Start the Dear ImGui frame + ImGui_ImplMetal_NewFrame(m_renderPassDescriptor); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + if(!mvApp::GetApp()->getTextureStorage().isValid()) + mvApp::GetApp()->getTextureStorage().refreshAtlas(); + + if (m_error) + { + mvAppLog::setSize(m_width, m_height); + mvAppLog::render(); + } + else + m_app->render(); + + // Rendering + ImGui::Render(); + ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, m_renderEncoder); + + [m_renderEncoder popDebugGroup]; + [m_renderEncoder endEncoding]; + + [commandBuffer presentDrawable:drawable]; + [commandBuffer commit]; + + } + } + +} diff --git a/DearPyGui/src/platform/Linux/mvLinuxViewport.cpp b/DearPyGui/src/platform/Linux/mvLinuxViewport.cpp new file mode 100644 index 000000000..b0c3111fc --- /dev/null +++ b/DearPyGui/src/platform/Linux/mvLinuxViewport.cpp @@ -0,0 +1,241 @@ +#include "mvLinuxViewport.h" +#include "mvApp.h" +#include "mvAppLog.h" +#include "mvFontManager.h" +#include +#include +#include "implot.h" +#include "imgui.h" +#include "imnodes.h" +#include "imgui_internal.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include +#include "mvTextureStorage.h" + +namespace Marvel { + + mvViewport* mvViewport::CreateViewport(unsigned int width, unsigned int height, bool error) + { + return new mvLinuxViewport(width, height, error); + } + + static void glfw_error_callback(int error, const char* description) + { + fprintf(stderr, "Glfw Error %d: %s\n", error, description); + } + + static void window_close_callback(GLFWwindow* window) + { + mvApp::StopApp(); + } + + static void window_size_callback(GLFWwindow* window, int width, int height) + { + mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, { + CreateEventArgument("actual_width", width), + CreateEventArgument("actual_height", height), + CreateEventArgument("client_width", width), + CreateEventArgument("client_height", height) + }); + } + + mvLinuxViewport::mvLinuxViewport(unsigned width, unsigned height, bool error) + : mvViewport(width, height, error) + { + } + + void mvLinuxViewport::show(bool minimized, bool maximized) + { + // Setup window + glfwSetErrorCallback(glfw_error_callback); + glfwInit(); + + if (!m_resizable) + glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); + if(m_alwaysOnTop) + glfwWindowHint(GLFW_FLOATING, GLFW_TRUE); + if(maximized) + glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE); + else if(minimized) + glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE); + if(!m_caption) + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); + + // Create window with graphics context + // GL 3.0 + GLSL 130 + const char* glsl_version = "#version 130"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); + m_window = glfwCreateWindow(m_actualWidth, m_actualHeight, m_title.c_str(), nullptr, nullptr); + glfwSetWindowPos(m_window, m_xpos, m_ypos); + glfwSetWindowSizeLimits(m_window, (int)m_minwidth, (int)m_minheight, (int)m_maxwidth, (int)m_maxheight); + + mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, { + CreateEventArgument("actual_width", (int)m_actualWidth), + CreateEventArgument("actual_height", (int)m_actualHeight), + CreateEventArgument("client_width", (int)m_actualWidth), + CreateEventArgument("client_height", (int)m_actualHeight) + }); + + glfwMakeContextCurrent(m_window); + + gl3wInit(); + + // Setup Dear ImGui binding + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + imnodes::Initialize(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigWindowsMoveFromTitleBarOnly = true; + io.IniFilename = nullptr; + + if (mvApp::GetApp()->m_docking) + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + if (mvApp::GetApp()->m_dockingShiftOnly) + io.ConfigDockingWithShift = true; + + // Setup style + ImGui::StyleColorsDark(); + + // Setup Platform/Renderer bindings + ImGui_ImplGlfw_InitForOpenGL(m_window, true); + ImGui_ImplOpenGL3_Init(glsl_version); + + // Setup callbacks + glfwSetWindowSizeCallback(m_window, window_size_callback); + glfwSetWindowCloseCallback(m_window, window_close_callback); + } + + mvLinuxViewport::~mvLinuxViewport() + { + // Cleanup + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + imnodes::Shutdown(); + ImGui::DestroyContext(); + + glfwDestroyWindow(m_window); + glfwTerminate(); + mvApp::s_started = false; + } + + void mvLinuxViewport::maximize() + { + glfwMaximizeWindow(m_window); + } + + void mvLinuxViewport::minimize() + { + glfwIconifyWindow(m_window); + } + + void mvLinuxViewport::restore() + { + glfwRestoreWindow(m_window); + } + + void mvLinuxViewport::renderFrame() + { + + prerender(); + + if(GImGui->CurrentWindow == nullptr) + return; + + if (m_error) + { + mvAppLog::setSize(m_width, m_height); + mvAppLog::render(); + } + + else + m_app->render(); + + postrender(); + } + + void mvLinuxViewport::run() + { + + setup(); + while (m_running) + renderFrame(); + + } + + void mvLinuxViewport::prerender() + { + m_running = !glfwWindowShouldClose(m_window); + + if(m_posDirty) + { + glfwSetWindowPos(m_window, m_xpos, m_ypos); + m_posDirty = false; + } + + if(m_sizeDirty) + { + glfwSetWindowSizeLimits(m_window, (int)m_minwidth, (int)m_minheight, (int)m_maxwidth, (int)m_maxheight); + glfwSetWindowSize(m_window, m_actualWidth, m_actualHeight); + m_sizeDirty = false; + } + + if(m_modesDirty) + { + glfwSetWindowTitle(m_window, m_title.c_str()); + glfwSetWindowAttrib(m_window, GLFW_RESIZABLE, m_resizable ? GLFW_TRUE : GLFW_FALSE); + glfwSetWindowAttrib(m_window, GLFW_DECORATED, m_caption ? GLFW_TRUE : GLFW_FALSE); + glfwSetWindowAttrib(m_window, GLFW_FLOATING, m_alwaysOnTop ? GLFW_TRUE : GLFW_FALSE); + m_modesDirty = false; + } + + if(glfwGetWindowAttrib(m_window, GLFW_ICONIFIED)) + { + glfwWaitEvents(); + return; + } + + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + if (mvApp::GetApp()->getFontManager().isInvalid()) + { + mvApp::GetApp()->getFontManager().rebuildAtlas(); + ImGui_ImplOpenGL3_DestroyDeviceObjects(); + mvApp::GetApp()->getFontManager().updateDefaultFont(); + } + + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + if (!mvApp::GetApp()->getTextureStorage().isValid()) + mvApp::GetApp()->getTextureStorage().refreshAtlas(); + } + + void mvLinuxViewport::postrender() + { + glfwSwapInterval(m_vsync ? 1 : 0); // Enable vsync + + // Rendering + ImGui::Render(); + int display_w, display_h; + glfwGetFramebufferSize(m_window, &display_w, &display_h); + + glViewport(0, 0, display_w, display_h); + glClearColor(m_clear_color[0], m_clear_color[1], m_clear_color[2], m_clear_color[3]); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + + glfwSwapBuffers(m_window); + } + +} diff --git a/DearPyGui/src/platform/Linux/mvLinuxViewport.h b/DearPyGui/src/platform/Linux/mvLinuxViewport.h new file mode 100644 index 000000000..5da85ee2a --- /dev/null +++ b/DearPyGui/src/platform/Linux/mvLinuxViewport.h @@ -0,0 +1,34 @@ +#pragma once + +#include "mvViewport.h" + +class GLFWwindow; + +namespace Marvel { + + class mvLinuxViewport : public mvViewport + { + + public: + + mvLinuxViewport(unsigned width, unsigned height, bool error = false); + ~mvLinuxViewport(); + + void show(bool minimized, bool maximized) override; + + void prerender (); + void postrender (); + void renderFrame() override; + void run () override; + void maximize () override; + void minimize () override; + void restore () override; + + + private: + float m_clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + GLFWwindow* m_window = nullptr; + + }; + +} diff --git a/DearPyGui/src/platform/Linux/mvUtilities.cpp b/DearPyGui/src/platform/Linux/mvUtilities.cpp new file mode 100644 index 000000000..1a1522c86 --- /dev/null +++ b/DearPyGui/src/platform/Linux/mvUtilities.cpp @@ -0,0 +1,78 @@ +#include "mvUtilities.h" +#define STB_IMAGE_IMPLEMENTATION +#include +#include +#include +#include +#include + +namespace Marvel { + + bool LoadTextureFromArray(const char* name, float* data, unsigned width, unsigned height, mvTexture& storage, mvTextureFormat format) + { + + // Create a OpenGL texture identifier + GLuint image_texture; + glGenTextures(1, &image_texture); + glBindTexture(GL_TEXTURE_2D, image_texture); + + // Setup filtering parameters for display + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + // Upload pixels into texture + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, data); + + storage.texture = reinterpret_cast(image_texture); + storage.width = width; + storage.height = height; + + return true; + } + + // Simple helper function to load an image into a DX11 texture with common settings + bool LoadTextureFromFile(const char* filename, mvTexture& storage) + { + + // Load from file + int image_width = 0; + int image_height = 0; + unsigned char* image_data = stbi_load(filename, &image_width, &image_height, nullptr, 4); + if (image_data == nullptr) + return false; + + // Create a OpenGL texture identifier + GLuint image_texture; + glGenTextures(1, &image_texture); + glBindTexture(GL_TEXTURE_2D, image_texture); + + // Setup filtering parameters for display + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + // Upload pixels into texture + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); + stbi_image_free(image_data); + + storage.texture = reinterpret_cast(image_texture); + storage.width = image_width; + storage.height = image_height; + + return true; + } + + bool UnloadTexture(const std::string& filename) + { + // TODO : decide if cleanup is necessary + return true; + } + + void FreeTexture(mvTexture& storage) + { + auto out_srv = (GLuint)(size_t)storage.texture; + glDeleteTextures(1, &out_srv); + } + +} diff --git a/DearPyGui/src/platform/Windows/mvUtilities.cpp b/DearPyGui/src/platform/Windows/mvUtilities.cpp new file mode 100644 index 000000000..74c43c2d6 --- /dev/null +++ b/DearPyGui/src/platform/Windows/mvUtilities.cpp @@ -0,0 +1,134 @@ +#include "mvUtilities.h" +#include "mvWindowsViewport.h" + +#define STB_IMAGE_IMPLEMENTATION +#include +#include +#include +#include +#include // Contains the declaration of CComPtr. +#include +#include +#include +#include + +#include + +namespace fs = std::filesystem; + +namespace Marvel { + + bool LoadTextureFromArray(const char* name, float* data, unsigned width, unsigned height, mvTexture& storage, mvTextureFormat format) + { + + //auto out_srv = static_cast(storage.texture); + ID3D11ShaderResourceView* out_srv = nullptr; + + // Create texture + D3D11_TEXTURE2D_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.CPUAccessFlags = 0; + desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + + ID3D11Texture2D* pTexture = NULL; + D3D11_SUBRESOURCE_DATA subResource; + subResource.pSysMem = data; + subResource.SysMemPitch = desc.Width * 4 * 4; + subResource.SysMemSlicePitch = 0; + mvWindowsViewport::getDevice()->CreateTexture2D(&desc, &subResource, &pTexture); + + // Create texture view + // Create texture view + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; + ZeroMemory(&srvDesc, sizeof(srvDesc)); + srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Texture2D.MostDetailedMip = 0; + mvWindowsViewport::getDevice()->CreateShaderResourceView(pTexture, &srvDesc, &out_srv); + pTexture->Release(); + + storage.texture = out_srv; + storage.width = width; + storage.height = height; + storage.count = 1; + + return true; + } + + // Simple helper function to load an image into a DX11 texture with common settings + bool LoadTextureFromFile(const char* filename, mvTexture& storage) + { + + //auto out_srv = static_cast(storage.texture); + ID3D11ShaderResourceView* out_srv = nullptr; + + // Load from disk into a raw RGBA buffer + int image_width = 0; + int image_height = 0; + unsigned char* image_data = stbi_load(filename, &image_width, &image_height, NULL, 4); + if (image_data == NULL) + return false; + + // Create texture + D3D11_TEXTURE2D_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.Width = image_width; + desc.Height = image_height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.CPUAccessFlags = 0; + + ID3D11Texture2D* pTexture = NULL; + D3D11_SUBRESOURCE_DATA subResource; + subResource.pSysMem = image_data; + subResource.SysMemPitch = desc.Width * 4; + subResource.SysMemSlicePitch = 0; + mvWindowsViewport::getDevice()->CreateTexture2D(&desc, &subResource, &pTexture); + + // Create texture view + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; + ZeroMemory(&srvDesc, sizeof(srvDesc)); + srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Texture2D.MostDetailedMip = 0; + mvWindowsViewport::getDevice()->CreateShaderResourceView(pTexture, &srvDesc, &out_srv); + pTexture->Release(); + + storage.texture = out_srv; + storage.width = image_width; + storage.height = image_height; + stbi_image_free(image_data); + + return true; + } + + bool UnloadTexture(const std::string& filename) + { + // TODO : decide if cleanup is necessary + return true; + } + + void FreeTexture(mvTexture& storage) + { + ID3D11ShaderResourceView* out_srv = static_cast(storage.texture); + if (out_srv) + auto count = out_srv->Release(); + + storage.texture = nullptr; + storage.count = 0; + } + +} \ No newline at end of file diff --git a/DearPyGui/src/platform/Windows/mvWindowsViewport.cpp b/DearPyGui/src/platform/Windows/mvWindowsViewport.cpp new file mode 100644 index 000000000..28d885ad7 --- /dev/null +++ b/DearPyGui/src/platform/Windows/mvWindowsViewport.cpp @@ -0,0 +1,437 @@ +#include "Platform/Windows/mvWindowsViewport.h" +#include "mvApp.h" +#include "mvAppLog.h" +#include "mvFontManager.h" +#include "mvTextureStorage.h" +#include "implot.h" +#include "imnodes.h" +#include +#include + +// Forward declare message handler from imgui_impl_win32.cpp +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +namespace Marvel { + + mvViewport* mvViewport::CreateViewport(unsigned width, unsigned height, bool error) + { + return new mvWindowsViewport(width, height, error); + } + + mvWindowsViewport::mvWindowsViewport(unsigned width, unsigned height, bool error) + : mvViewport(width, height, error) + { + m_clearColor = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + } + + mvWindowsViewport::~mvWindowsViewport() + { + // Cleanup + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + imnodes::Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + CleanupDeviceD3D(); + ::DestroyWindow(m_hwnd); + ::UnregisterClass(m_wc.lpszClassName, m_wc.hInstance); + } + + void mvWindowsViewport::maximize() + { + ShowWindow(m_hwnd, SW_MAXIMIZE); + } + + void mvWindowsViewport::minimize() + { + ShowWindow(m_hwnd, SW_MINIMIZE); + } + + void mvWindowsViewport::handleModes() + { + m_modes = 0; + + if (m_border) m_modes |= WS_THICKFRAME; + if (m_caption) m_modes |= WS_CAPTION; + if (m_minimizeBox) m_modes |= WS_MINIMIZEBOX; + if (m_maximizeBox) m_modes |= WS_MAXIMIZEBOX; + if (m_overlapped) m_modes |= WS_OVERLAPPED | WS_SYSMENU; + } + + void mvWindowsViewport::show(bool minimized, bool maximized) + { + + m_wc = { + sizeof(WNDCLASSEX), + CS_CLASSDC, + HandleMsgSetup, + 0L, + 0L, + GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, + _T(m_title.c_str()), nullptr }; + RegisterClassEx(&m_wc); + + handleModes(); + m_hwnd = CreateWindow(m_wc.lpszClassName, _T(m_title.c_str()), + m_modes, + m_xpos, m_ypos, m_actualWidth, m_actualHeight, nullptr, nullptr, m_wc.hInstance, this); + + // Initialize Direct3D + if (!CreateDeviceD3D(m_hwnd)) + { + CleanupDeviceD3D(); + ::UnregisterClass(m_wc.lpszClassName, m_wc.hInstance); + } + previous_ime_char = 0; + HKL hkl = GetKeyboardLayout(0); + lang_id = LOWORD(hkl); + + // Show the window + + int cmdShow; + + if (minimized) + cmdShow = SW_MINIMIZE; + else if (maximized) + cmdShow = SW_MAXIMIZE; + else + cmdShow = SW_SHOWDEFAULT; + + ::ShowWindow(m_hwnd, cmdShow); + ::UpdateWindow(m_hwnd); + + if (m_alwaysOnTop) + SetWindowPos(m_hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + imnodes::Initialize(); + + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigWindowsMoveFromTitleBarOnly = true; + io.IniFilename = nullptr; + + if(mvApp::GetApp()->m_docking) + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + if (mvApp::GetApp()->m_dockingShiftOnly) + io.ConfigDockingWithShift = true; + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + + // Setup Platform/Renderer bindings + ImGui_ImplWin32_Init(m_hwnd); + ImGui_ImplDX11_Init(s_pd3dDevice, s_pd3dDeviceContext); + } + + void mvWindowsViewport::setup() + { + ZeroMemory(&m_msg, sizeof(m_msg)); + } + + void mvWindowsViewport::prerender() + { + if (m_msg.message == WM_QUIT) + m_running = false; + + if (m_posDirty) + { + SetWindowPos(m_hwnd, m_alwaysOnTop ? HWND_TOPMOST : HWND_TOP, m_xpos, m_ypos, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE); + m_posDirty = false; + } + + if (m_sizeDirty) + { + SetWindowPos(m_hwnd, m_alwaysOnTop ? HWND_TOPMOST : HWND_TOP, 0, 0, m_actualWidth, m_actualHeight, SWP_SHOWWINDOW | SWP_NOMOVE); + m_sizeDirty = false; + } + + if (m_modesDirty) + { + handleModes(); + SetWindowTextA(m_hwnd, m_title.c_str()); + SetWindowLongPtr(m_hwnd, GWL_STYLE, m_modes); + SetWindowPos(m_hwnd, m_alwaysOnTop ? HWND_TOPMOST : HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); + m_modesDirty = false; + } + + // Poll and handle messages (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + if (::PeekMessage(&m_msg, nullptr, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&m_msg); + ::DispatchMessage(&m_msg); + //continue; + } + + if (mvApp::GetApp()->getFontManager().isInvalid()) + { + mvApp::GetApp()->getFontManager().rebuildAtlas(); + ImGui_ImplDX11_InvalidateDeviceObjects(); + mvApp::GetApp()->getFontManager().updateDefaultFont(); + } + + // Start the Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + + + if (!mvApp::GetApp()->getTextureStorage().isValid()) + mvApp::GetApp()->getTextureStorage().refreshAtlas(); + } + + void mvWindowsViewport::renderFrame() + { + prerender(); + + if (m_error) + { + mvAppLog::setSize(m_width, m_height); + mvAppLog::render(); + } + + else + m_app->render(); + + postrender(); + } + + void mvWindowsViewport::postrender() + { + + ImVec4 clear_color = m_clearColor; + + // Rendering + ImGui::Render(); + s_pd3dDeviceContext->OMSetRenderTargets(1, &s_mainRenderTargetView, nullptr); + s_pd3dDeviceContext->ClearRenderTargetView(s_mainRenderTargetView, (float*)&clear_color); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + //s_pSwapChain->Present(1, 0); // Present with vsync + //s_pSwapChain->Present(0, 0); // Present without vsync + + static UINT presentFlags = 0; + if (s_pSwapChain->Present(m_vsync ? 1 : 0, presentFlags) == DXGI_STATUS_OCCLUDED) { + presentFlags = DXGI_PRESENT_TEST; + Sleep(20); + } + else { + presentFlags = 0; + } + } + + bool mvWindowsViewport::CreateDeviceD3D(HWND hWnd) + { + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; + if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, + createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &s_pSwapChain, + &s_pd3dDevice, &featureLevel, &s_pd3dDeviceContext) != S_OK) + return false; + + CreateRenderTarget(); + return true; + } + + void mvWindowsViewport::CleanupDeviceD3D() + { + CleanupRenderTarget(); + if (s_pSwapChain) + { + s_pSwapChain->Release(); + s_pSwapChain = nullptr; + } + + if (s_pd3dDeviceContext) + { + s_pd3dDeviceContext->Release(); + s_pd3dDeviceContext = nullptr; + } + + if (s_pd3dDevice) + { + s_pd3dDevice->Release(); + s_pd3dDevice = nullptr; + } + } + + void mvWindowsViewport::CreateRenderTarget() + { + ID3D11Texture2D* pBackBuffer; + s_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + s_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &s_mainRenderTargetView); + pBackBuffer->Release(); + } + + void mvWindowsViewport::CleanupRenderTarget() + { + if (s_mainRenderTargetView) + { + s_mainRenderTargetView->Release(); + s_mainRenderTargetView = nullptr; + } + } + + LRESULT CALLBACK mvWindowsViewport::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept + { + // use create parameter passed in from CreateWindow() to store window class pointer at WinAPI side + if (msg == WM_NCCREATE) + { + // extract ptr to window class from creation data + const CREATESTRUCTW* const pCreate = reinterpret_cast(lParam); + auto const pWnd = static_cast(pCreate->lpCreateParams); + // set WinAPI-managed user data to store ptr to window instance + SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast(pWnd)); + // set message proc to normal (non-setup) handler now that setup is finished + SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast(&mvWindowsViewport::HandleMsgThunk)); + // forward message to window instance handler + return pWnd->HandleMsg(hWnd, msg, wParam, lParam); + } + // if we get a message before the WM_NCCREATE message, handle with default handler + return DefWindowProc(hWnd, msg, wParam, lParam); + } + + LRESULT CALLBACK mvWindowsViewport::HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept + { + // retrieve ptr to window instance + auto const pWnd = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + // forward message to window instance handler + return pWnd->HandleMsg(hWnd, msg, wParam, lParam); + } + + LRESULT mvWindowsViewport::HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept + { + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + switch (msg) + { + case WM_GETMINMAXINFO: + { + LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam; + lpMMI->ptMinTrackSize.x = m_minwidth; + lpMMI->ptMinTrackSize.y = m_minheight; + lpMMI->ptMaxTrackSize.x = m_maxwidth; + lpMMI->ptMaxTrackSize.y = m_maxheight; + break; + } + + case WM_SIZE: + if (s_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED) + { + RECT rect; + RECT crect; + int awidth = 0; + int aheight = 0; + int cwidth = 0; + int cheight = 0; + if (GetWindowRect(hWnd, &rect)) + { + awidth = rect.right - rect.left; + aheight = rect.bottom - rect.top; + } + + if (GetClientRect(hWnd, &crect)) + { + cwidth = crect.right - crect.left; + cheight = crect.bottom - crect.top; + } + + onResizeEvent(); + + // I believe this are only used for the error logger + m_width = (UINT)LOWORD(lParam); + m_height = (UINT)HIWORD(lParam); + + CleanupRenderTarget(); + s_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); + CreateRenderTarget(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + mvApp::StopApp(); + ::PostQuitMessage(0); + return 0; + case WM_INPUTLANGCHANGE: + lang_id=LOWORD(lParam); + break; + case WM_IME_CHAR: + if (lang_id==0x0412) + break; + auto& io = ImGui::GetIO(); + DWORD wChar = wParam; + if (wChar <= 127) + { + io.AddInputCharacter(wChar); + return 0; + } + else if(wChar<0xFF){ + //GBK also supports Traditional Chinese, Japanese, English, Russian and (partially) Greek. + //When input Japanese with MS Japanese IME under CP936, dual bytes of one Japanese char are send within one or two wParam in succession. + if (previous_ime_char==0){ + previous_ime_char=(BYTE)(wChar & 0x00FF); + return 0; + } + else{ + BYTE b2=(BYTE)(wChar & 0x00FF); + wChar = MAKEWORD( previous_ime_char,b2); + previous_ime_char=0; + } + } + else + { + // swap lower and upper part. + BYTE low = (BYTE)(wChar & 0x00FF); + BYTE high = (BYTE)((wChar & 0xFF00) >> 8); + if (previous_ime_char==0) + wChar = MAKEWORD(high, low); + else{ + wChar = MAKEWORD(previous_ime_char, high, low); + previous_ime_char=low; + } + } + wchar_t ch[6]; + MultiByteToWideChar(CP_OEMCP, 0, (LPCSTR)&wChar, 4, ch, 3); + io.AddInputCharacter(ch[0]); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); + } + + ID3D11Device* mvWindowsViewport::s_pd3dDevice = nullptr; + ID3D11DeviceContext* mvWindowsViewport::s_pd3dDeviceContext = nullptr; + IDXGISwapChain* mvWindowsViewport::s_pSwapChain = nullptr; + ID3D11RenderTargetView* mvWindowsViewport::s_mainRenderTargetView = nullptr; + +} \ No newline at end of file diff --git a/DearPyGui/src/platform/Windows/mvWindowsViewport.h b/DearPyGui/src/platform/Windows/mvWindowsViewport.h new file mode 100644 index 000000000..55a64382b --- /dev/null +++ b/DearPyGui/src/platform/Windows/mvWindowsViewport.h @@ -0,0 +1,70 @@ +#pragma once + +#include "imgui.h" +#include "imgui_impl_win32.h" +#include "imgui_impl_dx11.h" +#include +#define DIRECTINPUT_VERSION 0x0800 +#include +#include +#include "mvViewport.h" + +namespace Marvel { + + class mvWindowsViewport : public mvViewport + { + + public: + + mvWindowsViewport(unsigned width, unsigned height, bool error = false); + ~mvWindowsViewport() override; + + void show (bool minimized, bool maximized) override; + void setup () override; + void prerender (); + void postrender (); + void renderFrame() override; + void maximize () override; + void minimize () override; + void handleModes(); + + private: + + bool CreateDeviceD3D(HWND hWnd); + + void CleanupDeviceD3D(); + + static void CreateRenderTarget(); + + static void CleanupRenderTarget(); + + public: + + static ID3D11Device* getDevice() { return s_pd3dDevice; } + + static LRESULT CALLBACK HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + + static LRESULT CALLBACK HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + + LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + + private: + + HWND m_hwnd; + WNDCLASSEX m_wc; + MSG m_msg; + DWORD m_modes; + ImVec4 m_clearColor; + + private: + + // Data + static ID3D11Device* s_pd3dDevice; + static ID3D11DeviceContext* s_pd3dDeviceContext; + static IDXGISwapChain* s_pSwapChain; + static ID3D11RenderTargetView* s_mainRenderTargetView; + BYTE previous_ime_char; + WORD lang_id; + }; + +} diff --git a/thirdparty/ImGuiFileDialog/LICENSE b/DearPyGui/vendor/dirent/LICENSE similarity index 93% rename from thirdparty/ImGuiFileDialog/LICENSE rename to DearPyGui/vendor/dirent/LICENSE index bd17d9512..fadf777b0 100644 --- a/thirdparty/ImGuiFileDialog/LICENSE +++ b/DearPyGui/vendor/dirent/LICENSE @@ -1,6 +1,6 @@ -MIT License +The MIT License (MIT) -Copyright (c) 2018-2020 Stephane Cuillerdier (aka Aiekick) +Copyright (c) 2015 Toni Rnkk Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/DearPyGui/vendor/dirent/dirent.h b/DearPyGui/vendor/dirent/dirent.h new file mode 100644 index 000000000..29777be14 --- /dev/null +++ b/DearPyGui/vendor/dirent/dirent.h @@ -0,0 +1,1186 @@ +/* + * Dirent interface for Microsoft Visual Studio + * + * Copyright (C) 2006-2012 Toni Ronkko + * This file is part of dirent. Dirent may be freely distributed + * under the MIT license. For all details and documentation, see + * https://github.com/tronkko/dirent + */ +#ifndef DIRENT_H +#define DIRENT_H + + /* + * Include windows.h without Windows Sockets 1.1 to prevent conflicts with + * Windows Sockets 2.0. + */ +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + /* Indicates that d_type field is available in dirent structure */ +#define _DIRENT_HAVE_D_TYPE + +/* Indicates that d_namlen field is available in dirent structure */ +#define _DIRENT_HAVE_D_NAMLEN + +/* Entries missing from MSVC 6.0 */ +#if !defined(FILE_ATTRIBUTE_DEVICE) +# define FILE_ATTRIBUTE_DEVICE 0x40 +#endif + +/* File type and permission flags for stat(), general mask */ +#if !defined(S_IFMT) +# define S_IFMT _S_IFMT +#endif + +/* Directory bit */ +#if !defined(S_IFDIR) +# define S_IFDIR _S_IFDIR +#endif + +/* Character device bit */ +#if !defined(S_IFCHR) +# define S_IFCHR _S_IFCHR +#endif + +/* Pipe bit */ +#if !defined(S_IFFIFO) +# define S_IFFIFO _S_IFFIFO +#endif + +/* Regular file bit */ +#if !defined(S_IFREG) +# define S_IFREG _S_IFREG +#endif + +/* Read permission */ +#if !defined(S_IREAD) +# define S_IREAD _S_IREAD +#endif + +/* Write permission */ +#if !defined(S_IWRITE) +# define S_IWRITE _S_IWRITE +#endif + +/* Execute permission */ +#if !defined(S_IEXEC) +# define S_IEXEC _S_IEXEC +#endif + +/* Pipe */ +#if !defined(S_IFIFO) +# define S_IFIFO _S_IFIFO +#endif + +/* Block device */ +#if !defined(S_IFBLK) +# define S_IFBLK 0 +#endif + +/* Link */ +#if !defined(S_IFLNK) +# define S_IFLNK 0 +#endif + +/* Socket */ +#if !defined(S_IFSOCK) +# define S_IFSOCK 0 +#endif + +/* Read user permission */ +#if !defined(S_IRUSR) +# define S_IRUSR S_IREAD +#endif + +/* Write user permission */ +#if !defined(S_IWUSR) +# define S_IWUSR S_IWRITE +#endif + +/* Execute user permission */ +#if !defined(S_IXUSR) +# define S_IXUSR 0 +#endif + +/* Read group permission */ +#if !defined(S_IRGRP) +# define S_IRGRP 0 +#endif + +/* Write group permission */ +#if !defined(S_IWGRP) +# define S_IWGRP 0 +#endif + +/* Execute group permission */ +#if !defined(S_IXGRP) +# define S_IXGRP 0 +#endif + +/* Read others permission */ +#if !defined(S_IROTH) +# define S_IROTH 0 +#endif + +/* Write others permission */ +#if !defined(S_IWOTH) +# define S_IWOTH 0 +#endif + +/* Execute others permission */ +#if !defined(S_IXOTH) +# define S_IXOTH 0 +#endif + +/* Maximum length of file name */ +#if !defined(PATH_MAX) +# define PATH_MAX MAX_PATH +#endif +#if !defined(FILENAME_MAX) +# define FILENAME_MAX MAX_PATH +#endif +#if !defined(NAME_MAX) +# define NAME_MAX FILENAME_MAX +#endif + +/* File type flags for d_type */ +#define DT_UNKNOWN 0 +#define DT_REG S_IFREG +#define DT_DIR S_IFDIR +#define DT_FIFO S_IFIFO +#define DT_SOCK S_IFSOCK +#define DT_CHR S_IFCHR +#define DT_BLK S_IFBLK +#define DT_LNK S_IFLNK + +/* Macros for converting between st_mode and d_type */ +#define IFTODT(mode) ((mode) & S_IFMT) +#define DTTOIF(type) (type) + +/* + * File type macros. Note that block devices, sockets and links cannot be + * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are + * only defined for compatibility. These macros should always return false + * on Windows. + */ +#if !defined(S_ISFIFO) +# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) +#endif +#if !defined(S_ISDIR) +# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#endif +#if !defined(S_ISREG) +# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +#endif +#if !defined(S_ISLNK) +# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) +#endif +#if !defined(S_ISSOCK) +# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) +#endif +#if !defined(S_ISCHR) +# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) +#endif +#if !defined(S_ISBLK) +# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) +#endif + + /* Return the exact length of the file name without zero terminator */ +#define _D_EXACT_NAMLEN(p) ((p)->d_namlen) + +/* Return the maximum size of a file name */ +#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1) + + +#ifdef __cplusplus +extern "C" { +#endif + + + /* Wide-character version */ + struct _wdirent { + /* Always zero */ + long d_ino; + + /* File position within stream */ + long d_off; + + /* Structure size */ + unsigned short d_reclen; + + /* Length of name without \0 */ + size_t d_namlen; + + /* File type */ + int d_type; + + /* File name */ + wchar_t d_name[PATH_MAX + 1]; + }; + typedef struct _wdirent _wdirent; + + struct _WDIR { + /* Current directory entry */ + struct _wdirent ent; + + /* Private file data */ + WIN32_FIND_DATAW data; + + /* True if data is valid */ + int cached; + + /* Win32 search handle */ + HANDLE handle; + + /* Initial directory name */ + wchar_t* patt; + }; + typedef struct _WDIR _WDIR; + + /* Multi-byte character version */ + struct dirent { + /* Always zero */ + long d_ino; + + /* File position within stream */ + long d_off; + + /* Structure size */ + unsigned short d_reclen; + + /* Length of name without \0 */ + size_t d_namlen; + + /* File type */ + int d_type; + + /* File name */ + char d_name[PATH_MAX + 1]; + }; + typedef struct dirent dirent; + + struct DIR { + struct dirent ent; + struct _WDIR* wdirp; + }; + typedef struct DIR DIR; + + + /* Dirent functions */ + static DIR* opendir(const char* dirname); + static _WDIR* _wopendir(const wchar_t* dirname); + + static struct dirent* readdir(DIR* dirp); + static struct _wdirent* _wreaddir(_WDIR* dirp); + + static int readdir_r( + DIR* dirp, struct dirent* entry, struct dirent** result); + static int _wreaddir_r( + _WDIR* dirp, struct _wdirent* entry, struct _wdirent** result); + + static int closedir(DIR* dirp); + static int _wclosedir(_WDIR* dirp); + + static void rewinddir(DIR* dirp); + static void _wrewinddir(_WDIR* dirp); + + static int scandir(const char* dirname, struct dirent*** namelist, + int (*filter)(const struct dirent*), + int (*compare)(const struct dirent**, const struct dirent**)); + + static int alphasort(const struct dirent** a, const struct dirent** b); + + static int versionsort(const struct dirent** a, const struct dirent** b); + + + /* For compatibility with Symbian */ +#define wdirent _wdirent +#define WDIR _WDIR +#define wopendir _wopendir +#define wreaddir _wreaddir +#define wclosedir _wclosedir +#define wrewinddir _wrewinddir + + +/* Internal utility functions */ + static WIN32_FIND_DATAW* dirent_first(_WDIR* dirp); + static WIN32_FIND_DATAW* dirent_next(_WDIR* dirp); + + static int dirent_mbstowcs_s( + size_t* pReturnValue, + wchar_t* wcstr, + size_t sizeInWords, + const char* mbstr, + size_t count); + + static int dirent_wcstombs_s( + size_t* pReturnValue, + char* mbstr, + size_t sizeInBytes, + const wchar_t* wcstr, + size_t count); + + static void dirent_set_errno(int error); + + + /* + * Open directory stream DIRNAME for read and return a pointer to the + * internal working area that is used to retrieve individual directory + * entries. + */ + static _WDIR* + _wopendir( + const wchar_t* dirname) + { + _WDIR* dirp = NULL; + int error; + + /* Must have directory name */ + if (dirname == NULL || dirname[0] == '\0') { + dirent_set_errno(ENOENT); + return NULL; + } + + /* Allocate new _WDIR structure */ + dirp = (_WDIR*)malloc(sizeof(struct _WDIR)); + if (dirp != NULL) { + DWORD n; + + /* Reset _WDIR structure */ + dirp->handle = INVALID_HANDLE_VALUE; + dirp->patt = NULL; + dirp->cached = 0; + + /* Compute the length of full path plus zero terminator + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) + n = wcslen(dirname); +# else + n = GetFullPathNameW(dirname, 0, NULL, NULL); +# endif + + /* Allocate room for absolute directory name and search pattern */ + dirp->patt = (wchar_t*)malloc(sizeof(wchar_t) * n + 16); + if (dirp->patt) { + + /* + * Convert relative directory name to an absolute one. This + * allows rewinddir() to function correctly even when current + * working directory is changed between opendir() and rewinddir(). + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) + wcsncpy_s(dirp->patt, n + 1, dirname, n); +# else + n = GetFullPathNameW(dirname, n, dirp->patt, NULL); +# endif + if (n > 0) { + wchar_t* p; + + /* Append search pattern \* to the directory name */ + p = dirp->patt + n; + if (dirp->patt < p) { + switch (p[-1]) { + case '\\': + case '/': + case ':': + /* Directory ends in path separator, e.g. c:\temp\ */ + /*NOP*/; + break; + + default: + /* Directory name doesn't end in path separator */ + *p++ = '\\'; + } + } + *p++ = '*'; + *p = '\0'; + + /* Open directory stream and retrieve the first entry */ + if (dirent_first(dirp)) { + /* Directory stream opened successfully */ + error = 0; + } + else { + /* Cannot retrieve first entry */ + error = 1; + dirent_set_errno(ENOENT); + } + + } + else { + /* Cannot retrieve full path name */ + dirent_set_errno(ENOENT); + error = 1; + } + + } + else { + /* Cannot allocate memory for search pattern */ + error = 1; + } + + } + else { + /* Cannot allocate _WDIR structure */ + error = 1; + } + + /* Clean up in case of error */ + if (error && dirp) { + _wclosedir(dirp); + dirp = NULL; + } + + return dirp; + } + + /* + * Read next directory entry. + * + * Returns pointer to static directory entry which may be overwritten by + * subsequent calls to _wreaddir(). + */ + static struct _wdirent* + _wreaddir( + _WDIR* dirp) + { + struct _wdirent* entry; + + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to NULL in case of error. + */ + (void)_wreaddir_r(dirp, &dirp->ent, &entry); + + /* Return pointer to statically allocated directory entry */ + return entry; + } + + /* + * Read next directory entry. + * + * Returns zero on success. If end of directory stream is reached, then sets + * result to NULL and returns zero. + */ + static int + _wreaddir_r( + _WDIR* dirp, + struct _wdirent* entry, + struct _wdirent** result) + { + WIN32_FIND_DATAW* datap; + + /* Read next directory entry */ + datap = dirent_next(dirp); + if (datap) { + size_t n; + DWORD attr; + + /* + * Copy file name as wide-character string. If the file name is too + * long to fit in to the destination buffer, then truncate file name + * to PATH_MAX characters and zero-terminate the buffer. + */ + n = 0; + while (n < PATH_MAX && datap->cFileName[n] != 0) { + entry->d_name[n] = datap->cFileName[n]; + n++; + } + entry->d_name[n] = 0; + + /* Length of file name excluding zero terminator */ + entry->d_namlen = n; + + /* File type */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } + else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; + } + else { + entry->d_type = DT_REG; + } + + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof(struct _wdirent); + + /* Set result address */ + *result = entry; + + } + else { + + /* Return NULL to indicate end of directory */ + *result = NULL; + + } + + return /*OK*/0; + } + + /* + * Close directory stream opened by opendir() function. This invalidates the + * DIR structure as well as any directory entry read previously by + * _wreaddir(). + */ + static int + _wclosedir( + _WDIR* dirp) + { + int ok; + if (dirp) { + + /* Release search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose(dirp->handle); + dirp->handle = INVALID_HANDLE_VALUE; + } + + /* Release search pattern */ + if (dirp->patt) { + free(dirp->patt); + dirp->patt = NULL; + } + + /* Release directory structure */ + free(dirp); + ok = /*success*/0; + + } + else { + + /* Invalid directory stream */ + dirent_set_errno(EBADF); + ok = /*failure*/-1; + + } + return ok; + } + + /* + * Rewind directory stream such that _wreaddir() returns the very first + * file name again. + */ + static void + _wrewinddir( + _WDIR* dirp) + { + if (dirp) { + /* Release existing search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose(dirp->handle); + } + + /* Open new search handle */ + dirent_first(dirp); + } + } + + /* Get first directory entry (internal) */ + static WIN32_FIND_DATAW* + dirent_first( + _WDIR* dirp) + { + WIN32_FIND_DATAW* datap; + + /* Open directory and retrieve the first entry */ + dirp->handle = FindFirstFileExW( + dirp->patt, FindExInfoStandard, &dirp->data, + FindExSearchNameMatch, NULL, 0); + if (dirp->handle != INVALID_HANDLE_VALUE) { + + /* a directory entry is now waiting in memory */ + datap = &dirp->data; + dirp->cached = 1; + + } + else { + + /* Failed to re-open directory: no directory entry in memory */ + dirp->cached = 0; + datap = NULL; + + } + return datap; + } + + /* + * Get next directory entry (internal). + * + * Returns + */ + static WIN32_FIND_DATAW* + dirent_next( + _WDIR* dirp) + { + WIN32_FIND_DATAW* p; + + /* Get next directory entry */ + if (dirp->cached != 0) { + + /* A valid directory entry already in memory */ + p = &dirp->data; + dirp->cached = 0; + + } + else if (dirp->handle != INVALID_HANDLE_VALUE) { + + /* Get the next directory entry from stream */ + if (FindNextFileW(dirp->handle, &dirp->data) != FALSE) { + /* Got a file */ + p = &dirp->data; + } + else { + /* The very last entry has been processed or an error occurred */ + FindClose(dirp->handle); + dirp->handle = INVALID_HANDLE_VALUE; + p = NULL; + } + + } + else { + + /* End of directory stream reached */ + p = NULL; + + } + + return p; + } + + /* + * Open directory stream using plain old C-string. + */ + static DIR* + opendir( + const char* dirname) + { + struct DIR* dirp; + int error; + + /* Must have directory name */ + if (dirname == NULL || dirname[0] == '\0') { + dirent_set_errno(ENOENT); + return NULL; + } + + /* Allocate memory for DIR structure */ + dirp = (DIR*)malloc(sizeof(struct DIR)); + if (dirp) { + wchar_t wname[PATH_MAX + 1]; + size_t n; + + /* Convert directory name to wide-character string */ + error = dirent_mbstowcs_s( + &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); + if (!error) { + + /* Open directory stream using wide-character name */ + dirp->wdirp = _wopendir(wname); + if (dirp->wdirp) { + /* Directory stream opened */ + error = 0; + } + else { + /* Failed to open directory stream */ + error = 1; + } + + } + else { + /* + * Cannot convert file name to wide-character string. This + * occurs if the string contains invalid multi-byte sequences or + * the output buffer is too small to contain the resulting + * string. + */ + error = 1; + } + + } + else { + /* Cannot allocate DIR structure */ + error = 1; + } + + /* Clean up in case of error */ + if (error && dirp) { + free(dirp); + dirp = NULL; + } + + return dirp; + } + + /* + * Read next directory entry. + */ + static struct dirent* + readdir( + DIR* dirp) + { + struct dirent* entry; + + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to NULL in case of error. + */ + (void)readdir_r(dirp, &dirp->ent, &entry); + + /* Return pointer to statically allocated directory entry */ + return entry; + } + + /* + * Read next directory entry into called-allocated buffer. + * + * Returns zero on success. If the end of directory stream is reached, then + * sets result to NULL and returns zero. + */ + static int + readdir_r( + DIR* dirp, + struct dirent* entry, + struct dirent** result) + { + WIN32_FIND_DATAW* datap; + + /* Read next directory entry */ + datap = dirent_next(dirp->wdirp); + if (datap) { + size_t n; + int error; + + /* Attempt to convert file name to multi-byte string */ + error = dirent_wcstombs_s( + &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1); + + /* + * If the file name cannot be represented by a multi-byte string, + * then attempt to use old 8+3 file name. This allows traditional + * Unix-code to access some file names despite of unicode + * characters, although file names may seem unfamiliar to the user. + * + * Be ware that the code below cannot come up with a short file + * name unless the file system provides one. At least + * VirtualBox shared folders fail to do this. + */ + if (error && datap->cAlternateFileName[0] != '\0') { + error = dirent_wcstombs_s( + &n, entry->d_name, PATH_MAX + 1, + datap->cAlternateFileName, PATH_MAX + 1); + } + + if (!error) { + DWORD attr; + + /* Length of file name excluding zero terminator */ + entry->d_namlen = n - 1; + + /* File attributes */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } + else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; + } + else { + entry->d_type = DT_REG; + } + + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof(struct dirent); + + } + else { + + /* + * Cannot convert file name to multi-byte string so construct + * an erroneous directory entry and return that. Note that + * we cannot return NULL as that would stop the processing + * of directory entries completely. + */ + entry->d_name[0] = '?'; + entry->d_name[1] = '\0'; + entry->d_namlen = 1; + entry->d_type = DT_UNKNOWN; + entry->d_ino = 0; + entry->d_off = -1; + entry->d_reclen = 0; + + } + + /* Return pointer to directory entry */ + *result = entry; + + } + else { + + /* No more directory entries */ + *result = NULL; + + } + + return /*OK*/0; + } + + /* + * Close directory stream. + */ + static int + closedir( + DIR* dirp) + { + int ok; + if (dirp) { + + /* Close wide-character directory stream */ + ok = _wclosedir(dirp->wdirp); + dirp->wdirp = NULL; + + /* Release multi-byte character version */ + free(dirp); + + } + else { + + /* Invalid directory stream */ + dirent_set_errno(EBADF); + ok = /*failure*/-1; + + } + return ok; + } + + /* + * Rewind directory stream to beginning. + */ + static void + rewinddir( + DIR* dirp) + { + /* Rewind wide-character string directory stream */ + _wrewinddir(dirp->wdirp); + } + + /* + * Scan directory for entries. + */ + static int + scandir( + const char* dirname, + struct dirent*** namelist, + int (*filter)(const struct dirent*), + int (*compare)(const struct dirent**, const struct dirent**)) + { + struct dirent** files = NULL; + size_t size = 0; + size_t allocated = 0; + const size_t init_size = 1; + DIR* dir = NULL; + struct dirent* entry; + struct dirent* tmp = NULL; + size_t i; + int result = 0; + + /* Open directory stream */ + dir = opendir(dirname); + if (dir) { + + /* Read directory entries to memory */ + while (1) { + + /* Enlarge pointer table to make room for another pointer */ + if (size >= allocated) { + void* p; + size_t num_entries; + + /* Compute number of entries in the enlarged pointer table */ + if (size < init_size) { + /* Allocate initial pointer table */ + num_entries = init_size; + } + else { + /* Double the size */ + num_entries = size * 2; + } + + /* Allocate first pointer table or enlarge existing table */ + p = realloc(files, sizeof(void*) * num_entries); + if (p != NULL) { + /* Got the memory */ + files = (dirent**)p; + allocated = num_entries; + } + else { + /* Out of memory */ + result = -1; + break; + } + + } + + /* Allocate room for temporary directory entry */ + if (tmp == NULL) { + tmp = (struct dirent*)malloc(sizeof(struct dirent)); + if (tmp == NULL) { + /* Cannot allocate temporary directory entry */ + result = -1; + break; + } + } + + /* Read directory entry to temporary area */ + if (readdir_r(dir, tmp, &entry) == /*OK*/0) { + + /* Did we get an entry? */ + if (entry != NULL) { + int pass; + + /* Determine whether to include the entry in result */ + if (filter) { + /* Let the filter function decide */ + pass = filter(tmp); + } + else { + /* No filter function, include everything */ + pass = 1; + } + + if (pass) { + /* Store the temporary entry to pointer table */ + files[size++] = tmp; + tmp = NULL; + + /* Keep up with the number of files */ + result++; + } + + } + else { + + /* + * End of directory stream reached => sort entries and + * exit. + */ + qsort(files, size, sizeof(void*), + (int (*) (const void*, const void*)) compare); + break; + + } + + } + else { + /* Error reading directory entry */ + result = /*Error*/ -1; + break; + } + + } + + } + else { + /* Cannot open directory */ + result = /*Error*/ -1; + } + + /* Release temporary directory entry */ + if (tmp) { + free(tmp); + } + + /* Release allocated memory on error */ + if (result < 0) { + for (i = 0; i < size; i++) { + free(files[i]); + } + free(files); + files = NULL; + } + + /* Close directory stream */ + if (dir) { + closedir(dir); + } + + /* Pass pointer table to caller */ + if (namelist) { + *namelist = files; + } + return result; + } + + /* Alphabetical sorting */ + static int + alphasort( + const struct dirent** a, const struct dirent** b) + { + return strcoll((*a)->d_name, (*b)->d_name); + } + + /* Sort versions */ + static int + versionsort( + const struct dirent** a, const struct dirent** b) + { + /* FIXME: implement strverscmp and use that */ + return alphasort(a, b); + } + + + /* Convert multi-byte string to wide character string */ + static int + dirent_mbstowcs_s( + size_t* pReturnValue, + wchar_t* wcstr, + size_t sizeInWords, + const char* mbstr, + size_t count) + { + int error; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 or later */ + error = mbstowcs_s(pReturnValue, wcstr, sizeInWords, mbstr, count); + +#else + + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to wide-character string (or count characters) */ + n = mbstowcs(wcstr, mbstr, sizeInWords); + if (!wcstr || n < count) { + + /* Zero-terminate output buffer */ + if (wcstr && sizeInWords) { + if (n >= sizeInWords) { + n = sizeInWords - 1; + } + wcstr[n] = 0; + } + + /* Length of resulting multi-byte string WITH zero terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } + + /* Success */ + error = 0; + + } + else { + + /* Could not convert string */ + error = 1; + + } + +#endif + + return error; + } + + /* Convert wide-character string to multi-byte string */ + static int + dirent_wcstombs_s( + size_t* pReturnValue, + char* mbstr, + size_t sizeInBytes, /* max size of mbstr */ + const wchar_t* wcstr, + size_t count) + { + int error; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 or later */ + error = wcstombs_s(pReturnValue, mbstr, sizeInBytes, wcstr, count); + +#else + + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to multi-byte string (or count the number of bytes needed) */ + n = wcstombs(mbstr, wcstr, sizeInBytes); + if (!mbstr || n < count) { + + /* Zero-terminate output buffer */ + if (mbstr && sizeInBytes) { + if (n >= sizeInBytes) { + n = sizeInBytes - 1; + } + mbstr[n] = '\0'; + } + + /* Length of resulting multi-bytes string WITH zero-terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } + + /* Success */ + error = 0; + + } + else { + + /* Cannot convert string */ + error = 1; + + } + +#endif + + return error; + } + + /* Set errno variable */ + static void + dirent_set_errno( + int error) + { +#if defined(_MSC_VER) && _MSC_VER >= 1400 + + /* Microsoft Visual Studio 2005 and later */ + _set_errno(error); + +#else + + /* Non-Microsoft compiler or older Microsoft compiler */ + errno = error; + +#endif + } + + +#ifdef __cplusplus +} +#endif +#endif /*DIRENT_H*/ diff --git a/thirdparty/imnodes/LICENSE.md b/DearPyGui/vendor/imnodes/LICENSE.md similarity index 100% rename from thirdparty/imnodes/LICENSE.md rename to DearPyGui/vendor/imnodes/LICENSE.md diff --git a/DearPyGui/vendor/imnodes/imnodes.cpp b/DearPyGui/vendor/imnodes/imnodes.cpp new file mode 100644 index 000000000..cf37b0309 --- /dev/null +++ b/DearPyGui/vendor/imnodes/imnodes.cpp @@ -0,0 +1,2949 @@ +// the structure of this file: +// +// [SECTION] internal data structures +// [SECTION] global struct +// [SECTION] editor context definition +// [SECTION] draw list helper +// [SECTION] ObjectPool implementation +// [SECTION] ui state logic +// [SECTION] render helpers +// [SECTION] API implementation + +#include "imnodes.h" + +#include +#define IMGUI_DEFINE_MATH_OPERATORS +#include + +// Check minimum ImGui version +#define MINIMUM_COMPATIBLE_IMGUI_VERSION 17400 +#if IMGUI_VERSION_NUM < MINIMUM_COMPATIBLE_IMGUI_VERSION +#error "Minimum ImGui version requirement not met -- please use a newer version!" +#endif + +#include +#include +#include +#include +#include +#include // strlen, strncmp +#include // for fwrite, ssprintf, sscanf +#include + +namespace imnodes +{ +namespace +{ +enum ScopeFlags +{ + Scope_None = 1, + Scope_Editor = 1 << 1, + Scope_Node = 1 << 2, + Scope_Attribute = 1 << 3 +}; + +enum AttributeType +{ + AttributeType_None, + AttributeType_Input, + AttributeType_Output +}; + +enum ElementStateChange +{ + ElementStateChange_None = 0, + ElementStateChange_LinkStarted = 1 << 0, + ElementStateChange_LinkDropped = 1 << 1, + ElementStateChange_LinkCreated = 1 << 2 +}; + +// [SECTION] internal data structures + +// The object T must have the following interface: +// +// struct T +// { +// T(); +// +// int id; +// }; +template +struct ObjectPool +{ + ImVector pool; + ImVector in_use; + ImVector free_list; + ImGuiStorage id_map; + + ObjectPool() : pool(), in_use(), free_list(), id_map() {} +}; + +// Emulates std::optional using the sentinel value `invalid_index`. +struct OptionalIndex +{ + OptionalIndex() : m_index(invalid_index) {} + OptionalIndex(const int value) : m_index(value) {} + + // Observers + + inline bool has_value() const { return m_index != invalid_index; } + + inline int value() const + { + assert(has_value()); + return m_index; + } + + // Modifiers + + inline OptionalIndex& operator=(const int value) + { + m_index = value; + return *this; + } + + inline void reset() { m_index = invalid_index; } + + inline bool operator==(const OptionalIndex& rhs) const { return m_index == rhs.m_index; } + + inline bool operator==(const int rhs) const { return m_index == rhs; } + + inline bool operator!=(const OptionalIndex& rhs) const { return m_index != rhs.m_index; } + + inline bool operator!=(const int rhs) const { return m_index != rhs; } + + static const int invalid_index = -1; + +private: + int m_index; +}; + +struct NodeData +{ + int id; + ImVec2 origin; // The node origin is in editor space + ImRect title_bar_content_rect; + ImRect rect; + + struct + { + ImU32 background, background_hovered, background_selected, outline, titlebar, + titlebar_hovered, titlebar_selected; + } color_style; + + struct + { + float corner_rounding; + ImVec2 padding; + float border_thickness; + } layout_style; + + ImVector pin_indices; + bool draggable; + + NodeData(const int node_id) + : id(node_id), origin(100.0f, 100.0f), title_bar_content_rect(), + rect(ImVec2(0.0f, 0.0f), ImVec2(0.0f, 0.0f)), color_style(), layout_style(), + pin_indices(), draggable(true) + { + } + + ~NodeData() { id = INT_MIN; } +}; + +struct PinData +{ + int id; + int parent_node_idx; + ImRect attribute_rect; + AttributeType type; + PinShape shape; + ImVec2 pos; // screen-space coordinates + int flags; + + struct + { + ImU32 background, hovered; + } color_style; + + PinData(const int pin_id) + : id(pin_id), parent_node_idx(), attribute_rect(), type(AttributeType_None), + shape(PinShape_CircleFilled), pos(), flags(AttributeFlags_None), color_style() + { + } +}; + +struct LinkData +{ + int id; + int start_pin_idx, end_pin_idx; + + struct + { + ImU32 base, hovered, selected; + } color_style; + + LinkData(const int link_id) : id(link_id), start_pin_idx(), end_pin_idx(), color_style() {} +}; + +struct LinkPredicate +{ + bool operator()(const LinkData& lhs, const LinkData& rhs) const + { + // Do a unique compare by sorting the pins' addresses. + // This catches duplicate links, whether they are in the + // same direction or not. + // Sorting by pin index should have the uniqueness guarantees as sorting + // by id -- each unique id will get one slot in the link pool array. + + int lhs_start = lhs.start_pin_idx; + int lhs_end = lhs.end_pin_idx; + int rhs_start = rhs.start_pin_idx; + int rhs_end = rhs.end_pin_idx; + + if (lhs_start > lhs_end) + { + ImSwap(lhs_start, lhs_end); + } + + if (rhs_start > rhs_end) + { + ImSwap(rhs_start, rhs_end); + } + + return lhs_start == rhs_start && lhs_end == rhs_end; + } +}; + +struct BezierCurve +{ + // the curve control points + ImVec2 p0, p1, p2, p3; +}; + +struct LinkBezierData +{ + BezierCurve bezier; + int num_segments; +}; + +enum ClickInteractionType +{ + ClickInteractionType_Node, + ClickInteractionType_Link, + ClickInteractionType_LinkCreation, + ClickInteractionType_Panning, + ClickInteractionType_BoxSelection, + ClickInteractionType_None +}; + +enum LinkCreationType +{ + LinkCreationType_Standard, + LinkCreationType_FromDetach +}; + +struct ClickInteractionState +{ + struct + { + int start_pin_idx; + OptionalIndex end_pin_idx; + LinkCreationType link_creation_type; + } link_creation; + + struct + { + ImRect rect; + } box_selector; +}; + +struct ColorStyleElement +{ + ImU32 color; + ColorStyle item; + + ColorStyleElement(const ImU32 c, const ColorStyle s) : color(c), item(s) {} +}; + +struct StyleElement +{ + StyleVar item; + float value; + + StyleElement(const float value, const StyleVar variable) : item(variable), value(value) {} +}; + +// [SECTION] global struct +// this stores data which only lives for one frame +struct +{ + EditorContext* default_editor_ctx; + EditorContext* editor_ctx; + + // Canvas draw list and helper state + ImDrawList* canvas_draw_list; + ImGuiStorage node_idx_to_submission_idx; + ImVector node_idx_submission_order; + ImVector node_indices_overlapping_with_mouse; + + // Canvas extents + ImVec2 canvas_origin_screen_space; + ImRect canvas_rect_screen_space; + + // Debug helpers + ScopeFlags current_scope; + + // Configuration state + IO io; + Style style; + ImVector color_modifier_stack; + ImVector style_modifier_stack; + ImGuiTextBuffer text_buffer; + + int current_attribute_flags; + ImVector attribute_flag_stack; + + // UI element state + int current_node_idx; + int current_pin_idx; + int current_attribute_id; + + OptionalIndex hovered_node_idx; + OptionalIndex interactive_node_idx; + OptionalIndex hovered_link_idx; + OptionalIndex hovered_pin_idx; + int hovered_pin_flags; + + OptionalIndex deleted_link_idx; + OptionalIndex snap_link_idx; + + // Event helper state + int element_state_change; + + int active_attribute_id; + bool active_attribute; + + // ImGui::IO cache + + ImVec2 mouse_pos; + + bool left_mouse_clicked; + bool left_mouse_released; + bool middle_mouse_clicked; + bool left_mouse_dragging; + bool middle_mouse_dragging; +} g; + +EditorContext& editor_context_get() +{ + // No editor context was set! Did you forget to call imnodes::Initialize? + assert(g.editor_ctx != NULL); + return *g.editor_ctx; +} + +inline bool is_mouse_hovering_near_point(const ImVec2& point, float radius) +{ + ImVec2 delta = g.mouse_pos - point; + return (delta.x * delta.x + delta.y * delta.y) < (radius * radius); +} + +inline ImVec2 eval_bezier(float t, const BezierCurve& bezier) +{ + // B(t) = (1-t)**3 p0 + 3(1 - t)**2 t P1 + 3(1-t)t**2 P2 + t**3 P3 + return ImVec2( + (1 - t) * (1 - t) * (1 - t) * bezier.p0.x + 3 * (1 - t) * (1 - t) * t * bezier.p1.x + + 3 * (1 - t) * t * t * bezier.p2.x + t * t * t * bezier.p3.x, + (1 - t) * (1 - t) * (1 - t) * bezier.p0.y + 3 * (1 - t) * (1 - t) * t * bezier.p1.y + + 3 * (1 - t) * t * t * bezier.p2.y + t * t * t * bezier.p3.y); +} + +// Calculates the closest point along each bezier curve segment. +ImVec2 get_closest_point_on_cubic_bezier( + const int num_segments, + const ImVec2& p, + const BezierCurve& bezier) +{ + IM_ASSERT(num_segments > 0); + ImVec2 p_last = bezier.p0; + ImVec2 p_closest; + float p_closest_dist = FLT_MAX; + float t_step = 1.0f / (float)num_segments; + for (int i = 1; i <= num_segments; ++i) + { + ImVec2 p_current = eval_bezier(t_step * i, bezier); + ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); + float dist = ImLengthSqr(p - p_line); + if (dist < p_closest_dist) + { + p_closest = p_line; + p_closest_dist = dist; + } + p_last = p_current; + } + return p_closest; +} + +inline float get_distance_to_cubic_bezier( + const ImVec2& pos, + const BezierCurve& bezier, + const int num_segments) +{ + const ImVec2 point_on_curve = get_closest_point_on_cubic_bezier(num_segments, pos, bezier); + + const ImVec2 to_curve = point_on_curve - pos; + return ImSqrt(ImLengthSqr(to_curve)); +} + +inline ImRect get_containing_rect_for_bezier_curve(const BezierCurve& bezier) +{ + const ImVec2 min = ImVec2(ImMin(bezier.p0.x, bezier.p3.x), ImMin(bezier.p0.y, bezier.p3.y)); + const ImVec2 max = ImVec2(ImMax(bezier.p0.x, bezier.p3.x), ImMax(bezier.p0.y, bezier.p3.y)); + + const float hover_distance = g.style.link_hover_distance; + + ImRect rect(min, max); + rect.Add(bezier.p1); + rect.Add(bezier.p2); + rect.Expand(ImVec2(hover_distance, hover_distance)); + + return rect; +} + +inline LinkBezierData get_link_renderable( + ImVec2 start, + ImVec2 end, + const AttributeType start_type, + const float line_segments_per_length) +{ + assert((start_type == AttributeType_Input) || (start_type == AttributeType_Output)); + if (start_type == AttributeType_Input) + { + ImSwap(start, end); + } + + const float link_length = ImSqrt(ImLengthSqr(end - start)); + const ImVec2 offset = ImVec2(0.25f * link_length, 0.f); + LinkBezierData link_data; + link_data.bezier.p0 = start; + link_data.bezier.p1 = start + offset; + link_data.bezier.p2 = end - offset; + link_data.bezier.p3 = end; + link_data.num_segments = ImMax(static_cast(link_length * line_segments_per_length), 1); + return link_data; +} + +inline bool is_mouse_hovering_near_link(const BezierCurve& bezier, const int num_segments) +{ + const ImVec2 mouse_pos = g.mouse_pos; + + // First, do a simple bounding box test against the box containing the link + // to see whether calculating the distance to the link is worth doing. + const ImRect link_rect = get_containing_rect_for_bezier_curve(bezier); + + if (link_rect.Contains(mouse_pos)) + { + const float distance = get_distance_to_cubic_bezier(mouse_pos, bezier, num_segments); + if (distance < g.style.link_hover_distance) + { + return true; + } + } + + return false; +} + +inline float eval_implicit_line_eq(const ImVec2& p1, const ImVec2& p2, const ImVec2& p) +{ + return (p2.y - p1.y) * p.x + (p1.x - p2.x) * p.y + (p2.x * p1.y - p1.x * p2.y); +} + +inline int sign(float val) { return int(val > 0.0f) - int(val < 0.0f); } + +inline bool rectangle_overlaps_line_segment(const ImRect& rect, const ImVec2& p1, const ImVec2& p2) +{ + // Trivial case: rectangle contains an endpoint + if (rect.Contains(p1) || rect.Contains(p2)) + { + return true; + } + + // Flip rectangle if necessary + ImRect flip_rect = rect; + + if (flip_rect.Min.x > flip_rect.Max.x) + { + ImSwap(flip_rect.Min.x, flip_rect.Max.x); + } + + if (flip_rect.Min.y > flip_rect.Max.y) + { + ImSwap(flip_rect.Min.y, flip_rect.Max.y); + } + + // Trivial case: line segment lies to one particular side of rectangle + if ((p1.x < flip_rect.Min.x && p2.x < flip_rect.Min.x) || + (p1.x > flip_rect.Max.x && p2.x > flip_rect.Max.x) || + (p1.y < flip_rect.Min.y && p2.y < flip_rect.Min.y) || + (p1.y > flip_rect.Max.y && p2.y > flip_rect.Max.y)) + { + return false; + } + + const int corner_signs[4] = { + sign(eval_implicit_line_eq(p1, p2, flip_rect.Min)), + sign(eval_implicit_line_eq(p1, p2, ImVec2(flip_rect.Max.x, flip_rect.Min.y))), + sign(eval_implicit_line_eq(p1, p2, ImVec2(flip_rect.Min.x, flip_rect.Max.y))), + sign(eval_implicit_line_eq(p1, p2, flip_rect.Max))}; + + int sum = 0; + int sum_abs = 0; + + for (int i = 0; i < 4; ++i) + { + sum += corner_signs[i]; + sum_abs += abs(corner_signs[i]); + } + + // At least one corner of rectangle lies on a different side of line segment + return abs(sum) != sum_abs; +} + +inline bool rectangle_overlaps_bezier(const ImRect& rectangle, const LinkBezierData& link_data) +{ + ImVec2 current = eval_bezier(0.f, link_data.bezier); + const float dt = 1.0f / link_data.num_segments; + for (int s = 0; s < link_data.num_segments; ++s) + { + ImVec2 next = eval_bezier(static_cast((s + 1) * dt), link_data.bezier); + if (rectangle_overlaps_line_segment(rectangle, current, next)) + { + return true; + } + current = next; + } + return false; +} + +inline bool rectangle_overlaps_link( + const ImRect& rectangle, + const ImVec2& start, + const ImVec2& end, + const AttributeType start_type) +{ + // First level: simple rejection test via rectangle overlap: + + ImRect lrect = ImRect(start, end); + if (lrect.Min.x > lrect.Max.x) + { + ImSwap(lrect.Min.x, lrect.Max.x); + } + + if (lrect.Min.y > lrect.Max.y) + { + ImSwap(lrect.Min.y, lrect.Max.y); + } + + if (rectangle.Overlaps(lrect)) + { + // First, check if either one or both endpoinds are trivially contained + // in the rectangle + + if (rectangle.Contains(start) || rectangle.Contains(end)) + { + return true; + } + + // Second level of refinement: do a more expensive test against the + // link + + const LinkBezierData link_data = + get_link_renderable(start, end, start_type, g.style.link_line_segments_per_length); + return rectangle_overlaps_bezier(rectangle, link_data); + } + + return false; +} +} // namespace + +// [SECTION] editor context definition + +struct EditorContext +{ + ObjectPool nodes; + ObjectPool pins; + ObjectPool links; + + ImVector node_depth_order; + + // ui related fields + ImVec2 panning; + + ImVector selected_node_indices; + ImVector selected_link_indices; + + ClickInteractionType click_interaction_type; + ClickInteractionState click_interaction_state; + + EditorContext() + : nodes(), pins(), links(), panning(0.f, 0.f), selected_node_indices(), + selected_link_indices(), click_interaction_type(ClickInteractionType_None), + click_interaction_state() + { + } +}; + +namespace +{ +// [SECTION] draw list helper + +void ImDrawList_grow_channels(ImDrawList* draw_list, const int num_channels) +{ + ImDrawListSplitter& splitter = draw_list->_Splitter; + + if (splitter._Count == 1) + { + splitter.Split(draw_list, num_channels + 1); + return; + } + + // NOTE: this logic has been lifted from ImDrawListSplitter::Split with slight modifications + // to allow nested splits. The main modification is that we only create new ImDrawChannel + // instances after splitter._Count, instead of over the whole splitter._Channels array like + // the regular ImDrawListSplitter::Split method does. + + const int old_channel_capacity = splitter._Channels.Size; + // NOTE: _Channels is not resized down, and therefore _Count <= _Channels.size()! + const int old_channel_count = splitter._Count; + const int requested_channel_count = old_channel_count + num_channels; + if (old_channel_capacity < old_channel_count + num_channels) + { + splitter._Channels.resize(requested_channel_count); + } + + splitter._Count = requested_channel_count; + + for (int i = old_channel_count; i < requested_channel_count; ++i) + { + ImDrawChannel& channel = splitter._Channels[i]; + + // If we're inside the old capacity region of the array, we need to reuse the existing + // memory of the command and index buffers. + if (i < old_channel_capacity) + { + channel._CmdBuffer.resize(0); + channel._IdxBuffer.resize(0); + } + // Else, we need to construct new draw channels. + else + { + IM_PLACEMENT_NEW(&channel) ImDrawChannel(); + } + + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); + draw_cmd.TextureId = draw_list->_TextureIdStack.back(); + channel._CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawListSplitter_swap_channels( + ImDrawListSplitter& splitter, + const int lhs_idx, + const int rhs_idx) +{ + if (lhs_idx == rhs_idx) + { + return; + } + + assert(lhs_idx >= 0 && lhs_idx < splitter._Count); + assert(rhs_idx >= 0 && rhs_idx < splitter._Count); + + ImDrawChannel& lhs_channel = splitter._Channels[lhs_idx]; + ImDrawChannel& rhs_channel = splitter._Channels[rhs_idx]; + lhs_channel._CmdBuffer.swap(rhs_channel._CmdBuffer); + lhs_channel._IdxBuffer.swap(rhs_channel._IdxBuffer); + + const int current_channel = splitter._Current; + + if (current_channel == lhs_idx) + { + splitter._Current = rhs_idx; + } + else if (current_channel == rhs_idx) + { + splitter._Current = lhs_idx; + } +} + +void draw_list_set(ImDrawList* window_draw_list) +{ + g.canvas_draw_list = window_draw_list; + g.node_idx_to_submission_idx.Clear(); + g.node_idx_submission_order.clear(); +} + +// The draw list channels are structured as follows. First we have our base channel, the canvas grid +// on which we render the grid lines in BeginNodeEditor(). The base channel is the reason +// draw_list_submission_idx_to_background_channel_idx offsets the index by one. Each BeginNode() +// call appends two new draw channels, for the node background and foreground. The node foreground +// is the channel into which the node's ImGui content is rendered. Finally, in EndNodeEditor() we +// append one last draw channel for rendering the selection box and the incomplete link on top of +// everything else. +// +// +----------+----------+----------+----------+----------+----------+ +// | | | | | | | +// |canvas |node |node |... |... |click | +// |grid |background|foreground| | |interaction +// | | | | | | | +// +----------+----------+----------+----------+----------+----------+ +// | | +// | submission idx | +// | | +// ----------------------- + +void draw_list_add_node(const int node_idx) +{ + g.node_idx_to_submission_idx.SetInt( + static_cast(node_idx), g.node_idx_submission_order.Size); + g.node_idx_submission_order.push_back(node_idx); + ImDrawList_grow_channels(g.canvas_draw_list, 2); +} + +void draw_list_append_click_interaction_channel() +{ + // NOTE: don't use this function outside of EndNodeEditor. Using this before all nodes have been + // added will screw up the node draw order. + ImDrawList_grow_channels(g.canvas_draw_list, 1); +} + +int draw_list_submission_idx_to_background_channel_idx(const int submission_idx) +{ + // NOTE: the first channel is the canvas background, i.e. the grid + return 1 + 2 * submission_idx; +} + +int draw_list_submission_idx_to_foreground_channel_idx(const int submission_idx) +{ + return draw_list_submission_idx_to_background_channel_idx(submission_idx) + 1; +} + +void draw_list_activate_click_interaction_channel() +{ + g.canvas_draw_list->_Splitter.SetCurrentChannel( + g.canvas_draw_list, g.canvas_draw_list->_Splitter._Count - 1); +} + +void draw_list_activate_current_node_foreground() +{ + const int foreground_channel_idx = + draw_list_submission_idx_to_foreground_channel_idx(g.node_idx_submission_order.Size - 1); + g.canvas_draw_list->_Splitter.SetCurrentChannel(g.canvas_draw_list, foreground_channel_idx); +} + +void draw_list_activate_node_background(const int node_idx) +{ + const int submission_idx = + g.node_idx_to_submission_idx.GetInt(static_cast(node_idx), -1); + // There is a discrepancy in the submitted node count and the rendered node count! Did you call + // one of the following functions + // * EditorContextMoveToNode + // * SetNodeScreenSpacePos + // * SetNodeGridSpacePos + // * SetNodeDraggable + // after the BeginNode/EndNode function calls? + assert(submission_idx != -1); + const int background_channel_idx = + draw_list_submission_idx_to_background_channel_idx(submission_idx); + g.canvas_draw_list->_Splitter.SetCurrentChannel(g.canvas_draw_list, background_channel_idx); +} + +void draw_list_swap_submission_indices(const int lhs_idx, const int rhs_idx) +{ + assert(lhs_idx != rhs_idx); + + const int lhs_foreground_channel_idx = + draw_list_submission_idx_to_foreground_channel_idx(lhs_idx); + const int lhs_background_channel_idx = + draw_list_submission_idx_to_background_channel_idx(lhs_idx); + const int rhs_foreground_channel_idx = + draw_list_submission_idx_to_foreground_channel_idx(rhs_idx); + const int rhs_background_channel_idx = + draw_list_submission_idx_to_background_channel_idx(rhs_idx); + + ImDrawListSplitter_swap_channels( + g.canvas_draw_list->_Splitter, lhs_background_channel_idx, rhs_background_channel_idx); + ImDrawListSplitter_swap_channels( + g.canvas_draw_list->_Splitter, lhs_foreground_channel_idx, rhs_foreground_channel_idx); +} + +void draw_list_sort_channels_by_depth(const ImVector& node_idx_depth_order) +{ + if (g.node_idx_to_submission_idx.Data.Size < 2) + { + return; + } + + assert(node_idx_depth_order.Size == g.node_idx_submission_order.Size); + + int start_idx = node_idx_depth_order.Size - 1; + + while (node_idx_depth_order[start_idx] == g.node_idx_submission_order[start_idx]) + { + if (--start_idx == 0) + { + // early out if submission order and depth order are the same + return; + } + } + + // TODO: this is an O(N^2) algorithm. It might be worthwhile revisiting this to see if the time + // complexity can be reduced. + + for (int depth_idx = start_idx; depth_idx > 0; --depth_idx) + { + const int node_idx = node_idx_depth_order[depth_idx]; + + // Find the current index of the node_idx in the submission order array + int submission_idx = -1; + for (int i = 0; i < g.node_idx_submission_order.Size; ++i) + { + if (g.node_idx_submission_order[i] == node_idx) + { + submission_idx = i; + break; + } + } + assert(submission_idx >= 0); + + if (submission_idx == depth_idx) + { + continue; + } + + for (int j = submission_idx; j < depth_idx; ++j) + { + draw_list_swap_submission_indices(j, j + 1); + ImSwap(g.node_idx_submission_order[j], g.node_idx_submission_order[j + 1]); + } + } +} + +// [SECTION] ObjectPool implementation + +template +int object_pool_find(ObjectPool& objects, const int id) +{ + const int index = objects.id_map.GetInt(static_cast(id), -1); + return index; +} + +template +void object_pool_update(ObjectPool& objects) +{ + objects.free_list.clear(); + for (int i = 0; i < objects.in_use.size(); ++i) + { + if (!objects.in_use[i]) + { + objects.id_map.SetInt(objects.pool[i].id, -1); + objects.free_list.push_back(i); + (objects.pool.Data + i)->~T(); + } + } +} + +template<> +void object_pool_update(ObjectPool& nodes) +{ + nodes.free_list.clear(); + for (int i = 0; i < nodes.in_use.size(); ++i) + { + if (nodes.in_use[i]) + { + nodes.pool[i].pin_indices.clear(); + } + else + { + const int previous_id = nodes.pool[i].id; + const int previous_idx = nodes.id_map.GetInt(previous_id, -1); + + if (previous_idx != -1) + { + assert(previous_idx == i); + // Remove node idx form depth stack the first time we detect that this idx slot is + // unused + ImVector& depth_stack = editor_context_get().node_depth_order; + const int* const elem = depth_stack.find(i); + assert(elem != depth_stack.end()); + depth_stack.erase(elem); + } + + nodes.id_map.SetInt(previous_id, -1); + nodes.free_list.push_back(i); + (nodes.pool.Data + i)->~NodeData(); + } + } +} + +template +void object_pool_reset(ObjectPool& objects) +{ + if (!objects.in_use.empty()) + { + memset(objects.in_use.Data, 0, objects.in_use.size_in_bytes()); + } +} + +template +int object_pool_find_or_create_index(ObjectPool& objects, const int id) +{ + int index = objects.id_map.GetInt(static_cast(id), -1); + + // Construct new object + if (index == -1) + { + if (objects.free_list.empty()) + { + index = objects.pool.size(); + IM_ASSERT(objects.pool.size() == objects.in_use.size()); + const int new_size = objects.pool.size() + 1; + objects.pool.resize(new_size); + objects.in_use.resize(new_size); + } + else + { + index = objects.free_list.back(); + objects.free_list.pop_back(); + } + IM_PLACEMENT_NEW(objects.pool.Data + index) T(id); + objects.id_map.SetInt(static_cast(id), index); + } + + // Flag it as used + objects.in_use[index] = true; + + return index; +} + +template<> +int object_pool_find_or_create_index(ObjectPool& nodes, const int node_id) +{ + int node_idx = nodes.id_map.GetInt(static_cast(node_id), -1); + + // Construct new node + if (node_idx == -1) + { + if (nodes.free_list.empty()) + { + node_idx = nodes.pool.size(); + IM_ASSERT(nodes.pool.size() == nodes.in_use.size()); + const int new_size = nodes.pool.size() + 1; + nodes.pool.resize(new_size); + nodes.in_use.resize(new_size); + } + else + { + node_idx = nodes.free_list.back(); + nodes.free_list.pop_back(); + } + IM_PLACEMENT_NEW(nodes.pool.Data + node_idx) NodeData(node_id); + nodes.id_map.SetInt(static_cast(node_id), node_idx); + + EditorContext& editor = editor_context_get(); + editor.node_depth_order.push_back(node_idx); + } + + // Flag node as used + nodes.in_use[node_idx] = true; + + return node_idx; +} + +template +T& object_pool_find_or_create_object(ObjectPool& objects, const int id) +{ + const int index = object_pool_find_or_create_index(objects, id); + return objects.pool[index]; +} + +// [SECTION] ui state logic + +ImVec2 get_screen_space_pin_coordinates( + const ImRect& node_rect, + const ImRect& attribute_rect, + const AttributeType type) +{ + assert(type == AttributeType_Input || type == AttributeType_Output); + const float x = type == AttributeType_Input ? (node_rect.Min.x - g.style.pin_offset) + : (node_rect.Max.x + g.style.pin_offset); + return ImVec2(x, 0.5f * (attribute_rect.Min.y + attribute_rect.Max.y)); +} + +ImVec2 get_screen_space_pin_coordinates(const EditorContext& editor, const PinData& pin) +{ + const ImRect& parent_node_rect = editor.nodes.pool[pin.parent_node_idx].rect; + return get_screen_space_pin_coordinates(parent_node_rect, pin.attribute_rect, pin.type); +} + +bool mouse_in_canvas() +{ + // This flag should be true either when hovering or clicking something in the canvas. + const bool is_window_hovered_or_focused = ImGui::IsWindowHovered() || ImGui::IsWindowFocused(); + + return is_window_hovered_or_focused && + g.canvas_rect_screen_space.Contains(ImGui::GetMousePos()); +} + +void begin_node_selection(EditorContext& editor, const int node_idx) +{ + // Don't start selecting a node if we are e.g. already creating and dragging + // a new link! New link creation can happen when the mouse is clicked over + // a node, but within the hover radius of a pin. + if (editor.click_interaction_type != ClickInteractionType_None) + { + return; + } + + editor.click_interaction_type = ClickInteractionType_Node; + // If the node is not already contained in the selection, then we want only + // the interaction node to be selected, effective immediately. + // + // Otherwise, we want to allow for the possibility of multiple nodes to be + // moved at once. + if (!editor.selected_node_indices.contains(node_idx)) + { + editor.selected_node_indices.clear(); + editor.selected_link_indices.clear(); + editor.selected_node_indices.push_back(node_idx); + + // Ensure that individually selected nodes get rendered on top + ImVector& depth_stack = editor.node_depth_order; + const int* const elem = depth_stack.find(node_idx); + assert(elem != depth_stack.end()); + depth_stack.erase(elem); + depth_stack.push_back(node_idx); + } +} + +void begin_link_selection(EditorContext& editor, const int link_idx) +{ + editor.click_interaction_type = ClickInteractionType_Link; + // When a link is selected, clear all other selections, and insert the link + // as the sole selection. + editor.selected_node_indices.clear(); + editor.selected_link_indices.clear(); + editor.selected_link_indices.push_back(link_idx); +} + +void begin_link_detach(EditorContext& editor, const int link_idx, const int detach_pin_idx) +{ + const LinkData& link = editor.links.pool[link_idx]; + ClickInteractionState& state = editor.click_interaction_state; + state.link_creation.end_pin_idx.reset(); + state.link_creation.start_pin_idx = + detach_pin_idx == link.start_pin_idx ? link.end_pin_idx : link.start_pin_idx; + g.deleted_link_idx = link_idx; +} + +void begin_link_interaction(EditorContext& editor, const int link_idx) +{ + // First check if we are clicking a link in the vicinity of a pin. + // This may result in a link detach via click and drag. + if (editor.click_interaction_type == ClickInteractionType_LinkCreation) + { + if ((g.hovered_pin_flags & AttributeFlags_EnableLinkDetachWithDragClick) != 0) + { + begin_link_detach(editor, link_idx, g.hovered_pin_idx.value()); + editor.click_interaction_state.link_creation.link_creation_type = + LinkCreationType_FromDetach; + } + } + // If we aren't near a pin, check if we are clicking the link with the + // modifier pressed. This may also result in a link detach via clicking. + else + { + const bool modifier_pressed = g.io.link_detach_with_modifier_click.modifier == NULL + ? false + : *g.io.link_detach_with_modifier_click.modifier; + + if (modifier_pressed) + { + const LinkData& link = editor.links.pool[link_idx]; + const PinData& start_pin = editor.pins.pool[link.start_pin_idx]; + const PinData& end_pin = editor.pins.pool[link.end_pin_idx]; + const ImVec2& mouse_pos = g.mouse_pos; + const float dist_to_start = ImLengthSqr(start_pin.pos - mouse_pos); + const float dist_to_end = ImLengthSqr(end_pin.pos - mouse_pos); + const int closest_pin_idx = + dist_to_start < dist_to_end ? link.start_pin_idx : link.end_pin_idx; + + editor.click_interaction_type = ClickInteractionType_LinkCreation; + begin_link_detach(editor, link_idx, closest_pin_idx); + } + else + { + begin_link_selection(editor, link_idx); + } + } +} + +void begin_link_creation(EditorContext& editor, const int hovered_pin_idx) +{ + editor.click_interaction_type = ClickInteractionType_LinkCreation; + editor.click_interaction_state.link_creation.start_pin_idx = hovered_pin_idx; + editor.click_interaction_state.link_creation.end_pin_idx.reset(); + editor.click_interaction_state.link_creation.link_creation_type = LinkCreationType_Standard; + g.element_state_change |= ElementStateChange_LinkStarted; +} + +void begin_canvas_interaction(EditorContext& editor) +{ + const bool any_ui_element_hovered = g.hovered_node_idx.has_value() || + g.hovered_link_idx.has_value() || + g.hovered_pin_idx.has_value() || ImGui::IsAnyItemHovered(); + + const bool mouse_not_in_canvas = !mouse_in_canvas(); + + if (editor.click_interaction_type != ClickInteractionType_None || any_ui_element_hovered || + mouse_not_in_canvas) + { + return; + } + + const bool started_panning = g.middle_mouse_clicked; + + if (started_panning) + { + editor.click_interaction_type = ClickInteractionType_Panning; + } + else if (g.left_mouse_clicked) + { + editor.click_interaction_type = ClickInteractionType_BoxSelection; + editor.click_interaction_state.box_selector.rect.Min = g.mouse_pos; + } +} + +void box_selector_update_selection(EditorContext& editor, ImRect box_rect) +{ + // Invert box selector coordinates as needed + + if (box_rect.Min.x > box_rect.Max.x) + { + ImSwap(box_rect.Min.x, box_rect.Max.x); + } + + if (box_rect.Min.y > box_rect.Max.y) + { + ImSwap(box_rect.Min.y, box_rect.Max.y); + } + + // Update node selection + + editor.selected_node_indices.clear(); + + // Test for overlap against node rectangles + + for (int node_idx = 0; node_idx < editor.nodes.pool.size(); ++node_idx) + { + if (editor.nodes.in_use[node_idx]) + { + NodeData& node = editor.nodes.pool[node_idx]; + if (box_rect.Overlaps(node.rect)) + { + editor.selected_node_indices.push_back(node_idx); + } + } + } + + // Update link selection + + editor.selected_link_indices.clear(); + + // Test for overlap against links + + for (int link_idx = 0; link_idx < editor.links.pool.size(); ++link_idx) + { + if (editor.links.in_use[link_idx]) + { + const LinkData& link = editor.links.pool[link_idx]; + + const PinData& pin_start = editor.pins.pool[link.start_pin_idx]; + const PinData& pin_end = editor.pins.pool[link.end_pin_idx]; + const ImRect& node_start_rect = editor.nodes.pool[pin_start.parent_node_idx].rect; + const ImRect& node_end_rect = editor.nodes.pool[pin_end.parent_node_idx].rect; + + const ImVec2 start = get_screen_space_pin_coordinates( + node_start_rect, pin_start.attribute_rect, pin_start.type); + const ImVec2 end = get_screen_space_pin_coordinates( + node_end_rect, pin_end.attribute_rect, pin_end.type); + + // Test + if (rectangle_overlaps_link(box_rect, start, end, pin_start.type)) + { + editor.selected_link_indices.push_back(link_idx); + } + } + } +} + +void translate_selected_nodes(EditorContext& editor) +{ + if (g.left_mouse_dragging) + { + const ImGuiIO& io = ImGui::GetIO(); + for (int i = 0; i < editor.selected_node_indices.size(); ++i) + { + const int node_idx = editor.selected_node_indices[i]; + NodeData& node = editor.nodes.pool[node_idx]; + if (node.draggable) + { + node.origin += io.MouseDelta; + } + } + } +} + +OptionalIndex find_duplicate_link( + const EditorContext& editor, + const int start_pin_idx, + const int end_pin_idx) +{ + LinkData test_link(0); + test_link.start_pin_idx = start_pin_idx; + test_link.end_pin_idx = end_pin_idx; + for (int link_idx = 0; link_idx < editor.links.pool.size(); ++link_idx) + { + const LinkData& link = editor.links.pool[link_idx]; + if (LinkPredicate()(test_link, link) && editor.links.in_use[link_idx]) + { + return OptionalIndex(link_idx); + } + } + + return OptionalIndex(); +} + +bool should_link_snap_to_pin( + const EditorContext& editor, + const PinData& start_pin, + const int hovered_pin_idx, + const OptionalIndex duplicate_link) +{ + const PinData& end_pin = editor.pins.pool[hovered_pin_idx]; + + // The end pin must be in a different node + if (start_pin.parent_node_idx == end_pin.parent_node_idx) + { + return false; + } + + // The end pin must be of a different type + if (start_pin.type == end_pin.type) + { + return false; + } + + // The link to be created must not be a duplicate, unless it is the link which was created on + // snap. In that case we want to snap, since we want it to appear visually as if the created + // link remains snapped to the pin. + if (duplicate_link.has_value() && !(duplicate_link == g.snap_link_idx)) + { + return false; + } + + return true; +} + +void click_interaction_update(EditorContext& editor) +{ + switch (editor.click_interaction_type) + { + case ClickInteractionType_BoxSelection: + { + ImRect& box_rect = editor.click_interaction_state.box_selector.rect; + box_rect.Max = g.mouse_pos; + + box_selector_update_selection(editor, box_rect); + + const ImU32 box_selector_color = g.style.colors[ColorStyle_BoxSelector]; + const ImU32 box_selector_outline = g.style.colors[ColorStyle_BoxSelectorOutline]; + g.canvas_draw_list->AddRectFilled(box_rect.Min, box_rect.Max, box_selector_color); + g.canvas_draw_list->AddRect(box_rect.Min, box_rect.Max, box_selector_outline); + + if (g.left_mouse_released) + { + ImVector& depth_stack = editor.node_depth_order; + const ImVector& selected_idxs = editor.selected_node_indices; + + // Bump the selected node indices, in order, to the top of the depth stack. + // NOTE: this algorithm has worst case time complexity of O(N^2), if the node selection + // is ~ N (due to selected_idxs.contains()). + + if ((selected_idxs.Size > 0) && (selected_idxs.Size < depth_stack.Size)) + { + int num_moved = 0; // The number of indices moved. Stop after selected_idxs.Size + for (int i = 0; i < depth_stack.Size - selected_idxs.Size; ++i) + { + for (int node_idx = depth_stack[i]; selected_idxs.contains(node_idx); + node_idx = depth_stack[i]) + { + depth_stack.erase(depth_stack.begin() + static_cast(i)); + depth_stack.push_back(node_idx); + ++num_moved; + } + + if (num_moved == selected_idxs.Size) + { + break; + } + } + } + + editor.click_interaction_type = ClickInteractionType_None; + } + } + break; + case ClickInteractionType_Node: + { + translate_selected_nodes(editor); + + if (g.left_mouse_released) + { + editor.click_interaction_type = ClickInteractionType_None; + } + } + break; + case ClickInteractionType_Link: + { + if (g.left_mouse_released) + { + editor.click_interaction_type = ClickInteractionType_None; + } + } + break; + case ClickInteractionType_LinkCreation: + { + const PinData& start_pin = + editor.pins.pool[editor.click_interaction_state.link_creation.start_pin_idx]; + + const OptionalIndex maybe_duplicate_link_idx = + g.hovered_pin_idx.has_value() + ? find_duplicate_link( + editor, + editor.click_interaction_state.link_creation.start_pin_idx, + g.hovered_pin_idx.value()) + : OptionalIndex(); + + const bool should_snap = + g.hovered_pin_idx.has_value() && + should_link_snap_to_pin( + editor, start_pin, g.hovered_pin_idx.value(), maybe_duplicate_link_idx); + + // If we created on snap and the hovered pin is empty or changed, then we need signal that + // the link's state has changed. + const bool snapping_pin_changed = + editor.click_interaction_state.link_creation.end_pin_idx.has_value() && + !(g.hovered_pin_idx == editor.click_interaction_state.link_creation.end_pin_idx); + + // Detach the link that was created by this link event if it's no longer in snap range + if (snapping_pin_changed && g.snap_link_idx.has_value()) + { + begin_link_detach( + editor, + g.snap_link_idx.value(), + editor.click_interaction_state.link_creation.end_pin_idx.value()); + } + + const ImVec2 start_pos = get_screen_space_pin_coordinates(editor, start_pin); + // If we are within the hover radius of a receiving pin, snap the link + // endpoint to it + const ImVec2 end_pos = should_snap + ? get_screen_space_pin_coordinates( + editor, editor.pins.pool[g.hovered_pin_idx.value()]) + : g.mouse_pos; + + const LinkBezierData link_data = get_link_renderable( + start_pos, end_pos, start_pin.type, g.style.link_line_segments_per_length); +#if IMGUI_VERSION_NUM < 18000 + g.canvas_draw_list->AddBezierCurve( +#else + g.canvas_draw_list->AddBezierCubic( +#endif + link_data.bezier.p0, + link_data.bezier.p1, + link_data.bezier.p2, + link_data.bezier.p3, + g.style.colors[ColorStyle_Link], + g.style.link_thickness, + link_data.num_segments); + + const bool link_creation_on_snap = + g.hovered_pin_idx.has_value() && (editor.pins.pool[g.hovered_pin_idx.value()].flags & + AttributeFlags_EnableLinkCreationOnSnap); + + if (!should_snap) + { + editor.click_interaction_state.link_creation.end_pin_idx.reset(); + } + + const bool create_link = should_snap && (g.left_mouse_released || link_creation_on_snap); + + if (create_link && !maybe_duplicate_link_idx.has_value()) + { + // Avoid send OnLinkCreated() events every frame if the snap link is not saved + // (only applies for EnableLinkCreationOnSnap) + if (!g.left_mouse_released && + editor.click_interaction_state.link_creation.end_pin_idx == g.hovered_pin_idx) + { + break; + } + + g.element_state_change |= ElementStateChange_LinkCreated; + editor.click_interaction_state.link_creation.end_pin_idx = g.hovered_pin_idx.value(); + } + + if (g.left_mouse_released) + { + editor.click_interaction_type = ClickInteractionType_None; + if (!create_link) + { + g.element_state_change |= ElementStateChange_LinkDropped; + } + } + } + break; + case ClickInteractionType_Panning: + { + const bool dragging = g.middle_mouse_dragging; + + if (dragging) + { + editor.panning += ImGui::GetIO().MouseDelta; + } + else + { + editor.click_interaction_type = ClickInteractionType_None; + } + } + break; + case ClickInteractionType_None: + break; + default: + assert(!"Unreachable code!"); + break; + } +} + +OptionalIndex resolve_hovered_node(const EditorContext& editor) +{ + if (g.node_indices_overlapping_with_mouse.size() == 0) + { + return OptionalIndex(); + } + + if (g.node_indices_overlapping_with_mouse.size() == 1) + { + return OptionalIndex(g.node_indices_overlapping_with_mouse[0]); + } + + int largest_depth_idx = -1; + int node_idx_on_top = -1; + + const ImVector& depth_stack = editor.node_depth_order; + for (int i = 0; i < g.node_indices_overlapping_with_mouse.size(); ++i) + { + const int node_idx = g.node_indices_overlapping_with_mouse[i]; + for (int depth_idx = 0; depth_idx < depth_stack.size(); ++depth_idx) + { + if (depth_stack[depth_idx] == node_idx && (depth_idx > largest_depth_idx)) + { + largest_depth_idx = depth_idx; + node_idx_on_top = node_idx; + } + } + } + + assert(node_idx_on_top != -1); + return OptionalIndex(node_idx_on_top); +} + +// [SECTION] render helpers + +inline ImVec2 screen_space_to_grid_space(const EditorContext& editor, const ImVec2& v) +{ + return v - g.canvas_origin_screen_space - editor.panning; +} + +inline ImVec2 grid_space_to_screen_space(const EditorContext& editor, const ImVec2& v) +{ + return v + g.canvas_origin_screen_space + editor.panning; +} + +inline ImVec2 grid_space_to_editor_space(const EditorContext& editor, const ImVec2& v) +{ + return v + editor.panning; +} + +inline ImVec2 editor_space_to_grid_space(const EditorContext& editor, const ImVec2& v) +{ + return v - editor.panning; +} + +inline ImVec2 editor_space_to_screen_space(const ImVec2& v) +{ + return g.canvas_origin_screen_space + v; +} + +inline ImRect get_item_rect() { return ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); } + +inline ImVec2 get_node_title_bar_origin(const NodeData& node) +{ + return node.origin + node.layout_style.padding; +} + +inline ImVec2 get_node_content_origin(const NodeData& node) +{ + const ImVec2 title_bar_height = + ImVec2(0.f, node.title_bar_content_rect.GetHeight() + 2.0f * node.layout_style.padding.y); + return node.origin + title_bar_height + node.layout_style.padding; +} + +inline ImRect get_node_title_rect(const NodeData& node) +{ + ImRect expanded_title_rect = node.title_bar_content_rect; + expanded_title_rect.Expand(node.layout_style.padding); + + return ImRect( + expanded_title_rect.Min, + expanded_title_rect.Min + ImVec2(node.rect.GetWidth(), 0.f) + + ImVec2(0.f, expanded_title_rect.GetHeight())); +} + +void draw_grid(EditorContext& editor, const ImVec2& canvas_size) +{ + const ImVec2 offset = editor.panning; + + for (float x = fmodf(offset.x, g.style.grid_spacing); x < canvas_size.x; + x += g.style.grid_spacing) + { + g.canvas_draw_list->AddLine( + editor_space_to_screen_space(ImVec2(x, 0.0f)), + editor_space_to_screen_space(ImVec2(x, canvas_size.y)), + g.style.colors[ColorStyle_GridLine]); + } + + for (float y = fmodf(offset.y, g.style.grid_spacing); y < canvas_size.y; + y += g.style.grid_spacing) + { + g.canvas_draw_list->AddLine( + editor_space_to_screen_space(ImVec2(0.0f, y)), + editor_space_to_screen_space(ImVec2(canvas_size.x, y)), + g.style.colors[ColorStyle_GridLine]); + } +} + +struct QuadOffsets +{ + ImVec2 top_left, bottom_left, bottom_right, top_right; +}; + +QuadOffsets calculate_quad_offsets(const float side_length) +{ + const float half_side = 0.5f * side_length; + + QuadOffsets offset; + + offset.top_left = ImVec2(-half_side, half_side); + offset.bottom_left = ImVec2(-half_side, -half_side); + offset.bottom_right = ImVec2(half_side, -half_side); + offset.top_right = ImVec2(half_side, half_side); + + return offset; +} + +struct TriangleOffsets +{ + ImVec2 top_left, bottom_left, right; +}; + +TriangleOffsets calculate_triangle_offsets(const float side_length) +{ + // Calculates the Vec2 offsets from an equilateral triangle's midpoint to + // its vertices. Here is how the left_offset and right_offset are + // calculated. + // + // For an equilateral triangle of side length s, the + // triangle's height, h, is h = s * sqrt(3) / 2. + // + // The length from the base to the midpoint is (1 / 3) * h. The length from + // the midpoint to the triangle vertex is (2 / 3) * h. + const float sqrt_3 = sqrtf(3.0f); + const float left_offset = -0.1666666666667f * sqrt_3 * side_length; + const float right_offset = 0.333333333333f * sqrt_3 * side_length; + const float vertical_offset = 0.5f * side_length; + + TriangleOffsets offset; + offset.top_left = ImVec2(left_offset, vertical_offset); + offset.bottom_left = ImVec2(left_offset, -vertical_offset); + offset.right = ImVec2(right_offset, 0.f); + + return offset; +} + +void draw_pin_shape(const ImVec2& pin_pos, const PinData& pin, const ImU32 pin_color) +{ + static const int circle_num_segments = 8; + + switch (pin.shape) + { + case PinShape_Circle: + { + g.canvas_draw_list->AddCircle( + pin_pos, + g.style.pin_circle_radius, + pin_color, + circle_num_segments, + g.style.pin_line_thickness); + } + break; + case PinShape_CircleFilled: + { + g.canvas_draw_list->AddCircleFilled( + pin_pos, g.style.pin_circle_radius, pin_color, circle_num_segments); + } + break; + case PinShape_Quad: + { + const QuadOffsets offset = calculate_quad_offsets(g.style.pin_quad_side_length); + g.canvas_draw_list->AddQuad( + pin_pos + offset.top_left, + pin_pos + offset.bottom_left, + pin_pos + offset.bottom_right, + pin_pos + offset.top_right, + pin_color, + g.style.pin_line_thickness); + } + break; + case PinShape_QuadFilled: + { + const QuadOffsets offset = calculate_quad_offsets(g.style.pin_quad_side_length); + g.canvas_draw_list->AddQuadFilled( + pin_pos + offset.top_left, + pin_pos + offset.bottom_left, + pin_pos + offset.bottom_right, + pin_pos + offset.top_right, + pin_color); + } + break; + case PinShape_Triangle: + { + const TriangleOffsets offset = calculate_triangle_offsets(g.style.pin_triangle_side_length); + g.canvas_draw_list->AddTriangle( + pin_pos + offset.top_left, + pin_pos + offset.bottom_left, + pin_pos + offset.right, + pin_color, + // NOTE: for some weird reason, the line drawn by AddTriangle is + // much thinner than the lines drawn by AddCircle or AddQuad. + // Multiplying the line thickness by two seemed to solve the + // problem at a few different thickness values. + 2.f * g.style.pin_line_thickness); + } + break; + case PinShape_TriangleFilled: + { + const TriangleOffsets offset = calculate_triangle_offsets(g.style.pin_triangle_side_length); + g.canvas_draw_list->AddTriangleFilled( + pin_pos + offset.top_left, + pin_pos + offset.bottom_left, + pin_pos + offset.right, + pin_color); + } + break; + default: + assert(!"Invalid PinShape value!"); + break; + } +} + +bool is_pin_hovered(const PinData& pin) +{ + return is_mouse_hovering_near_point(pin.pos, g.style.pin_hover_radius); +} + +void draw_pin(EditorContext& editor, const int pin_idx, const bool left_mouse_clicked) +{ + PinData& pin = editor.pins.pool[pin_idx]; + const ImRect& parent_node_rect = editor.nodes.pool[pin.parent_node_idx].rect; + + pin.pos = get_screen_space_pin_coordinates(parent_node_rect, pin.attribute_rect, pin.type); + + ImU32 pin_color = pin.color_style.background; + + const bool pin_hovered = is_pin_hovered(pin) && mouse_in_canvas() && + editor.click_interaction_type != ClickInteractionType_BoxSelection; + + if (pin_hovered) + { + g.hovered_pin_idx = pin_idx; + g.hovered_pin_flags = pin.flags; + pin_color = pin.color_style.hovered; + + if (left_mouse_clicked) + { + begin_link_creation(editor, pin_idx); + } + } + + draw_pin_shape(pin.pos, pin, pin_color); +} + +// TODO: Separate hover code from drawing code to avoid this unpleasant divergent function +// signature. +bool is_node_hovered(const NodeData& node, const int node_idx, const ObjectPool pins) +{ + // We render pins on top of nodes. In order to prevent node interaction when a pin is on top of + // a node, we just early out here if a pin is hovered. + for (int i = 0; i < node.pin_indices.size(); ++i) + { + const PinData& pin = pins.pool[node.pin_indices[i]]; + if (is_pin_hovered(pin)) + { + return false; + } + } + + return g.hovered_node_idx.has_value() && node_idx == g.hovered_node_idx.value(); +} + +// TODO: It may be useful to make this an EditorContext method, since this uses +// a lot of editor state. Currently that is just not clear, since we don't pass +// the editor as a part of the function signature. +void draw_node(EditorContext& editor, const int node_idx) +{ + const NodeData& node = editor.nodes.pool[node_idx]; + ImGui::SetCursorPos(node.origin + editor.panning); + + const bool node_hovered = is_node_hovered(node, node_idx, editor.pins) && mouse_in_canvas() && + editor.click_interaction_type != ClickInteractionType_BoxSelection; + + ImU32 node_background = node.color_style.background; + ImU32 titlebar_background = node.color_style.titlebar; + + if (editor.selected_node_indices.contains(node_idx)) + { + node_background = node.color_style.background_selected; + titlebar_background = node.color_style.titlebar_selected; + } + else if (node_hovered) + { + node_background = node.color_style.background_hovered; + titlebar_background = node.color_style.titlebar_hovered; + } + + { + // node base + g.canvas_draw_list->AddRectFilled( + node.rect.Min, node.rect.Max, node_background, node.layout_style.corner_rounding); + + // title bar: + if (node.title_bar_content_rect.GetHeight() > 0.f) + { + ImRect title_bar_rect = get_node_title_rect(node); + + g.canvas_draw_list->AddRectFilled( + title_bar_rect.Min, + title_bar_rect.Max, + titlebar_background, + node.layout_style.corner_rounding, + ImDrawCornerFlags_Top); + } + + if ((g.style.flags & StyleFlags_NodeOutline) != 0) + { + g.canvas_draw_list->AddRect( + node.rect.Min, + node.rect.Max, + node.color_style.outline, + node.layout_style.corner_rounding, + ImDrawCornerFlags_All, + node.layout_style.border_thickness); + } + } + + for (int i = 0; i < node.pin_indices.size(); ++i) + { + draw_pin(editor, node.pin_indices[i], g.left_mouse_clicked); + } + + if (node_hovered) + { + g.hovered_node_idx = node_idx; + const bool node_free_to_move = g.interactive_node_idx != node_idx; + if (g.left_mouse_clicked && node_free_to_move) + { + begin_node_selection(editor, node_idx); + } + } +} + +bool is_link_hovered(const LinkBezierData& link_data) +{ + // We render pins and nodes on top of links. In order to prevent link interaction when a pin or + // node is on top of a link, we just early out here if a pin or node is hovered. + if (g.hovered_pin_idx.has_value() || g.hovered_node_idx.has_value()) + { + return false; + } + + return is_mouse_hovering_near_link(link_data.bezier, link_data.num_segments); +} + +void draw_link(EditorContext& editor, const int link_idx) +{ + const LinkData& link = editor.links.pool[link_idx]; + const PinData& start_pin = editor.pins.pool[link.start_pin_idx]; + const PinData& end_pin = editor.pins.pool[link.end_pin_idx]; + + const LinkBezierData link_data = get_link_renderable( + start_pin.pos, end_pin.pos, start_pin.type, g.style.link_line_segments_per_length); + + const bool link_hovered = is_link_hovered(link_data) && mouse_in_canvas() && + editor.click_interaction_type != ClickInteractionType_BoxSelection; + + if (link_hovered) + { + g.hovered_link_idx = link_idx; + if (g.left_mouse_clicked) + { + begin_link_interaction(editor, link_idx); + } + } + + // It's possible for a link to be deleted in begin_link_interaction. A user + // may detach a link, resulting in the link wire snapping to the mouse + // position. + // + // In other words, skip rendering the link if it was deleted. + if (g.deleted_link_idx == link_idx) + { + return; + } + + ImU32 link_color = link.color_style.base; + if (editor.selected_link_indices.contains(link_idx)) + { + link_color = link.color_style.selected; + } + else if (link_hovered) + { + link_color = link.color_style.hovered; + } + +#if IMGUI_VERSION_NUM < 18000 + g.canvas_draw_list->AddBezierCurve( +#else + g.canvas_draw_list->AddBezierCubic( +#endif + link_data.bezier.p0, + link_data.bezier.p1, + link_data.bezier.p2, + link_data.bezier.p3, + link_color, + g.style.link_thickness, + link_data.num_segments); +} + +void begin_pin_attribute( + const int id, + const AttributeType type, + const PinShape shape, + const int node_idx) +{ + // Make sure to call BeginNode() before calling + // BeginAttribute() + assert(g.current_scope == Scope_Node); + g.current_scope = Scope_Attribute; + + ImGui::BeginGroup(); + ImGui::PushID(id); + + EditorContext& editor = editor_context_get(); + + g.current_attribute_id = id; + + const int pin_idx = object_pool_find_or_create_index(editor.pins, id); + g.current_pin_idx = pin_idx; + PinData& pin = editor.pins.pool[pin_idx]; + pin.id = id; + pin.parent_node_idx = node_idx; + pin.type = type; + pin.shape = shape; + pin.flags = g.current_attribute_flags; + pin.color_style.background = g.style.colors[ColorStyle_Pin]; + pin.color_style.hovered = g.style.colors[ColorStyle_PinHovered]; +} + +void end_pin_attribute() +{ + assert(g.current_scope == Scope_Attribute); + g.current_scope = Scope_Node; + + ImGui::PopID(); + ImGui::EndGroup(); + + if (ImGui::IsItemActive()) + { + g.active_attribute = true; + g.active_attribute_id = g.current_attribute_id; + g.interactive_node_idx = g.current_node_idx; + } + + EditorContext& editor = editor_context_get(); + PinData& pin = editor.pins.pool[g.current_pin_idx]; + NodeData& node = editor.nodes.pool[g.current_node_idx]; + pin.attribute_rect = get_item_rect(); + node.pin_indices.push_back(g.current_pin_idx); +} +} // namespace + +// [SECTION] API implementation + +IO::EmulateThreeButtonMouse::EmulateThreeButtonMouse() : enabled(false), modifier(NULL) {} + +IO::LinkDetachWithModifierClick::LinkDetachWithModifierClick() : modifier(NULL) {} + +IO::IO() : emulate_three_button_mouse(), link_detach_with_modifier_click() {} + +Style::Style() + : grid_spacing(32.f), node_corner_rounding(4.f), node_padding_horizontal(8.f), + node_padding_vertical(8.f), node_border_thickness(1.f), link_thickness(3.f), + link_line_segments_per_length(0.1f), link_hover_distance(10.f), pin_circle_radius(4.f), + pin_quad_side_length(7.f), pin_triangle_side_length(9.5), pin_line_thickness(1.f), + pin_hover_radius(10.f), pin_offset(0.f), + flags(StyleFlags(StyleFlags_NodeOutline | StyleFlags_GridLines)), colors() +{ +} + +EditorContext* EditorContextCreate() +{ + void* mem = ImGui::MemAlloc(sizeof(EditorContext)); + new (mem) EditorContext(); + return (EditorContext*)mem; +} + +void EditorContextFree(EditorContext* ctx) +{ + ctx->~EditorContext(); + ImGui::MemFree(ctx); +} + +void EditorContextSet(EditorContext* ctx) { g.editor_ctx = ctx; } + +ImVec2 EditorContextGetPanning() +{ + const EditorContext& editor = editor_context_get(); + return editor.panning; +} + +void EditorContextResetPanning(const ImVec2& pos) +{ + EditorContext& editor = editor_context_get(); + editor.panning = pos; +} + +void EditorContextMoveToNode(const int node_id) +{ + EditorContext& editor = editor_context_get(); + NodeData& node = object_pool_find_or_create_object(editor.nodes, node_id); + + editor.panning.x = -node.origin.x; + editor.panning.y = -node.origin.y; +} + +void Initialize() +{ + g.canvas_origin_screen_space = ImVec2(0.0f, 0.0f); + g.canvas_rect_screen_space = ImRect(ImVec2(0.f, 0.f), ImVec2(0.f, 0.f)); + g.current_scope = Scope_None; + + g.current_pin_idx = INT_MAX; + g.current_node_idx = INT_MAX; + + g.default_editor_ctx = EditorContextCreate(); + EditorContextSet(g.default_editor_ctx); + + const ImGuiIO& io = ImGui::GetIO(); + g.io.emulate_three_button_mouse.modifier = &io.KeyAlt; + + g.current_attribute_flags = AttributeFlags_None; + g.attribute_flag_stack.push_back(g.current_attribute_flags); + + StyleColorsDark(); +} + +void Shutdown() +{ + EditorContextFree(g.default_editor_ctx); + g.editor_ctx = NULL; + g.default_editor_ctx = NULL; +} + +IO& GetIO() { return g.io; } + +Style& GetStyle() { return g.style; } + +void StyleColorsDark() +{ + g.style.colors[ColorStyle_NodeBackground] = IM_COL32(50, 50, 50, 255); + g.style.colors[ColorStyle_NodeBackgroundHovered] = IM_COL32(75, 75, 75, 255); + g.style.colors[ColorStyle_NodeBackgroundSelected] = IM_COL32(75, 75, 75, 255); + g.style.colors[ColorStyle_NodeOutline] = IM_COL32(100, 100, 100, 255); + // title bar colors match ImGui's titlebg colors + g.style.colors[ColorStyle_TitleBar] = IM_COL32(41, 74, 122, 255); + g.style.colors[ColorStyle_TitleBarHovered] = IM_COL32(66, 150, 250, 255); + g.style.colors[ColorStyle_TitleBarSelected] = IM_COL32(66, 150, 250, 255); + // link colors match ImGui's slider grab colors + g.style.colors[ColorStyle_Link] = IM_COL32(61, 133, 224, 200); + g.style.colors[ColorStyle_LinkHovered] = IM_COL32(66, 150, 250, 255); + g.style.colors[ColorStyle_LinkSelected] = IM_COL32(66, 150, 250, 255); + // pin colors match ImGui's button colors + g.style.colors[ColorStyle_Pin] = IM_COL32(53, 150, 250, 180); + g.style.colors[ColorStyle_PinHovered] = IM_COL32(53, 150, 250, 255); + + g.style.colors[ColorStyle_BoxSelector] = IM_COL32(61, 133, 224, 30); + g.style.colors[ColorStyle_BoxSelectorOutline] = IM_COL32(61, 133, 224, 150); + + g.style.colors[ColorStyle_GridBackground] = IM_COL32(40, 40, 50, 200); + g.style.colors[ColorStyle_GridLine] = IM_COL32(200, 200, 200, 40); +} + +void StyleColorsClassic() +{ + g.style.colors[ColorStyle_NodeBackground] = IM_COL32(50, 50, 50, 255); + g.style.colors[ColorStyle_NodeBackgroundHovered] = IM_COL32(75, 75, 75, 255); + g.style.colors[ColorStyle_NodeBackgroundSelected] = IM_COL32(75, 75, 75, 255); + g.style.colors[ColorStyle_NodeOutline] = IM_COL32(100, 100, 100, 255); + g.style.colors[ColorStyle_TitleBar] = IM_COL32(69, 69, 138, 255); + g.style.colors[ColorStyle_TitleBarHovered] = IM_COL32(82, 82, 161, 255); + g.style.colors[ColorStyle_TitleBarSelected] = IM_COL32(82, 82, 161, 255); + g.style.colors[ColorStyle_Link] = IM_COL32(255, 255, 255, 100); + g.style.colors[ColorStyle_LinkHovered] = IM_COL32(105, 99, 204, 153); + g.style.colors[ColorStyle_LinkSelected] = IM_COL32(105, 99, 204, 153); + g.style.colors[ColorStyle_Pin] = IM_COL32(89, 102, 156, 170); + g.style.colors[ColorStyle_PinHovered] = IM_COL32(102, 122, 179, 200); + g.style.colors[ColorStyle_BoxSelector] = IM_COL32(82, 82, 161, 100); + g.style.colors[ColorStyle_BoxSelectorOutline] = IM_COL32(82, 82, 161, 255); + g.style.colors[ColorStyle_GridBackground] = IM_COL32(40, 40, 50, 200); + g.style.colors[ColorStyle_GridLine] = IM_COL32(200, 200, 200, 40); +} + +void StyleColorsLight() +{ + g.style.colors[ColorStyle_NodeBackground] = IM_COL32(240, 240, 240, 255); + g.style.colors[ColorStyle_NodeBackgroundHovered] = IM_COL32(240, 240, 240, 255); + g.style.colors[ColorStyle_NodeBackgroundSelected] = IM_COL32(240, 240, 240, 255); + g.style.colors[ColorStyle_NodeOutline] = IM_COL32(100, 100, 100, 255); + g.style.colors[ColorStyle_TitleBar] = IM_COL32(248, 248, 248, 255); + g.style.colors[ColorStyle_TitleBarHovered] = IM_COL32(209, 209, 209, 255); + g.style.colors[ColorStyle_TitleBarSelected] = IM_COL32(209, 209, 209, 255); + // original imgui values: 66, 150, 250 + g.style.colors[ColorStyle_Link] = IM_COL32(66, 150, 250, 100); + // original imgui values: 117, 138, 204 + g.style.colors[ColorStyle_LinkHovered] = IM_COL32(66, 150, 250, 242); + g.style.colors[ColorStyle_LinkSelected] = IM_COL32(66, 150, 250, 242); + // original imgui values: 66, 150, 250 + g.style.colors[ColorStyle_Pin] = IM_COL32(66, 150, 250, 160); + g.style.colors[ColorStyle_PinHovered] = IM_COL32(66, 150, 250, 255); + g.style.colors[ColorStyle_BoxSelector] = IM_COL32(90, 170, 250, 30); + g.style.colors[ColorStyle_BoxSelectorOutline] = IM_COL32(90, 170, 250, 150); + g.style.colors[ColorStyle_GridBackground] = IM_COL32(225, 225, 225, 255); + g.style.colors[ColorStyle_GridLine] = IM_COL32(180, 180, 180, 100); + g.style.flags = StyleFlags(StyleFlags_None); +} + +void BeginNodeEditor() +{ + assert(g.current_scope == Scope_None); + g.current_scope = Scope_Editor; + + // Reset state from previous pass + + EditorContext& editor = editor_context_get(); + object_pool_reset(editor.nodes); + object_pool_reset(editor.pins); + object_pool_reset(editor.links); + + g.hovered_node_idx.reset(); + g.interactive_node_idx.reset(); + g.hovered_link_idx.reset(); + g.hovered_pin_idx.reset(); + g.hovered_pin_flags = AttributeFlags_None; + g.deleted_link_idx.reset(); + g.snap_link_idx.reset(); + + g.node_indices_overlapping_with_mouse.clear(); + + g.element_state_change = ElementStateChange_None; + + g.mouse_pos = ImGui::GetIO().MousePos; + g.left_mouse_clicked = ImGui::IsMouseClicked(0); + g.left_mouse_released = ImGui::IsMouseReleased(0); + g.middle_mouse_clicked = (g.io.emulate_three_button_mouse.enabled && g.left_mouse_clicked && + *g.io.emulate_three_button_mouse.modifier) || + ImGui::IsMouseClicked(2); + g.left_mouse_dragging = ImGui::IsMouseDragging(0, 0.0f); + g.middle_mouse_dragging = (g.io.emulate_three_button_mouse.enabled && g.left_mouse_dragging && + (*g.io.emulate_three_button_mouse.modifier)) || + ImGui::IsMouseDragging(2, 0.0f); + + g.active_attribute = false; + + ImGui::BeginGroup(); + { + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(1.f, 1.f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.f, 0.f)); + ImGui::PushStyleColor(ImGuiCol_ChildBg, g.style.colors[ColorStyle_GridBackground]); + ImGui::BeginChild( + "scrolling_region", + ImVec2(0.f, 0.f), + true, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollWithMouse); + g.canvas_origin_screen_space = ImGui::GetCursorScreenPos(); + + // NOTE: we have to fetch the canvas draw list *after* we call + // BeginChild(), otherwise the ImGui UI elements are going to be + // rendered into the parent window draw list. + draw_list_set(ImGui::GetWindowDrawList()); + + { + const ImVec2 canvas_size = ImGui::GetWindowSize(); + g.canvas_rect_screen_space = ImRect( + editor_space_to_screen_space(ImVec2(0.f, 0.f)), + editor_space_to_screen_space(canvas_size)); + + if (g.style.flags & StyleFlags_GridLines) + { + draw_grid(editor, canvas_size); + } + } + } +} + +void EndNodeEditor() +{ + assert(g.current_scope == Scope_Editor); + g.current_scope = Scope_None; + + EditorContext& editor = editor_context_get(); + + // Resolve which node is actually on top and being hovered. This needs to be done before any of + // the nodes can be rendered. + + g.hovered_node_idx = resolve_hovered_node(editor); + + // Render the nodes and resolve which pin the mouse is hovering over. The hovered pin is needed + // for handling click interactions. + + for (int node_idx = 0; node_idx < editor.nodes.pool.size(); ++node_idx) + { + if (editor.nodes.in_use[node_idx]) + { + draw_list_activate_node_background(node_idx); + draw_node(editor, node_idx); + } + } + + // In order to render the links underneath the nodes, we want to first select the bottom draw + // channel. + g.canvas_draw_list->ChannelsSetCurrent(0); + + for (int link_idx = 0; link_idx < editor.links.pool.size(); ++link_idx) + { + if (editor.links.in_use[link_idx]) + { + draw_link(editor, link_idx); + } + } + + // Render the click interaction UI elements (partial links, box selector) on top of everything + // else. + + draw_list_append_click_interaction_channel(); + draw_list_activate_click_interaction_channel(); + + if (g.left_mouse_clicked || g.middle_mouse_clicked) + { + begin_canvas_interaction(editor); + } + + click_interaction_update(editor); + + // At this point, draw commands have been issued for all nodes (and pins). Update the node pool + // to detect unused node slots and remove those indices from the depth stack before sorting the + // node draw commands by depth. + object_pool_update(editor.nodes); + object_pool_update(editor.pins); + + draw_list_sort_channels_by_depth(editor.node_depth_order); + + // After the links have been rendered, the link pool can be updated as well. + object_pool_update(editor.links); + + // Finally, merge the draw channels + g.canvas_draw_list->ChannelsMerge(); + + // pop style + ImGui::EndChild(); // end scrolling region + ImGui::PopStyleColor(); // pop child window background color + ImGui::PopStyleVar(); // pop window padding + ImGui::PopStyleVar(); // pop frame padding + ImGui::EndGroup(); +} + +void BeginNode(const int node_id) +{ + // Remember to call BeginNodeEditor before calling BeginNode + assert(g.current_scope == Scope_Editor); + g.current_scope = Scope_Node; + + EditorContext& editor = editor_context_get(); + + const int node_idx = object_pool_find_or_create_index(editor.nodes, node_id); + g.current_node_idx = node_idx; + + NodeData& node = editor.nodes.pool[node_idx]; + node.color_style.background = g.style.colors[ColorStyle_NodeBackground]; + node.color_style.background_hovered = g.style.colors[ColorStyle_NodeBackgroundHovered]; + node.color_style.background_selected = g.style.colors[ColorStyle_NodeBackgroundSelected]; + node.color_style.outline = g.style.colors[ColorStyle_NodeOutline]; + node.color_style.titlebar = g.style.colors[ColorStyle_TitleBar]; + node.color_style.titlebar_hovered = g.style.colors[ColorStyle_TitleBarHovered]; + node.color_style.titlebar_selected = g.style.colors[ColorStyle_TitleBarSelected]; + node.layout_style.corner_rounding = g.style.node_corner_rounding; + node.layout_style.padding = + ImVec2(g.style.node_padding_horizontal, g.style.node_padding_vertical); + node.layout_style.border_thickness = g.style.node_border_thickness; + + // ImGui::SetCursorPos sets the cursor position, local to the current widget + // (in this case, the child object started in BeginNodeEditor). Use + // ImGui::SetCursorScreenPos to set the screen space coordinates directly. + ImGui::SetCursorPos(grid_space_to_editor_space(editor, get_node_title_bar_origin(node))); + + draw_list_add_node(node_idx); + draw_list_activate_current_node_foreground(); + + ImGui::PushID(node.id); + ImGui::BeginGroup(); +} + +void EndNode() +{ + assert(g.current_scope == Scope_Node); + g.current_scope = Scope_Editor; + + EditorContext& editor = editor_context_get(); + + // The node's rectangle depends on the ImGui UI group size. + ImGui::EndGroup(); + ImGui::PopID(); + + NodeData& node = editor.nodes.pool[g.current_node_idx]; + node.rect = get_item_rect(); + node.rect.Expand(node.layout_style.padding); + + if (node.rect.Contains(g.mouse_pos)) + { + g.node_indices_overlapping_with_mouse.push_back(g.current_node_idx); + } +} + +ImVec2 GetNodeDimensions(int node_id) +{ + EditorContext& editor = editor_context_get(); + const int node_idx = object_pool_find(editor.nodes, node_id); + assert(node_idx != -1); // invalid node_id + const NodeData& node = editor.nodes.pool[node_idx]; + return node.rect.GetSize(); +} + +void BeginNodeTitleBar() +{ + assert(g.current_scope == Scope_Node); + ImGui::BeginGroup(); +} + +void EndNodeTitleBar() +{ + assert(g.current_scope == Scope_Node); + ImGui::EndGroup(); + + EditorContext& editor = editor_context_get(); + NodeData& node = editor.nodes.pool[g.current_node_idx]; + node.title_bar_content_rect = get_item_rect(); + + ImGui::ItemAdd(get_node_title_rect(node), ImGui::GetID("title_bar")); + + ImGui::SetCursorPos(grid_space_to_editor_space(editor, get_node_content_origin(node))); +} + +void BeginInputAttribute(const int id, const PinShape shape) +{ + begin_pin_attribute(id, AttributeType_Input, shape, g.current_node_idx); +} + +void EndInputAttribute() { end_pin_attribute(); } + +void BeginOutputAttribute(const int id, const PinShape shape) +{ + begin_pin_attribute(id, AttributeType_Output, shape, g.current_node_idx); +} + +void EndOutputAttribute() { end_pin_attribute(); } + +void BeginStaticAttribute(const int id) +{ + // Make sure to call BeginNode() before calling BeginAttribute() + assert(g.current_scope == Scope_Node); + g.current_scope = Scope_Attribute; + + g.current_attribute_id = id; + + ImGui::BeginGroup(); + ImGui::PushID(id); +} + +void EndStaticAttribute() +{ + // Make sure to call BeginNode() before calling BeginAttribute() + assert(g.current_scope == Scope_Attribute); + g.current_scope = Scope_Node; + + ImGui::PopID(); + ImGui::EndGroup(); + + if (ImGui::IsItemActive()) + { + g.active_attribute = true; + g.active_attribute_id = g.current_attribute_id; + g.interactive_node_idx = g.current_node_idx; + } +} + +void PushAttributeFlag(AttributeFlags flag) +{ + g.current_attribute_flags |= static_cast(flag); + g.attribute_flag_stack.push_back(g.current_attribute_flags); +} + +void PopAttributeFlag() +{ + // PopAttributeFlag called without a matching PushAttributeFlag! + // The bottom value is always the default value, pushed in Initialize(). + assert(g.attribute_flag_stack.size() > 1); + + g.attribute_flag_stack.pop_back(); + g.current_attribute_flags = g.attribute_flag_stack.back(); +} + +void Link(int id, const int start_attr_id, const int end_attr_id) +{ + assert(g.current_scope == Scope_Editor); + + EditorContext& editor = editor_context_get(); + LinkData& link = object_pool_find_or_create_object(editor.links, id); + link.id = id; + link.start_pin_idx = object_pool_find_or_create_index(editor.pins, start_attr_id); + link.end_pin_idx = object_pool_find_or_create_index(editor.pins, end_attr_id); + link.color_style.base = g.style.colors[ColorStyle_Link]; + link.color_style.hovered = g.style.colors[ColorStyle_LinkHovered]; + link.color_style.selected = g.style.colors[ColorStyle_LinkSelected]; + + // Check if this link was created by the current link event + if ((editor.click_interaction_type == ClickInteractionType_LinkCreation && + editor.pins.pool[link.end_pin_idx].flags & AttributeFlags_EnableLinkCreationOnSnap && + editor.click_interaction_state.link_creation.start_pin_idx == link.start_pin_idx && + editor.click_interaction_state.link_creation.end_pin_idx == link.end_pin_idx) || + (editor.click_interaction_state.link_creation.start_pin_idx == link.end_pin_idx && + editor.click_interaction_state.link_creation.end_pin_idx == link.start_pin_idx)) + { + g.snap_link_idx = object_pool_find_or_create_index(editor.links, id); + } +} + +void PushColorStyle(ColorStyle item, unsigned int color) +{ + g.color_modifier_stack.push_back(ColorStyleElement(g.style.colors[item], item)); + g.style.colors[item] = color; +} + +void PopColorStyle() +{ + assert(g.color_modifier_stack.size() > 0); + const ColorStyleElement elem = g.color_modifier_stack.back(); + g.style.colors[elem.item] = elem.color; + g.color_modifier_stack.pop_back(); +} + +float& lookup_style_var(const StyleVar item) +{ + // TODO: once the switch gets too big and unwieldy to work with, we could do + // a byte-offset lookup into the Style struct, using the StyleVar as an + // index. This is how ImGui does it. + float* style_var = 0; + switch (item) + { + case StyleVar_GridSpacing: + style_var = &g.style.grid_spacing; + break; + case StyleVar_NodeCornerRounding: + style_var = &g.style.node_corner_rounding; + break; + case StyleVar_NodePaddingHorizontal: + style_var = &g.style.node_padding_horizontal; + break; + case StyleVar_NodePaddingVertical: + style_var = &g.style.node_padding_vertical; + break; + case StyleVar_NodeBorderThickness: + style_var = &g.style.node_border_thickness; + break; + case StyleVar_LinkThickness: + style_var = &g.style.link_thickness; + break; + case StyleVar_LinkLineSegmentsPerLength: + style_var = &g.style.link_line_segments_per_length; + break; + case StyleVar_LinkHoverDistance: + style_var = &g.style.link_hover_distance; + break; + case StyleVar_PinCircleRadius: + style_var = &g.style.pin_circle_radius; + break; + case StyleVar_PinQuadSideLength: + style_var = &g.style.pin_quad_side_length; + break; + case StyleVar_PinTriangleSideLength: + style_var = &g.style.pin_triangle_side_length; + break; + case StyleVar_PinLineThickness: + style_var = &g.style.pin_line_thickness; + break; + case StyleVar_PinHoverRadius: + style_var = &g.style.pin_hover_radius; + break; + case StyleVar_PinOffset: + style_var = &g.style.pin_offset; + break; + default: + assert(!"Invalid StyleVar value!"); + } + + return *style_var; +} + +void PushStyleVar(const StyleVar item, const float value) +{ + float& style_var = lookup_style_var(item); + g.style_modifier_stack.push_back(StyleElement(style_var, item)); + style_var = value; +} + +void PopStyleVar() +{ + assert(g.style_modifier_stack.size() > 0); + const StyleElement style_elem = g.style_modifier_stack.back(); + g.style_modifier_stack.pop_back(); + float& style_var = lookup_style_var(style_elem.item); + style_var = style_elem.value; +} + +void SetNodeScreenSpacePos(int node_id, const ImVec2& screen_space_pos) +{ + EditorContext& editor = editor_context_get(); + NodeData& node = object_pool_find_or_create_object(editor.nodes, node_id); + node.origin = screen_space_to_grid_space(editor, screen_space_pos); +} + +void SetNodeEditorSpacePos(int node_id, const ImVec2& editor_space_pos) +{ + EditorContext& editor = editor_context_get(); + NodeData& node = object_pool_find_or_create_object(editor.nodes, node_id); + node.origin = editor_space_to_grid_space(editor, editor_space_pos); +} + +void SetNodeGridSpacePos(int node_id, const ImVec2& grid_pos) +{ + EditorContext& editor = editor_context_get(); + NodeData& node = object_pool_find_or_create_object(editor.nodes, node_id); + node.origin = grid_pos; +} + +void SetNodeDraggable(int node_id, const bool draggable) +{ + EditorContext& editor = editor_context_get(); + NodeData& node = object_pool_find_or_create_object(editor.nodes, node_id); + node.draggable = draggable; +} + +ImVec2 GetNodeScreenSpacePos(const int node_id) +{ + EditorContext& editor = editor_context_get(); + const int node_idx = object_pool_find(editor.nodes, node_id); + assert(node_idx != -1); + NodeData& node = editor.nodes.pool[node_idx]; + return grid_space_to_screen_space(editor, node.origin); +} + +ImVec2 GetNodeEditorSpacePos(const int node_id) +{ + EditorContext& editor = editor_context_get(); + const int node_idx = object_pool_find(editor.nodes, node_id); + assert(node_idx != -1); + NodeData& node = editor.nodes.pool[node_idx]; + return grid_space_to_editor_space(editor, node.origin); +} + +ImVec2 GetNodeGridSpacePos(int node_id) +{ + EditorContext& editor = editor_context_get(); + const int node_idx = object_pool_find(editor.nodes, node_id); + assert(node_idx != -1); + NodeData& node = editor.nodes.pool[node_idx]; + return node.origin; +} + +bool IsEditorHovered() { return mouse_in_canvas(); } + +bool IsNodeHovered(int* const node_id) +{ + assert(g.current_scope == Scope_None); + assert(node_id != NULL); + + const bool is_hovered = g.hovered_node_idx.has_value(); + if (is_hovered) + { + const EditorContext& editor = editor_context_get(); + *node_id = editor.nodes.pool[g.hovered_node_idx.value()].id; + } + return is_hovered; +} + +bool IsLinkHovered(int* const link_id) +{ + assert(g.current_scope == Scope_None); + assert(link_id != NULL); + + const bool is_hovered = g.hovered_link_idx.has_value(); + if (is_hovered) + { + const EditorContext& editor = editor_context_get(); + *link_id = editor.links.pool[g.hovered_link_idx.value()].id; + } + return is_hovered; +} + +bool IsPinHovered(int* const attr) +{ + assert(g.current_scope == Scope_None); + assert(attr != NULL); + + const bool is_hovered = g.hovered_pin_idx.has_value(); + if (is_hovered) + { + const EditorContext& editor = editor_context_get(); + *attr = editor.pins.pool[g.hovered_pin_idx.value()].id; + } + return is_hovered; +} + +int NumSelectedNodes() +{ + assert(g.current_scope == Scope_None); + const EditorContext& editor = editor_context_get(); + return editor.selected_node_indices.size(); +} + +int NumSelectedLinks() +{ + assert(g.current_scope == Scope_None); + const EditorContext& editor = editor_context_get(); + return editor.selected_link_indices.size(); +} + +void GetSelectedNodes(int* node_ids) +{ + assert(node_ids != NULL); + + const EditorContext& editor = editor_context_get(); + for (int i = 0; i < editor.selected_node_indices.size(); ++i) + { + const int node_idx = editor.selected_node_indices[i]; + node_ids[i] = editor.nodes.pool[node_idx].id; + } +} + +void GetSelectedLinks(int* link_ids) +{ + assert(link_ids != NULL); + + const EditorContext& editor = editor_context_get(); + for (int i = 0; i < editor.selected_link_indices.size(); ++i) + { + const int link_idx = editor.selected_link_indices[i]; + link_ids[i] = editor.links.pool[link_idx].id; + } +} + +void ClearNodeSelection() +{ + EditorContext& editor = editor_context_get(); + editor.selected_node_indices.clear(); +} + +void ClearLinkSelection() +{ + EditorContext& editor = editor_context_get(); + editor.selected_link_indices.clear(); +} + +bool IsAttributeActive() +{ + assert((g.current_scope & Scope_Node) != 0); + + if (!g.active_attribute) + { + return false; + } + + return g.active_attribute_id == g.current_attribute_id; +} + +bool IsAnyAttributeActive(int* const attribute_id) +{ + assert((g.current_scope & (Scope_Node | Scope_Attribute)) == 0); + + if (!g.active_attribute) + { + return false; + } + + if (attribute_id != NULL) + { + *attribute_id = g.active_attribute_id; + } + + return true; +} + +bool IsLinkStarted(int* const started_at_id) +{ + // Call this function after EndNodeEditor()! + assert(g.current_scope == Scope_None); + assert(started_at_id != NULL); + + const bool is_started = (g.element_state_change & ElementStateChange_LinkStarted) != 0; + if (is_started) + { + const EditorContext& editor = editor_context_get(); + const int pin_idx = editor.click_interaction_state.link_creation.start_pin_idx; + *started_at_id = editor.pins.pool[pin_idx].id; + } + + return is_started; +} + +bool IsLinkDropped(int* const started_at_id, const bool including_detached_links) +{ + // Call this function after EndNodeEditor()! + assert(g.current_scope == Scope_None); + + const EditorContext& editor = editor_context_get(); + + const bool link_dropped = (g.element_state_change & ElementStateChange_LinkDropped) != 0 && + (including_detached_links || + editor.click_interaction_state.link_creation.link_creation_type != + LinkCreationType_FromDetach); + + if (link_dropped && started_at_id) + { + const int pin_idx = editor.click_interaction_state.link_creation.start_pin_idx; + *started_at_id = editor.pins.pool[pin_idx].id; + } + + return link_dropped; +} + +bool IsLinkCreated( + int* const started_at_pin_id, + int* const ended_at_pin_id, + bool* const created_from_snap) +{ + assert(g.current_scope == Scope_None); + assert(started_at_pin_id != NULL); + assert(ended_at_pin_id != NULL); + + const bool is_created = (g.element_state_change & ElementStateChange_LinkCreated) != 0; + + if (is_created) + { + const EditorContext& editor = editor_context_get(); + const int start_idx = editor.click_interaction_state.link_creation.start_pin_idx; + const int end_idx = editor.click_interaction_state.link_creation.end_pin_idx.value(); + const PinData& start_pin = editor.pins.pool[start_idx]; + const PinData& end_pin = editor.pins.pool[end_idx]; + + if (start_pin.type == AttributeType_Output) + { + *started_at_pin_id = start_pin.id; + *ended_at_pin_id = end_pin.id; + } + else + { + *started_at_pin_id = end_pin.id; + *ended_at_pin_id = start_pin.id; + } + + if (created_from_snap) + { + *created_from_snap = editor.click_interaction_type == ClickInteractionType_LinkCreation; + } + } + + return is_created; +} + +bool IsLinkCreated( + int* started_at_node_id, + int* started_at_pin_id, + int* ended_at_node_id, + int* ended_at_pin_id, + bool* created_from_snap) +{ + assert(g.current_scope == Scope_None); + assert(started_at_node_id != NULL); + assert(started_at_pin_id != NULL); + assert(ended_at_node_id != NULL); + assert(ended_at_pin_id != NULL); + + const bool is_created = (g.element_state_change & ElementStateChange_LinkCreated) != 0; + + if (is_created) + { + const EditorContext& editor = editor_context_get(); + const int start_idx = editor.click_interaction_state.link_creation.start_pin_idx; + const int end_idx = editor.click_interaction_state.link_creation.end_pin_idx.value(); + const PinData& start_pin = editor.pins.pool[start_idx]; + const NodeData& start_node = editor.nodes.pool[start_pin.parent_node_idx]; + const PinData& end_pin = editor.pins.pool[end_idx]; + const NodeData& end_node = editor.nodes.pool[end_pin.parent_node_idx]; + + if (start_pin.type == AttributeType_Output) + { + *started_at_pin_id = start_pin.id; + *started_at_node_id = start_node.id; + *ended_at_pin_id = end_pin.id; + *ended_at_node_id = end_node.id; + } + else + { + *started_at_pin_id = end_pin.id; + *started_at_node_id = end_node.id; + *ended_at_pin_id = start_pin.id; + *ended_at_node_id = start_node.id; + } + + if (created_from_snap) + { + *created_from_snap = editor.click_interaction_type == ClickInteractionType_LinkCreation; + } + } + + return is_created; +} + +bool IsLinkDestroyed(int* const link_id) +{ + assert(g.current_scope == Scope_None); + + const bool link_destroyed = g.deleted_link_idx.has_value(); + if (link_destroyed) + { + const EditorContext& editor = editor_context_get(); + const int link_idx = g.deleted_link_idx.value(); + *link_id = editor.links.pool[link_idx].id; + } + + return link_destroyed; +} + +namespace +{ +void node_line_handler(EditorContext& editor, const char* line) +{ + int id; + int x, y; + if (sscanf(line, "[node.%i", &id) == 1) + { + const int node_idx = object_pool_find_or_create_index(editor.nodes, id); + g.current_node_idx = node_idx; + NodeData& node = editor.nodes.pool[node_idx]; + node.id = id; + } + else if (sscanf(line, "origin=%i,%i", &x, &y) == 2) + { + NodeData& node = editor.nodes.pool[g.current_node_idx]; + node.origin = ImVec2((float)x, (float)y); + } +} + +void editor_line_handler(EditorContext& editor, const char* line) +{ + sscanf(line, "panning=%f,%f", &editor.panning.x, &editor.panning.y); +} +} // namespace + +const char* SaveCurrentEditorStateToIniString(size_t* const data_size) +{ + return SaveEditorStateToIniString(&editor_context_get(), data_size); +} + +const char* SaveEditorStateToIniString( + const EditorContext* const editor_ptr, + size_t* const data_size) +{ + assert(editor_ptr != NULL); + const EditorContext& editor = *editor_ptr; + + g.text_buffer.clear(); + // TODO: check to make sure that the estimate is the upper bound of element + g.text_buffer.reserve(64 * editor.nodes.pool.size()); + + g.text_buffer.appendf( + "[editor]\npanning=%i,%i\n", (int)editor.panning.x, (int)editor.panning.y); + + for (int i = 0; i < editor.nodes.pool.size(); i++) + { + if (editor.nodes.in_use[i]) + { + const NodeData& node = editor.nodes.pool[i]; + g.text_buffer.appendf("\n[node.%d]\n", node.id); + g.text_buffer.appendf("origin=%i,%i\n", (int)node.origin.x, (int)node.origin.y); + } + } + + if (data_size != NULL) + { + *data_size = g.text_buffer.size(); + } + + return g.text_buffer.c_str(); +} + +void LoadCurrentEditorStateFromIniString(const char* const data, const size_t data_size) +{ + LoadEditorStateFromIniString(&editor_context_get(), data, data_size); +} + +void LoadEditorStateFromIniString( + EditorContext* const editor_ptr, + const char* const data, + const size_t data_size) +{ + if (data_size == 0u) + { + return; + } + + EditorContext& editor = editor_ptr == NULL ? editor_context_get() : *editor_ptr; + + char* buf = (char*)ImGui::MemAlloc(data_size + 1); + const char* buf_end = buf + data_size; + memcpy(buf, data, data_size); + buf[data_size] = 0; + + void (*line_handler)(EditorContext&, const char*); + line_handler = NULL; + char* line_end = NULL; + for (char* line = buf; line < buf_end; line = line_end + 1) + { + while (*line == '\n' || *line == '\r') + { + line++; + } + line_end = line; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + { + line_end++; + } + line_end[0] = 0; + + if (*line == ';' || *line == '\0') + { + continue; + } + + if (line[0] == '[' && line_end[-1] == ']') + { + line_end[-1] = 0; + if (strncmp(line + 1, "node", 4) == 0) + { + line_handler = node_line_handler; + } + else if (strcmp(line + 1, "editor") == 0) + { + line_handler = editor_line_handler; + } + } + + if (line_handler != NULL) + { + line_handler(editor, line); + } + } + ImGui::MemFree(buf); +} + +void SaveCurrentEditorStateToIniFile(const char* const file_name) +{ + SaveEditorStateToIniFile(&editor_context_get(), file_name); +} + +void SaveEditorStateToIniFile(const EditorContext* const editor, const char* const file_name) +{ + size_t data_size = 0u; + const char* data = SaveEditorStateToIniString(editor, &data_size); + FILE* file = ImFileOpen(file_name, "wt"); + if (!file) + { + return; + } + + fwrite(data, sizeof(char), data_size, file); + fclose(file); +} + +void LoadCurrentEditorStateFromIniFile(const char* const file_name) +{ + LoadEditorStateFromIniFile(&editor_context_get(), file_name); +} + +void LoadEditorStateFromIniFile(EditorContext* const editor, const char* const file_name) +{ + size_t data_size = 0u; + char* file_data = (char*)ImFileLoadToMemory(file_name, "rb", &data_size); + + if (!file_data) + { + return; + } + + LoadEditorStateFromIniString(editor, file_data, data_size); + ImGui::MemFree(file_data); +} +} // namespace imnodes diff --git a/DearPyGui/vendor/imnodes/imnodes.h b/DearPyGui/vendor/imnodes/imnodes.h new file mode 100644 index 000000000..80febad1e --- /dev/null +++ b/DearPyGui/vendor/imnodes/imnodes.h @@ -0,0 +1,323 @@ +#pragma once + +#include + +struct ImVec2; + +namespace imnodes +{ +enum ColorStyle +{ + ColorStyle_NodeBackground = 0, + ColorStyle_NodeBackgroundHovered, + ColorStyle_NodeBackgroundSelected, + ColorStyle_NodeOutline, + ColorStyle_TitleBar, + ColorStyle_TitleBarHovered, + ColorStyle_TitleBarSelected, + ColorStyle_Link, + ColorStyle_LinkHovered, + ColorStyle_LinkSelected, + ColorStyle_Pin, + ColorStyle_PinHovered, + ColorStyle_BoxSelector, + ColorStyle_BoxSelectorOutline, + ColorStyle_GridBackground, + ColorStyle_GridLine, + ColorStyle_Count +}; + +enum StyleVar +{ + StyleVar_GridSpacing = 0, + StyleVar_NodeCornerRounding, + StyleVar_NodePaddingHorizontal, + StyleVar_NodePaddingVertical, + StyleVar_NodeBorderThickness, + StyleVar_LinkThickness, + StyleVar_LinkLineSegmentsPerLength, + StyleVar_LinkHoverDistance, + StyleVar_PinCircleRadius, + StyleVar_PinQuadSideLength, + StyleVar_PinTriangleSideLength, + StyleVar_PinLineThickness, + StyleVar_PinHoverRadius, + StyleVar_PinOffset +}; + +enum StyleFlags +{ + StyleFlags_None = 0, + StyleFlags_NodeOutline = 1 << 0, + StyleFlags_GridLines = 1 << 2 +}; + +// This enum controls the way attribute pins look. +enum PinShape +{ + PinShape_Circle, + PinShape_CircleFilled, + PinShape_Triangle, + PinShape_TriangleFilled, + PinShape_Quad, + PinShape_QuadFilled +}; + +// This enum controls the way the attribute pins behave. +enum AttributeFlags +{ + AttributeFlags_None = 0, + // Allow detaching a link by left-clicking and dragging the link at a pin it is connected to. + // NOTE: the user has to actually delete the link for this to work. A deleted link can be + // detected by calling IsLinkDestroyed() after EndNodeEditor(). + AttributeFlags_EnableLinkDetachWithDragClick = 1 << 0, + // Visual snapping of an in progress link will trigger IsLink Created/Destroyed events. Allows + // for previewing the creation of a link while dragging it across attributes. See here for demo: + // https://github.com/Nelarius/imnodes/issues/41#issuecomment-647132113 NOTE: the user has to + // actually delete the link for this to work. A deleted link can be detected by calling + // IsLinkDestroyed() after EndNodeEditor(). + AttributeFlags_EnableLinkCreationOnSnap = 1 << 1 +}; + +struct IO +{ + struct EmulateThreeButtonMouse + { + EmulateThreeButtonMouse(); + + // Controls whether this feature is enabled or not. + bool enabled; + const bool* modifier; // The keyboard modifier to use with the mouse left click. Set to + // &ImGuiIO::KeyAlt by default. + } emulate_three_button_mouse; + + struct LinkDetachWithModifierClick + { + LinkDetachWithModifierClick(); + + // Pointer to a boolean value indicating when the desired modifier is pressed. Set to NULL + // by default (i.e. this feature is disabled). To enable the feature, set the link to point + // to, for example, &ImGuiIO::KeyCtrl. + // + // Left-clicking a link with this modifier pressed will detach that link. NOTE: the user has + // to actually delete the link for this to work. A deleted link can be detected by calling + // IsLinkDestroyed() after EndNodeEditor(). + const bool* modifier; + } link_detach_with_modifier_click; + + IO(); +}; + +struct Style +{ + float grid_spacing; + + float node_corner_rounding; + float node_padding_horizontal; + float node_padding_vertical; + float node_border_thickness; + + float link_thickness; + float link_line_segments_per_length; + float link_hover_distance; + + // The following variables control the look and behavior of the pins. The default size of each + // pin shape is balanced to occupy approximately the same surface area on the screen. + + // The circle radius used when the pin shape is either PinShape_Circle or PinShape_CircleFilled. + float pin_circle_radius; + // The quad side length used when the shape is either PinShape_Quad or PinShape_QuadFilled. + float pin_quad_side_length; + // The equilateral triangle side length used when the pin shape is either PinShape_Triangle or + // PinShape_TriangleFilled. + float pin_triangle_side_length; + // The thickness of the line used when the pin shape is not filled. + float pin_line_thickness; + // The radius from the pin's center position inside of which it is detected as being hovered + // over. + float pin_hover_radius; + // Offsets the pins' positions from the edge of the node to the outside of the node. + float pin_offset; + + // By default, StyleFlags_NodeOutline and StyleFlags_Gridlines are enabled. + StyleFlags flags; + // Set these mid-frame using Push/PopColorStyle. You can index this color array with with a + // ColorStyle enum value. + unsigned int colors[ColorStyle_Count]; + + Style(); +}; + +// An editor context corresponds to a set of nodes in a single workspace (created with a single +// Begin/EndNodeEditor pair) +// +// By default, the library creates an editor context behind the scenes, so using any of the imnodes +// functions doesn't require you to explicitly create a context. +struct EditorContext; + +EditorContext* EditorContextCreate(); +void EditorContextFree(EditorContext*); +void EditorContextSet(EditorContext*); +ImVec2 EditorContextGetPanning(); +void EditorContextResetPanning(const ImVec2& pos); +void EditorContextMoveToNode(const int node_id); + +// Initialize the node editor system. +void Initialize(); +void Shutdown(); + +IO& GetIO(); + +// Returns the global style struct. See the struct declaration for default values. +Style& GetStyle(); +// Style presets matching the dear imgui styles of the same name. +void StyleColorsDark(); // on by default +void StyleColorsClassic(); +void StyleColorsLight(); + +// The top-level function call. Call this before calling BeginNode/EndNode. Calling this function +// will result the node editor grid workspace being rendered. +void BeginNodeEditor(); +void EndNodeEditor(); + +// Use PushColorStyle and PopColorStyle to modify Style::colors mid-frame. +void PushColorStyle(ColorStyle item, unsigned int color); +void PopColorStyle(); +void PushStyleVar(StyleVar style_item, float value); +void PopStyleVar(); + +// id can be any positive or negative integer, but INT_MIN is currently reserved for internal use. +void BeginNode(int id); +void EndNode(); + +ImVec2 GetNodeDimensions(int id); + +// Place your node title bar content (such as the node title, using ImGui::Text) between the +// following function calls. These functions have to be called before adding any attributes, or the +// layout of the node will be incorrect. +void BeginNodeTitleBar(); +void EndNodeTitleBar(); + +// Attributes are ImGui UI elements embedded within the node. Attributes can have pin shapes +// rendered next to them. Links are created between pins. +// +// The activity status of an attribute can be checked via the IsAttributeActive() and +// IsAnyAttributeActive() function calls. This is one easy way of checking for any changes made to +// an attribute's drag float UI, for instance. +// +// Each attribute id must be unique. + +// Create an input attribute block. The pin is rendered on left side. +void BeginInputAttribute(int id, PinShape shape = PinShape_CircleFilled); +void EndInputAttribute(); +// Create an output attribute block. The pin is rendered on the right side. +void BeginOutputAttribute(int id, PinShape shape = PinShape_CircleFilled); +void EndOutputAttribute(); +// Create a static attribute block. A static attribute has no pin, and therefore can't be linked to +// anything. However, you can still use IsAttributeActive() and IsAnyAttributeActive() to check for +// attribute activity. +void BeginStaticAttribute(int id); +void EndStaticAttribute(); + +// Push a single AttributeFlags value. By default, only AttributeFlags_None is set. +void PushAttributeFlag(AttributeFlags flag); +void PopAttributeFlag(); + +// Render a link between attributes. +// The attributes ids used here must match the ids used in Begin(Input|Output)Attribute function +// calls. The order of start_attr and end_attr doesn't make a difference for rendering the link. +void Link(int id, int start_attribute_id, int end_attribute_id); + +// Enable or disable the ability to click and drag a specific node. +void SetNodeDraggable(int node_id, const bool draggable); + +// The node's position can be expressed in three coordinate systems: +// * screen space coordinates, -- the origin is the upper left corner of the window. +// * editor space coordinates -- the origin is the upper left corner of the node editor window +// * grid space coordinates, -- the origin is the upper left corner of the node editor window, +// translated by the current editor panning vector (see EditorContextGetPanning() and +// EditorContextResetPanning()) + +// Use the following functions to get and set the node's coordinates in these coordinate systems. + +void SetNodeScreenSpacePos(int node_id, const ImVec2& screen_space_pos); +void SetNodeEditorSpacePos(int node_id, const ImVec2& editor_space_pos); +void SetNodeGridSpacePos(int node_id, const ImVec2& grid_pos); + +ImVec2 GetNodeScreenSpacePos(const int node_id); +ImVec2 GetNodeEditorSpacePos(const int node_id); +ImVec2 GetNodeGridSpacePos(const int node_id); + +// Returns true if the current node editor canvas is being hovered over by the mouse, and is not +// blocked by any other windows. +bool IsEditorHovered(); +// The following functions return true if a UI element is being hovered over by the mouse cursor. +// Assigns the id of the UI element being hovered over to the function argument. Use these functions +// after EndNodeEditor() has been called. +bool IsNodeHovered(int* node_id); +bool IsLinkHovered(int* link_id); +bool IsPinHovered(int* attribute_id); + +// Use The following two functions to query the number of selected nodes or links in the current +// editor. Use after calling EndNodeEditor(). +int NumSelectedNodes(); +int NumSelectedLinks(); +// Get the selected node/link ids. The pointer argument should point to an integer array with at +// least as many elements as the respective NumSelectedNodes/NumSelectedLinks function call +// returned. +void GetSelectedNodes(int* node_ids); +void GetSelectedLinks(int* link_ids); + +// Clears the list of selected nodes/links. Useful if you want to delete a selected node or link. +void ClearNodeSelection(); +void ClearLinkSelection(); + +// Was the previous attribute active? This will continuously return true while the left mouse button +// is being pressed over the UI content of the attribute. +bool IsAttributeActive(); +// Was any attribute active? If so, sets the active attribute id to the output function argument. +bool IsAnyAttributeActive(int* attribute_id = NULL); + +// Use the following functions to query a change of state for an existing link, or new link. Call +// these after EndNodeEditor(). + +// Did the user start dragging a new link from a pin? +bool IsLinkStarted(int* started_at_attribute_id); +// Did the user drop the dragged link before attaching it to a pin? +// There are two different kinds of situations to consider when handling this event: +// 1) a link which is created at a pin and then dropped +// 2) an existing link which is detached from a pin and then dropped +// Use the including_detached_links flag to control whether this function triggers when the user +// detaches a link and drops it. +bool IsLinkDropped(int* started_at_attribute_id = NULL, bool including_detached_links = true); +// Did the user finish creating a new link? +bool IsLinkCreated( + int* started_at_attribute_id, + int* ended_at_attribute_id, + bool* created_from_snap = NULL); +bool IsLinkCreated( + int* started_at_node_id, + int* started_at_attribute_id, + int* ended_at_node_id, + int* ended_at_attribute_id, + bool* created_from_snap = NULL); + +// Was an existing link detached from a pin by the user? The detached link's id is assigned to the +// output argument link_id. +bool IsLinkDestroyed(int* link_id); + +// Use the following functions to write the editor context's state to a string, or directly to a +// file. The editor context is serialized in the INI file format. + +const char* SaveCurrentEditorStateToIniString(size_t* data_size = NULL); +const char* SaveEditorStateToIniString(const EditorContext* editor, size_t* data_size = NULL); + +void LoadCurrentEditorStateFromIniString(const char* data, size_t data_size); +void LoadEditorStateFromIniString(EditorContext* editor, const char* data, size_t data_size); + +void SaveCurrentEditorStateToIniFile(const char* file_name); +void SaveEditorStateToIniFile(const EditorContext* editor, const char* file_name); + +void LoadCurrentEditorStateFromIniFile(const char* file_name); +void LoadEditorStateFromIniFile(EditorContext* editor, const char* file_name); +} // namespace imnodes diff --git a/thirdparty/DearPyGui_Ext/LICENSE b/DearPyGui/vendor/implot/LICENSE similarity index 97% rename from thirdparty/DearPyGui_Ext/LICENSE rename to DearPyGui/vendor/implot/LICENSE index 7551d8d07..3995ef7c5 100644 --- a/thirdparty/DearPyGui_Ext/LICENSE +++ b/DearPyGui/vendor/implot/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 Raylock, LLC +Copyright (c) 2020 Evan Pezent Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/DearPyGui/vendor/implot/implot.cpp b/DearPyGui/vendor/implot/implot.cpp new file mode 100644 index 000000000..7abfe228f --- /dev/null +++ b/DearPyGui/vendor/implot/implot.cpp @@ -0,0 +1,4469 @@ +// MIT License + +// Copyright (c) 2021 Evan Pezent + +// 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. + +// ImPlot v0.9 WIP + +/* + +API BREAKING CHANGES +==================== +Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. +Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. +When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all implot files. +You can read releases logs https://github.com/epezent/implot/releases for more details. + +- 2021/03/08 (0.9) - SetColormap and PushColormap(ImVec4*) were removed. Use AddColormap for custom colormap support. LerpColormap was changed to SampleColormap. + ShowColormapScale was changed to ColormapScale and requires additional arguments. +- 2021/03/07 (0.9) - The signature of ShowColormapScale was modified to accept a ImVec2 size. +- 2021/02/28 (0.9) - BeginLegendDragDropSource was changed to BeginDragDropSourceItem with a number of other drag and drop improvements. +- 2021/01/18 (0.9) - The default behavior for opening context menus was change from double right-click to single right-click. ImPlotInputMap and related functions were moved + to implot_internal.h due to its immaturity. +- 2020/10/16 (0.8) - ImPlotStyleVar_InfoPadding was changed to ImPlotStyleVar_MousePosPadding +- 2020/09/10 (0.8) - The single array versions of PlotLine, PlotScatter, PlotStems, and PlotShaded were given additional arguments for x-scale and x0. +- 2020/09/07 (0.8) - Plotting functions which accept a custom getter function pointer have been post-fixed with a G (e.g. PlotLineG) +- 2020/09/06 (0.7) - Several flags under ImPlotFlags and ImPlotAxisFlags were inverted (e.g. ImPlotFlags_Legend -> ImPlotFlags_NoLegend) so that the default flagset + is simply 0. This more closely matches ImGui's style and makes it easier to enable non-default but commonly used flags (e.g. ImPlotAxisFlags_Time). +- 2020/08/28 (0.5) - ImPlotMarker_ can no longer be combined with bitwise OR, |. This features caused unecessary slow-down, and almost no one used it. +- 2020/08/25 (0.5) - ImPlotAxisFlags_Scientific was removed. Logarithmic axes automatically uses scientific notation. +- 2020/08/17 (0.5) - PlotText was changed so that text is centered horizontally and vertically about the desired point. +- 2020/08/16 (0.5) - An ImPlotContext must be explicitly created and destroyed now with `CreateContext` and `DestroyContext`. Previously, the context was statically initialized in this source file. +- 2020/06/13 (0.4) - The flags `ImPlotAxisFlag_Adaptive` and `ImPlotFlags_Cull` were removed. Both are now done internally by default. +- 2020/06/03 (0.3) - The signature and behavior of PlotPieChart was changed so that data with sum less than 1 can optionally be normalized. The label format can now be specified as well. +- 2020/06/01 (0.3) - SetPalette was changed to `SetColormap` for consistency with other plotting libraries. `RestorePalette` was removed. Use `SetColormap(ImPlotColormap_Default)`. +- 2020/05/31 (0.3) - Plot functions taking custom ImVec2* getters were removed. Use the ImPlotPoint* getter versions instead. +- 2020/05/29 (0.3) - The signature of ImPlotLimits::Contains was changed to take two doubles instead of ImVec2 +- 2020/05/16 (0.2) - All plotting functions were reverted to being prefixed with "Plot" to maintain a consistent VerbNoun style. `Plot` was split into `PlotLine` + and `PlotScatter` (however, `PlotLine` can still be used to plot scatter points as `Plot` did before.). `Bar` is not `PlotBars`, to indicate + that multiple bars will be plotted. +- 2020/05/13 (0.2) - `ImMarker` was change to `ImPlotMarker` and `ImAxisFlags` was changed to `ImPlotAxisFlags`. +- 2020/05/11 (0.2) - `ImPlotFlags_Selection` was changed to `ImPlotFlags_BoxSelect` +- 2020/05/11 (0.2) - The namespace ImGui:: was replaced with ImPlot::. As a result, the following additional changes were made: + - Functions that were prefixed or decorated with the word "Plot" have been truncated. E.g., `ImGui::PlotBars` is now just `ImPlot::Bar`. + It should be fairly obvious what was what. + - Some functions have been given names that would have otherwise collided with the ImGui namespace. This has been done to maintain a consistent + style with ImGui. E.g., 'ImGui::PushPlotStyleVar` is now 'ImPlot::PushStyleVar'. +- 2020/05/10 (0.2) - The following function/struct names were changes: + - ImPlotRange -> ImPlotLimits + - GetPlotRange() -> GetPlotLimits() + - SetNextPlotRange -> SetNextPlotLimits + - SetNextPlotRangeX -> SetNextPlotLimitsX + - SetNextPlotRangeY -> SetNextPlotLimitsY +- 2020/05/10 (0.2) - Plot queries are pixel based by default. Query rects that maintain relative plot position have been removed. This was done to support multi-y-axis. + +*/ + +#include "implot.h" +#include "implot_internal.h" + +#ifdef _MSC_VER +#define sprintf sprintf_s +#endif + +// Support for pre-1.82 version. Users on 1.82+ can use 0 (default) flags to mean "all corners" but in order to support older versions we are more explicit. +#if (IMGUI_VERSION_NUM < 18102) && !defined(ImDrawFlags_RoundCornersAll) +#define ImDrawFlags_RoundCornersAll ImDrawCornerFlags_All +#endif + +// Global plot context +ImPlotContext* GImPlot = NULL; + +//----------------------------------------------------------------------------- +// Struct Implementations +//----------------------------------------------------------------------------- + +ImPlotInputMap::ImPlotInputMap() { + PanButton = ImGuiMouseButton_Left; + PanMod = ImGuiKeyModFlags_None; + FitButton = ImGuiMouseButton_Left; + ContextMenuButton = ImGuiMouseButton_Right; + BoxSelectButton = ImGuiMouseButton_Right; + BoxSelectMod = ImGuiKeyModFlags_None; + BoxSelectCancelButton = ImGuiMouseButton_Left; + QueryButton = ImGuiMouseButton_Middle; + QueryMod = ImGuiKeyModFlags_None; + QueryToggleMod = ImGuiKeyModFlags_Ctrl; + HorizontalMod = ImGuiKeyModFlags_Alt; + VerticalMod = ImGuiKeyModFlags_Shift; +} + +ImPlotStyle::ImPlotStyle() { + + LineWeight = 1; + Marker = ImPlotMarker_None; + MarkerSize = 4; + MarkerWeight = 1; + FillAlpha = 1; + ErrorBarSize = 5; + ErrorBarWeight = 1.5f; + DigitalBitHeight = 8; + DigitalBitGap = 4; + + PlotBorderSize = 1; + MinorAlpha = 0.25f; + MajorTickLen = ImVec2(10,10); + MinorTickLen = ImVec2(5,5); + MajorTickSize = ImVec2(1,1); + MinorTickSize = ImVec2(1,1); + MajorGridSize = ImVec2(1,1); + MinorGridSize = ImVec2(1,1); + PlotPadding = ImVec2(10,10); + LabelPadding = ImVec2(5,5); + LegendPadding = ImVec2(10,10); + LegendInnerPadding = ImVec2(5,5); + LegendSpacing = ImVec2(5,0); + MousePosPadding = ImVec2(10,10); + AnnotationPadding = ImVec2(2,2); + FitPadding = ImVec2(0,0); + PlotDefaultSize = ImVec2(400,300); + PlotMinSize = ImVec2(300,225); + + ImPlot::StyleColorsAuto(this); + + Colormap = ImPlotColormap_Deep; + + AntiAliasedLines = false; + UseLocalTime = false; + Use24HourClock = false; + UseISO8601 = false; +} + +ImPlotItem* ImPlotPlot::GetLegendItem(int i) { + IM_ASSERT(Items.GetSize() > 0); + return Items.GetByIndex(LegendData.Indices[i]); +} + +const char* ImPlotPlot::GetLegendLabel(int i) { + ImPlotItem* item = GetLegendItem(i); + IM_ASSERT(item != NULL); + IM_ASSERT(item->NameOffset != -1 && item->NameOffset < LegendData.Labels.Buf.Size); + return LegendData.Labels.Buf.Data + item->NameOffset; +} + +//----------------------------------------------------------------------------- +// Style +//----------------------------------------------------------------------------- + +namespace ImPlot { + +const char* GetStyleColorName(ImPlotCol col) { + static const char* col_names[] = { + "Line", + "Fill", + "MarkerOutline", + "MarkerFill", + "ErrorBar", + "FrameBg", + "PlotBg", + "PlotBorder", + "LegendBg", + "LegendBorder", + "LegendText", + "TitleText", + "InlayText", + "XAxis", + "XAxisGrid", + "YAxis", + "YAxisGrid", + "YAxis2", + "YAxisGrid2", + "YAxis3", + "YAxisGrid3", + "Selection", + "Query", + "Crosshairs" + }; + return col_names[col]; +} + +const char* GetMarkerName(ImPlotMarker marker) { + switch (marker) { + case ImPlotMarker_None: return "None"; + case ImPlotMarker_Circle: return "Circle"; + case ImPlotMarker_Square: return "Square"; + case ImPlotMarker_Diamond: return "Diamond"; + case ImPlotMarker_Up: return "Up"; + case ImPlotMarker_Down: return "Down"; + case ImPlotMarker_Left: return "Left"; + case ImPlotMarker_Right: return "Right"; + case ImPlotMarker_Cross: return "Cross"; + case ImPlotMarker_Plus: return "Plus"; + case ImPlotMarker_Asterisk: return "Asterisk"; + default: return ""; + } +} + +ImVec4 GetAutoColor(ImPlotCol idx) { + ImVec4 col(0,0,0,1); + switch(idx) { + case ImPlotCol_Line: return col; // these are plot dependent! + case ImPlotCol_Fill: return col; // these are plot dependent! + case ImPlotCol_MarkerOutline: return col; // these are plot dependent! + case ImPlotCol_MarkerFill: return col; // these are plot dependent! + case ImPlotCol_ErrorBar: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_FrameBg: return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg); + case ImPlotCol_PlotBg: return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg); + case ImPlotCol_PlotBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border); + case ImPlotCol_LegendBg: return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg); + case ImPlotCol_LegendBorder: return GetStyleColorVec4(ImPlotCol_PlotBorder); + case ImPlotCol_LegendText: return GetStyleColorVec4(ImPlotCol_InlayText); + case ImPlotCol_TitleText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_InlayText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_XAxis: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_XAxisGrid: return GetStyleColorVec4(ImPlotCol_XAxis) * ImVec4(1,1,1,0.25f); + case ImPlotCol_YAxis: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_YAxisGrid: return GetStyleColorVec4(ImPlotCol_YAxis) * ImVec4(1,1,1,0.25f); + case ImPlotCol_YAxis2: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_YAxisGrid2: return GetStyleColorVec4(ImPlotCol_YAxis2) * ImVec4(1,1,1,0.25f); + case ImPlotCol_YAxis3: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlotCol_YAxisGrid3: return GetStyleColorVec4(ImPlotCol_YAxis3) * ImVec4(1,1,1,0.25f); + case ImPlotCol_Selection: return ImVec4(1,1,0,1); + case ImPlotCol_Query: return ImVec4(0,1,0,1); + case ImPlotCol_Crosshairs: return GetStyleColorVec4(ImPlotCol_PlotBorder); + default: return col; + } +} + +struct ImPlotStyleVarInfo { + ImGuiDataType Type; + ImU32 Count; + ImU32 Offset; + void* GetVarPtr(ImPlotStyle* style) const { return (void*)((unsigned char*)style + Offset); } +}; + +static const ImPlotStyleVarInfo GPlotStyleVarInfo[] = +{ + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, LineWeight) }, // ImPlotStyleVar_LineWeight + { ImGuiDataType_S32, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, Marker) }, // ImPlotStyleVar_Marker + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerSize) }, // ImPlotStyleVar_MarkerSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerWeight) }, // ImPlotStyleVar_MarkerWeight + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, FillAlpha) }, // ImPlotStyleVar_FillAlpha + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarSize) }, // ImPlotStyleVar_ErrorBarSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarWeight) }, // ImPlotStyleVar_ErrorBarWeight + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitHeight) }, // ImPlotStyleVar_DigitalBitHeight + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitGap) }, // ImPlotStyleVar_DigitalBitGap + + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotBorderSize) }, // ImPlotStyleVar_PlotBorderSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorAlpha) }, // ImPlotStyleVar_MinorAlpha + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickLen) }, // ImPlotStyleVar_MajorTickLen + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickLen) }, // ImPlotStyleVar_MinorTickLen + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickSize) }, // ImPlotStyleVar_MajorTickSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickSize) }, // ImPlotStyleVar_MinorTickSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorGridSize) }, // ImPlotStyleVar_MajorGridSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorGridSize) }, // ImPlotStyleVar_MinorGridSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotPadding) }, // ImPlotStyleVar_PlotPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LabelPadding) }, // ImPlotStyleVar_LabelPaddine + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendPadding) }, // ImPlotStyleVar_LegendPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendInnerPadding) }, // ImPlotStyleVar_LegendInnerPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendSpacing) }, // ImPlotStyleVar_LegendSpacing + + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MousePosPadding) }, // ImPlotStyleVar_MousePosPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, AnnotationPadding) }, // ImPlotStyleVar_AnnotationPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, FitPadding) }, // ImPlotStyleVar_FitPadding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotDefaultSize) }, // ImPlotStyleVar_PlotDefaultSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotMinSize) } // ImPlotStyleVar_PlotMinSize +}; + +static const ImPlotStyleVarInfo* GetPlotStyleVarInfo(ImPlotStyleVar idx) { + IM_ASSERT(idx >= 0 && idx < ImPlotStyleVar_COUNT); + IM_ASSERT(IM_ARRAYSIZE(GPlotStyleVarInfo) == ImPlotStyleVar_COUNT); + return &GPlotStyleVarInfo[idx]; +} + +//----------------------------------------------------------------------------- +// Generic Helpers +//----------------------------------------------------------------------------- + +void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char *text_begin, const char* text_end) { + // the code below is based loosely on ImFont::RenderText + if (!text_end) + text_end = text_begin + strlen(text_begin); + ImGuiContext& g = *GImGui; + ImFont* font = g.Font; + // Align to be pixel perfect + pos.x = IM_FLOOR(pos.x); + pos.y = IM_FLOOR(pos.y); + const float scale = g.FontSize / font->FontSize; + const char* s = text_begin; + int chars_exp = (int)(text_end - s); + int chars_rnd = 0; + const int vtx_count_max = chars_exp * 4; + const int idx_count_max = chars_exp * 6; + DrawList->PrimReserve(idx_count_max, vtx_count_max); + while (s < text_end) { + unsigned int c = (unsigned int)*s; + if (c < 0x80) { + s += 1; + } + else { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + const ImFontGlyph * glyph = font->FindGlyph((ImWchar)c); + if (glyph == NULL) { + continue; + } + DrawList->PrimQuadUV(pos + ImVec2(glyph->Y0, -glyph->X0) * scale, pos + ImVec2(glyph->Y0, -glyph->X1) * scale, + pos + ImVec2(glyph->Y1, -glyph->X1) * scale, pos + ImVec2(glyph->Y1, -glyph->X0) * scale, + ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V0), + ImVec2(glyph->U1, glyph->V1), ImVec2(glyph->U0, glyph->V1), + col); + pos.y -= glyph->AdvanceX * scale; + chars_rnd++; + } + // Give back unused vertices + int chars_skp = chars_exp-chars_rnd; + DrawList->PrimUnreserve(chars_skp*6, chars_skp*4); +} + +double NiceNum(double x, bool round) { + double f; /* fractional part of x */ + double nf; /* nice, rounded fraction */ + int expv = (int)floor(ImLog10(x)); + f = x / ImPow(10.0, (double)expv); /* between 1 and 10 */ + if (round) + if (f < 1.5) + nf = 1; + else if (f < 3) + nf = 2; + else if (f < 7) + nf = 5; + else + nf = 10; + else if (f <= 1) + nf = 1; + else if (f <= 2) + nf = 2; + else if (f <= 5) + nf = 5; + else + nf = 10; + return nf * ImPow(10.0, expv); +} + +//----------------------------------------------------------------------------- +// Context Utils +//----------------------------------------------------------------------------- + +void SetImGuiContext(ImGuiContext* ctx) { + ImGui::SetCurrentContext(ctx); +} + +ImPlotContext* CreateContext() { + ImPlotContext* ctx = IM_NEW(ImPlotContext)(); + Initialize(ctx); + if (GImPlot == NULL) + SetCurrentContext(ctx); + return ctx; +} + +void DestroyContext(ImPlotContext* ctx) { + if (ctx == NULL) + ctx = GImPlot; + if (GImPlot == ctx) + SetCurrentContext(NULL); + IM_DELETE(ctx); +} + +ImPlotContext* GetCurrentContext() { + return GImPlot; +} + +void SetCurrentContext(ImPlotContext* ctx) { + GImPlot = ctx; +} + +#define IMPLOT_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name)/sizeof(ImU32), qual) +#define IM_RGB(r,g,b) IM_COL32(r,g,b,255) + +void Initialize(ImPlotContext* ctx) { + Reset(ctx); + + const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396 }; + const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409 }; + const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986 }; + const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481}; + const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, 4286883874, 4285579076, 4283552122, 4280737725, 4280674301 }; + const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, 4284638433, 4283139314, 4281771772, 4280667900, 4280416752 }; + const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, 4278239231, 4278255615, 4283826175, 4289396735, 4294967295 }; + const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, 4294928025, 4294921651, 4294915020, 4294908646, 4294902015 }; + const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, 4288794330, 4289651940, 4291685869, 4293392118, 4294967295 }; + const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, 4283826090, 4278255615, 4278233855, 4278212095, 4278190335 }; + const ImU32 Twilight[] = {IM_RGB(226,217,226),IM_RGB(166,191,202),IM_RGB(109,144,192),IM_RGB(95,88,176),IM_RGB(83,30,124),IM_RGB(47,20,54),IM_RGB(100,25,75),IM_RGB(159,60,80),IM_RGB(192,117,94),IM_RGB(208,179,158),IM_RGB(226,217,226)}; + const ImU32 RdBu[] = {IM_RGB(103,0,31),IM_RGB(178,24,43),IM_RGB(214,96,77),IM_RGB(244,165,130),IM_RGB(253,219,199),IM_RGB(247,247,247),IM_RGB(209,229,240),IM_RGB(146,197,222),IM_RGB(67,147,195),IM_RGB(33,102,172),IM_RGB(5,48,97)}; + const ImU32 BrBG[] = {IM_RGB(84,48,5),IM_RGB(140,81,10),IM_RGB(191,129,45),IM_RGB(223,194,125),IM_RGB(246,232,195),IM_RGB(245,245,245),IM_RGB(199,234,229),IM_RGB(128,205,193),IM_RGB(53,151,143),IM_RGB(1,102,94),IM_RGB(0,60,48)}; + const ImU32 PiYG[] = {IM_RGB(142,1,82),IM_RGB(197,27,125),IM_RGB(222,119,174),IM_RGB(241,182,218),IM_RGB(253,224,239),IM_RGB(247,247,247),IM_RGB(230,245,208),IM_RGB(184,225,134),IM_RGB(127,188,65),IM_RGB(77,146,33),IM_RGB(39,100,25)}; + const ImU32 Spectral[] = {IM_RGB(158,1,66),IM_RGB(213,62,79),IM_RGB(244,109,67),IM_RGB(253,174,97),IM_RGB(254,224,139),IM_RGB(255,255,191),IM_RGB(230,245,152),IM_RGB(171,221,164),IM_RGB(102,194,165),IM_RGB(50,136,189),IM_RGB(94,79,162)}; + const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK }; + + IMPLOT_APPEND_CMAP(Deep, true); + IMPLOT_APPEND_CMAP(Dark, true); + IMPLOT_APPEND_CMAP(Pastel, true); + IMPLOT_APPEND_CMAP(Paired, true); + IMPLOT_APPEND_CMAP(Viridis, false); + IMPLOT_APPEND_CMAP(Plasma, false); + IMPLOT_APPEND_CMAP(Hot, false); + IMPLOT_APPEND_CMAP(Cool, false); + IMPLOT_APPEND_CMAP(Pink, false); + IMPLOT_APPEND_CMAP(Jet, false); + IMPLOT_APPEND_CMAP(Twilight, false); + IMPLOT_APPEND_CMAP(RdBu, false); + IMPLOT_APPEND_CMAP(BrBG, false); + IMPLOT_APPEND_CMAP(PiYG, false); + IMPLOT_APPEND_CMAP(Spectral, false); + IMPLOT_APPEND_CMAP(Greys, false); + +} + +void Reset(ImPlotContext* ctx) { + // end child window if it was made + if (ctx->ChildWindowMade) + ImGui::EndChild(); + ctx->ChildWindowMade = false; + // reset the next plot/item data + ctx->NextPlotData.Reset(); + ctx->NextItemData.Reset(); + // reset items count + ctx->VisibleItemCount = 0; + // reset ticks/labels + ctx->XTicks.Reset(); + for (int i = 0; i < 3; ++i) + ctx->YTicks[i].Reset(); + // reset labels + ctx->Annotations.Reset(); + // reset extents/fit + ctx->FitThisFrame = false; + ctx->FitX = false; + ctx->ExtentsX.Min = HUGE_VAL; + ctx->ExtentsX.Max = -HUGE_VAL; + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + ctx->ExtentsY[i].Min = HUGE_VAL; + ctx->ExtentsY[i].Max = -HUGE_VAL; + ctx->FitY[i] = false; + } + // reset digital plot items count + ctx->DigitalPlotItemCnt = 0; + ctx->DigitalPlotOffset = 0; + // nullify plot + ctx->CurrentPlot = NULL; + ctx->CurrentItem = NULL; + ctx->PreviousItem = NULL; +} + +//----------------------------------------------------------------------------- +// Plot Utils +//----------------------------------------------------------------------------- + +ImPlotPlot* GetPlot(const char* title) { + ImGuiWindow* Window = GImGui->CurrentWindow; + const ImGuiID ID = Window->GetID(title); + return GImPlot->Plots.GetByKey(ID); +} + +ImPlotPlot* GetCurrentPlot() { + return GImPlot->CurrentPlot; +} + +void BustPlotCache() { + GImPlot->Plots.Clear(); +} + +void FitPoint(const ImPlotPoint& p) { + FitPointX(p.x); + FitPointY(p.y); +} + +void FitPointX(double x) { + ImPlotContext& gp = *GImPlot; + ImPlotRange& ex_x = gp.ExtentsX; + const bool log_x = ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale); + if (!ImNanOrInf(x) && !(log_x && x <= 0)) { + ex_x.Min = x < ex_x.Min ? x : ex_x.Min; + ex_x.Max = x > ex_x.Max ? x : ex_x.Max; + } +} + +void FitPointY(double y) { + ImPlotContext& gp = *GImPlot; + const ImPlotYAxis y_axis = gp.CurrentPlot->CurrentYAxis; + ImPlotRange& ex_y = gp.ExtentsY[y_axis]; + const bool log_y = ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale); + if (!ImNanOrInf(y) && !(log_y && y <= 0)) { + ex_y.Min = y < ex_y.Min ? y : ex_y.Min; + ex_y.Max = y > ex_y.Max ? y : ex_y.Max; + } +} + +void PushLinkedAxis(ImPlotAxis& axis) { + if (axis.LinkedMin) { *axis.LinkedMin = axis.Range.Min; } + if (axis.LinkedMax) { *axis.LinkedMax = axis.Range.Max; } +} + +void PullLinkedAxis(ImPlotAxis& axis) { + if (axis.LinkedMin) { axis.SetMin(*axis.LinkedMin); } + if (axis.LinkedMax) { axis.SetMax(*axis.LinkedMax); } +} + +//----------------------------------------------------------------------------- +// Coordinate Utils +//----------------------------------------------------------------------------- + +void UpdateTransformCache() { + ImPlotContext& gp = *GImPlot; + // get pixels for transforms + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + gp.PixelRange[i] = ImRect(ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_Invert) ? gp.CurrentPlot->PlotRect.Max.x : gp.CurrentPlot->PlotRect.Min.x, + ImHasFlag(gp.CurrentPlot->YAxis[i].Flags, ImPlotAxisFlags_Invert) ? gp.CurrentPlot->PlotRect.Min.y : gp.CurrentPlot->PlotRect.Max.y, + ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_Invert) ? gp.CurrentPlot->PlotRect.Min.x : gp.CurrentPlot->PlotRect.Max.x, + ImHasFlag(gp.CurrentPlot->YAxis[i].Flags, ImPlotAxisFlags_Invert) ? gp.CurrentPlot->PlotRect.Max.y : gp.CurrentPlot->PlotRect.Min.y); + gp.My[i] = (gp.PixelRange[i].Max.y - gp.PixelRange[i].Min.y) / gp.CurrentPlot->YAxis[i].Range.Size(); + } + gp.LogDenX = ImLog10(gp.CurrentPlot->XAxis.Range.Max / gp.CurrentPlot->XAxis.Range.Min); + for (int i = 0; i < IMPLOT_Y_AXES; i++) + gp.LogDenY[i] = ImLog10(gp.CurrentPlot->YAxis[i].Range.Max / gp.CurrentPlot->YAxis[i].Range.Min); + gp.Mx = (gp.PixelRange[0].Max.x - gp.PixelRange[0].Min.x) / gp.CurrentPlot->XAxis.Range.Size(); +} + +ImPlotPoint PixelsToPlot(float x, float y, ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PixelsToPlot() needs to be called between BeginPlot() and EndPlot()!"); + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + ImPlotPoint plt; + plt.x = (x - gp.PixelRange[y_axis].Min.x) / gp.Mx + gp.CurrentPlot->XAxis.Range.Min; + plt.y = (y - gp.PixelRange[y_axis].Min.y) / gp.My[y_axis] + gp.CurrentPlot->YAxis[y_axis].Range.Min; + if (ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale)) { + double t = (plt.x - gp.CurrentPlot->XAxis.Range.Min) / gp.CurrentPlot->XAxis.Range.Size(); + plt.x = ImPow(10, t * gp.LogDenX) * gp.CurrentPlot->XAxis.Range.Min; + } + if (ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale)) { + double t = (plt.y - gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.CurrentPlot->YAxis[y_axis].Range.Size(); + plt.y = ImPow(10, t * gp.LogDenY[y_axis]) * gp.CurrentPlot->YAxis[y_axis].Range.Min; + } + return plt; +} + +ImPlotPoint PixelsToPlot(const ImVec2& pix, ImPlotYAxis y_axis) { + return PixelsToPlot(pix.x, pix.y, y_axis); +} + +// This function is convenient but should not be used to process a high volume of points. Use the Transformer structs below instead. +ImVec2 PlotToPixels(double x, double y, ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!"); + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + ImVec2 pix; + if (ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale)) { + double t = ImLog10(x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX; + x = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, (float)t); + } + if (ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale)) { + double t = ImLog10(y / gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.LogDenY[y_axis]; + y = ImLerp(gp.CurrentPlot->YAxis[y_axis].Range.Min, gp.CurrentPlot->YAxis[y_axis].Range.Max, (float)t); + } + pix.x = (float)(gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min)); + pix.y = (float)(gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min)); + return pix; +} + +// This function is convenient but should not be used to process a high volume of points. Use the Transformer structs below instead. +ImVec2 PlotToPixels(const ImPlotPoint& plt, ImPlotYAxis y_axis) { + return PlotToPixels(plt.x, plt.y, y_axis); +} + +//----------------------------------------------------------------------------- +// Legend Utils +//----------------------------------------------------------------------------- + +ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation loc, const ImVec2& pad) { + ImVec2 pos; + if (ImHasFlag(loc, ImPlotLocation_West) && !ImHasFlag(loc, ImPlotLocation_East)) + pos.x = outer_rect.Min.x + pad.x; + else if (!ImHasFlag(loc, ImPlotLocation_West) && ImHasFlag(loc, ImPlotLocation_East)) + pos.x = outer_rect.Max.x - pad.x - inner_size.x; + else + pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f; + // legend reference point y + if (ImHasFlag(loc, ImPlotLocation_North) && !ImHasFlag(loc, ImPlotLocation_South)) + pos.y = outer_rect.Min.y + pad.y; + else if (!ImHasFlag(loc, ImPlotLocation_North) && ImHasFlag(loc, ImPlotLocation_South)) + pos.y = outer_rect.Max.y - pad.y - inner_size.y; + else + pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f; + pos.x = IM_ROUND(pos.x); + pos.y = IM_ROUND(pos.y); + return pos; +} + +ImVec2 CalcLegendSize(ImPlotPlot& plot, const ImVec2& pad, const ImVec2& spacing, ImPlotOrientation orn) { + // vars + const int nItems = plot.GetLegendCount(); + const float txt_ht = ImGui::GetTextLineHeight(); + const float icon_size = txt_ht; + // get label max width + float max_label_width = 0; + float sum_label_width = 0; + for (int i = 0; i < nItems; ++i) { + const char* label = plot.GetLegendLabel(i); + const float label_width = ImGui::CalcTextSize(label, NULL, true).x; + max_label_width = label_width > max_label_width ? label_width : max_label_width; + sum_label_width += label_width; + } + // calc legend size + const ImVec2 legend_size = orn == ImPlotOrientation_Vertical ? + ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) : + ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht); + return legend_size; +} + +void ShowLegendEntries(ImPlotPlot& plot, const ImRect& legend_bb, bool interactable, const ImVec2& pad, const ImVec2& spacing, ImPlotOrientation orn, ImDrawList& DrawList) { + ImGuiIO& IO = ImGui::GetIO(); + // vars + const float txt_ht = ImGui::GetTextLineHeight(); + const float icon_size = txt_ht; + const float icon_shrink = 2; + ImU32 col_txt = GetStyleColorU32(ImPlotCol_LegendText); + ImU32 col_txt_dis = ImAlphaU32(col_txt, 0.25f); + // render each legend item + float sum_label_width = 0; + for (int i = 0; i < plot.GetLegendCount(); ++i) { + ImPlotItem* item = plot.GetLegendItem(i); + const char* label = plot.GetLegendLabel(i); + const float label_width = ImGui::CalcTextSize(label, NULL, true).x; + const ImVec2 top_left = orn == ImPlotOrientation_Vertical ? + legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) : + legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0); + sum_label_width += label_width; + ImRect icon_bb; + icon_bb.Min = top_left + ImVec2(icon_shrink,icon_shrink); + icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink); + ImRect label_bb; + label_bb.Min = top_left; + label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size); + ImU32 col_hl_txt; + ImU32 col_item = ImAlphaU32(item->Color,1); + if (interactable && (icon_bb.Contains(IO.MousePos) || label_bb.Contains(IO.MousePos))) { + item->LegendHovered = true; + col_hl_txt = ImMixU32(col_txt, col_item, 64); + } + else { + // item->LegendHovered = false; + col_hl_txt = ImGui::GetColorU32(col_txt); + } + ImU32 iconColor; + if (interactable && icon_bb.Contains(IO.MousePos)) { + ImU32 col_alpha = ImAlphaU32(col_item,0.5f); + iconColor = item->Show ? col_alpha : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f); + if (IO.MouseClicked[0]) + item->Show = !item->Show; + } + else { + iconColor = item->Show ? col_item : col_txt_dis; + } + DrawList.AddRectFilled(icon_bb.Min, icon_bb.Max, iconColor, 1); + const char* text_display_end = ImGui::FindRenderedTextEnd(label, NULL); + if (label != text_display_end) + DrawList.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_hl_txt : col_txt_dis, label, text_display_end); + } +} + +//----------------------------------------------------------------------------- +// Tick Utils +//----------------------------------------------------------------------------- + +void LabelTickDefault(ImPlotTick& tick, ImGuiTextBuffer& buffer) { + char temp[32]; + if (tick.ShowLabel) { + tick.TextOffset = buffer.size(); + snprintf(temp, 32, "%.10g", tick.PlotPos); + buffer.append(temp, temp + strlen(temp) + 1); + tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.TextOffset); + } +} + +void LabelTickScientific(ImPlotTick& tick, ImGuiTextBuffer& buffer) { + char temp[32]; + if (tick.ShowLabel) { + tick.TextOffset = buffer.size(); + snprintf(temp, 32, "%.0E", tick.PlotPos); + buffer.append(temp, temp + strlen(temp) + 1); + tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.TextOffset); + } +} + +void AddTicksDefault(const ImPlotRange& range, int nMajor, int nMinor, ImPlotTickCollection& ticks) { + const double nice_range = NiceNum(range.Size() * 0.99, false); + const double interval = NiceNum(nice_range / (nMajor - 1), true); + const double graphmin = floor(range.Min / interval) * interval; + const double graphmax = ceil(range.Max / interval) * interval; + for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) { + if (range.Contains(major)) + ticks.Append(major, true, true, LabelTickDefault); + for (int i = 1; i < nMinor; ++i) { + double minor = major + i * interval / nMinor; + if (range.Contains(minor)) + ticks.Append(minor, false, true, LabelTickDefault); + } + } +} + +void AddTicksLogarithmic(const ImPlotRange& range, int nMajor, ImPlotTickCollection& ticks) { + if (range.Min <= 0 || range.Max <= 0) + return; + double log_min = ImLog10(range.Min); + double log_max = ImLog10(range.Max); + int exp_step = ImMax(1,(int)(log_max - log_min) / nMajor); + int exp_min = (int)log_min; + int exp_max = (int)log_max; + if (exp_step != 1) { + while(exp_step % 3 != 0) exp_step++; // make step size multiple of three + while(exp_min % exp_step != 0) exp_min--; // decrease exp_min until exp_min + N * exp_step will be 0 + } + for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) { + double major1 = ImPow(10, (double)(e)); + double major2 = ImPow(10, (double)(e + 1)); + double interval = (major2 - major1) / 9; + if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON)) + ticks.Append(major1, true, true, LabelTickScientific); + for (int j = 0; j < exp_step; ++j) { + major1 = ImPow(10, (double)(e+j)); + major2 = ImPow(10, (double)(e+j+1)); + interval = (major2 - major1) / 9; + for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) { + double minor = major1 + i * interval; + if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON)) + ticks.Append(minor, false, false, LabelTickScientific); + + } + } + } +} + +void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlotTickCollection& ticks) { + for (int i = 0; i < n; ++i) { + ImPlotTick tick(values[i], false, true); + if (labels != NULL) { + tick.TextOffset = ticks.TextBuffer.size(); + ticks.TextBuffer.append(labels[i], labels[i] + strlen(labels[i]) + 1); + tick.LabelSize = ImGui::CalcTextSize(labels[i]); + } + else { + LabelTickDefault(tick, ticks.TextBuffer); + } + ticks.Append(tick); + } +} + +//----------------------------------------------------------------------------- +// Time Ticks and Utils +//----------------------------------------------------------------------------- + +// this may not be thread safe? +static const double TimeUnitSpans[ImPlotTimeUnit_COUNT] = { + 0.000001, + 0.001, + 1, + 60, + 3600, + 86400, + 2629800, + 31557600 +}; + +inline ImPlotTimeUnit GetUnitForRange(double range) { + static double cutoffs[ImPlotTimeUnit_COUNT] = {0.001, 1, 60, 3600, 86400, 2629800, 31557600, IMPLOT_MAX_TIME}; + for (int i = 0; i < ImPlotTimeUnit_COUNT; ++i) { + if (range <= cutoffs[i]) + return (ImPlotTimeUnit)i; + } + return ImPlotTimeUnit_Yr; +} + +inline int LowerBoundStep(int max_divs, const int* divs, const int* step, int size) { + if (max_divs < divs[0]) + return 0; + for (int i = 1; i < size; ++i) { + if (max_divs < divs[i]) + return step[i-1]; + } + return step[size-1]; +} + +inline int GetTimeStep(int max_divs, ImPlotTimeUnit unit) { + if (unit == ImPlotTimeUnit_Ms || unit == ImPlotTimeUnit_Us) { + static const int step[] = {500,250,200,100,50,25,20,10,5,2,1}; + static const int divs[] = {2,4,5,10,20,40,50,100,200,500,1000}; + return LowerBoundStep(max_divs, divs, step, 11); + } + if (unit == ImPlotTimeUnit_S || unit == ImPlotTimeUnit_Min) { + static const int step[] = {30,15,10,5,1}; + static const int divs[] = {2,4,6,12,60}; + return LowerBoundStep(max_divs, divs, step, 5); + } + else if (unit == ImPlotTimeUnit_Hr) { + static const int step[] = {12,6,3,2,1}; + static const int divs[] = {2,4,8,12,24}; + return LowerBoundStep(max_divs, divs, step, 5); + } + else if (unit == ImPlotTimeUnit_Day) { + static const int step[] = {14,7,2,1}; + static const int divs[] = {2,4,14,28}; + return LowerBoundStep(max_divs, divs, step, 4); + } + else if (unit == ImPlotTimeUnit_Mo) { + static const int step[] = {6,3,2,1}; + static const int divs[] = {2,4,6,12}; + return LowerBoundStep(max_divs, divs, step, 4); + } + return 0; +} + +ImPlotTime MkGmtTime(struct tm *ptm) { + ImPlotTime t; +#ifdef _WIN32 + t.S = _mkgmtime(ptm); +#else + t.S = timegm(ptm); +#endif + if (t.S < 0) + t.S = 0; + return t; +} + +tm* GetGmtTime(const ImPlotTime& t, tm* ptm) +{ +#ifdef _WIN32 + if (gmtime_s(ptm, &t.S) == 0) + return ptm; + else + return NULL; +#else + return gmtime_r(&t.S, ptm); +#endif +} + +ImPlotTime MkLocTime(struct tm *ptm) { + ImPlotTime t; + t.S = mktime(ptm); + if (t.S < 0) + t.S = 0; + return t; +} + +tm* GetLocTime(const ImPlotTime& t, tm* ptm) { +#ifdef _WIN32 + if (localtime_s(ptm, &t.S) == 0) + return ptm; + else + return NULL; +#else + return localtime_r(&t.S, ptm); +#endif +} + +inline ImPlotTime MkTime(struct tm *ptm) { + if (GetStyle().UseLocalTime) + return MkLocTime(ptm); + else + return MkGmtTime(ptm); +} + +inline tm* GetTime(const ImPlotTime& t, tm* ptm) { + if (GetStyle().UseLocalTime) + return GetLocTime(t,ptm); + else + return GetGmtTime(t,ptm); +} + +ImPlotTime MakeTime(int year, int month, int day, int hour, int min, int sec, int us) { + tm& Tm = GImPlot->Tm; + + int yr = year - 1900; + if (yr < 0) + yr = 0; + + sec = sec + us / 1000000; + us = us % 1000000; + + Tm.tm_sec = sec; + Tm.tm_min = min; + Tm.tm_hour = hour; + Tm.tm_mday = day; + Tm.tm_mon = month; + Tm.tm_year = yr; + + ImPlotTime t = MkTime(&Tm); + + t.Us = us; + return t; +} + +int GetYear(const ImPlotTime& t) { + tm& Tm = GImPlot->Tm; + GetTime(t, &Tm); + return Tm.tm_year + 1900; +} + +ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count) { + tm& Tm = GImPlot->Tm; + ImPlotTime t_out = t; + switch(unit) { + case ImPlotTimeUnit_Us: t_out.Us += count; break; + case ImPlotTimeUnit_Ms: t_out.Us += count * 1000; break; + case ImPlotTimeUnit_S: t_out.S += count; break; + case ImPlotTimeUnit_Min: t_out.S += count * 60; break; + case ImPlotTimeUnit_Hr: t_out.S += count * 3600; break; + case ImPlotTimeUnit_Day: t_out.S += count * 86400; break; + case ImPlotTimeUnit_Mo: for (int i = 0; i < abs(count); ++i) { + GetTime(t_out, &Tm); + if (count > 0) + t_out.S += 86400 * GetDaysInMonth(Tm.tm_year + 1900, Tm.tm_mon); + else if (count < 0) + t_out.S -= 86400 * GetDaysInMonth(Tm.tm_year + 1900 - (Tm.tm_mon == 0 ? 1 : 0), Tm.tm_mon == 0 ? 11 : Tm.tm_mon - 1); // NOT WORKING + } + break; + case ImPlotTimeUnit_Yr: for (int i = 0; i < abs(count); ++i) { + if (count > 0) + t_out.S += 86400 * (365 + (int)IsLeapYear(GetYear(t_out))); + else if (count < 0) + t_out.S -= 86400 * (365 + (int)IsLeapYear(GetYear(t_out) - 1)); + // this is incorrect if leap year and we are past Feb 28 + } + break; + default: break; + } + t_out.RollOver(); + return t_out; +} + +ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit) { + GetTime(t, &GImPlot->Tm); + switch (unit) { + case ImPlotTimeUnit_S: return ImPlotTime(t.S, 0); + case ImPlotTimeUnit_Ms: return ImPlotTime(t.S, (t.Us / 1000) * 1000); + case ImPlotTimeUnit_Us: return t; + case ImPlotTimeUnit_Yr: GImPlot->Tm.tm_mon = 0; // fall-through + case ImPlotTimeUnit_Mo: GImPlot->Tm.tm_mday = 1; // fall-through + case ImPlotTimeUnit_Day: GImPlot->Tm.tm_hour = 0; // fall-through + case ImPlotTimeUnit_Hr: GImPlot->Tm.tm_min = 0; // fall-through + case ImPlotTimeUnit_Min: GImPlot->Tm.tm_sec = 0; break; + default: return t; + } + return MkTime(&GImPlot->Tm); +} + +ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit) { + return AddTime(FloorTime(t, unit), unit, 1); +} + +ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit) { + ImPlotTime t1 = FloorTime(t, unit); + ImPlotTime t2 = AddTime(t1,unit,1); + if (t1.S == t2.S) + return t.Us - t1.Us < t2.Us - t.Us ? t1 : t2; + return t.S - t1.S < t2.S - t.S ? t1 : t2; +} + +ImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& tod_part) { + tm& Tm = GImPlot->Tm; + GetTime(date_part, &GImPlot->Tm); + int y = Tm.tm_year; + int m = Tm.tm_mon; + int d = Tm.tm_mday; + GetTime(tod_part, &GImPlot->Tm); + Tm.tm_year = y; + Tm.tm_mon = m; + Tm.tm_mday = d; + ImPlotTime t = MkTime(&Tm); + t.Us = tod_part.Us; + return t; +} + +static const char* MONTH_NAMES[] = {"January","February","March","April","May","June","July","August","September","October","November","December"}; +static const char* WD_ABRVS[] = {"Su","Mo","Tu","We","Th","Fr","Sa"}; +static const char* MONTH_ABRVS[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; + +int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk) { + tm& Tm = GImPlot->Tm; + GetTime(t, &Tm); + const int us = t.Us % 1000; + const int ms = t.Us / 1000; + const int sec = Tm.tm_sec; + const int min = Tm.tm_min; + if (use_24_hr_clk) { + const int hr = Tm.tm_hour; + switch(fmt) { + case ImPlotTimeFmt_Us: return snprintf(buffer, size, ".%03d %03d", ms, us); + case ImPlotTimeFmt_SUs: return snprintf(buffer, size, ":%02d.%03d %03d", sec, ms, us); + case ImPlotTimeFmt_SMs: return snprintf(buffer, size, ":%02d.%03d", sec, ms); + case ImPlotTimeFmt_S: return snprintf(buffer, size, ":%02d", sec); + case ImPlotTimeFmt_HrMinSMs: return snprintf(buffer, size, "%02d:%02d:%02d.%03d", hr, min, sec, ms); + case ImPlotTimeFmt_HrMinS: return snprintf(buffer, size, "%02d:%02d:%02d", hr, min, sec); + case ImPlotTimeFmt_HrMin: return snprintf(buffer, size, "%02d:%02d", hr, min); + case ImPlotTimeFmt_Hr: return snprintf(buffer, size, "%02d:00", hr); + default: return 0; + } + } + else { + const char* ap = Tm.tm_hour < 12 ? "am" : "pm"; + const int hr = (Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12; + switch(fmt) { + case ImPlotTimeFmt_Us: return snprintf(buffer, size, ".%03d %03d", ms, us); + case ImPlotTimeFmt_SUs: return snprintf(buffer, size, ":%02d.%03d %03d", sec, ms, us); + case ImPlotTimeFmt_SMs: return snprintf(buffer, size, ":%02d.%03d", sec, ms); + case ImPlotTimeFmt_S: return snprintf(buffer, size, ":%02d", sec); + case ImPlotTimeFmt_HrMinSMs: return snprintf(buffer, size, "%d:%02d:%02d.%03d%s", hr, min, sec, ms, ap); + case ImPlotTimeFmt_HrMinS: return snprintf(buffer, size, "%d:%02d:%02d%s", hr, min, sec, ap); + case ImPlotTimeFmt_HrMin: return snprintf(buffer, size, "%d:%02d%s", hr, min, ap); + case ImPlotTimeFmt_Hr: return snprintf(buffer, size, "%d%s", hr, ap); + default: return 0; + } + } +} + +int FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601) { + tm& Tm = GImPlot->Tm; + GetTime(t, &Tm); + const int day = Tm.tm_mday; + const int mon = Tm.tm_mon + 1; + const int year = Tm.tm_year + 1900; + const int yr = year % 100; + if (use_iso_8601) { + switch (fmt) { + case ImPlotDateFmt_DayMo: return snprintf(buffer, size, "--%02d-%02d", mon, day); + case ImPlotDateFmt_DayMoYr: return snprintf(buffer, size, "%d-%02d-%02d", year, mon, day); + case ImPlotDateFmt_MoYr: return snprintf(buffer, size, "%d-%02d", year, mon); + case ImPlotDateFmt_Mo: return snprintf(buffer, size, "--%02d", mon); + case ImPlotDateFmt_Yr: return snprintf(buffer, size, "%d", year); + default: return 0; + } + } + else { + switch (fmt) { + case ImPlotDateFmt_DayMo: return snprintf(buffer, size, "%d/%d", mon, day); + case ImPlotDateFmt_DayMoYr: return snprintf(buffer, size, "%d/%d/%02d", mon, day, yr); + case ImPlotDateFmt_MoYr: return snprintf(buffer, size, "%s %d", MONTH_ABRVS[Tm.tm_mon], year); + case ImPlotDateFmt_Mo: return snprintf(buffer, size, "%s", MONTH_ABRVS[Tm.tm_mon]); + case ImPlotDateFmt_Yr: return snprintf(buffer, size, "%d", year); + default: return 0; + } + } + } + +int FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeFmt fmt) { + int written = 0; + if (fmt.Date != ImPlotDateFmt_None) + written += FormatDate(t, buffer, size, fmt.Date, fmt.UseISO8601); + if (fmt.Time != ImPlotTimeFmt_None) { + if (fmt.Date != ImPlotDateFmt_None) + buffer[written++] = ' '; + written += FormatTime(t, &buffer[written], size - written, fmt.Time, fmt.Use24HourClock); + } + return written; +} + +inline float GetDateTimeWidth(ImPlotDateTimeFmt fmt) { + static const ImPlotTime t_max_width = MakeTime(2888, 12, 22, 12, 58, 58, 888888); // best guess at time that maximizes pixel width + char buffer[32]; + FormatDateTime(t_max_width, buffer, 32, fmt); + return ImGui::CalcTextSize(buffer).x; +} + +void LabelTickTime(ImPlotTick& tick, ImGuiTextBuffer& buffer, const ImPlotTime& t, ImPlotDateTimeFmt fmt) { + char temp[32]; + if (tick.ShowLabel) { + tick.TextOffset = buffer.size(); + FormatDateTime(t, temp, 32, fmt); + buffer.append(temp, temp + strlen(temp) + 1); + tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.TextOffset); + } +} + +inline bool TimeLabelSame(const char* l1, const char* l2) { + size_t len1 = strlen(l1); + size_t len2 = strlen(l2); + size_t n = len1 < len2 ? len1 : len2; + return strcmp(l1 + len1 - n, l2 + len2 - n) == 0; +} + +static const ImPlotDateTimeFmt TimeFormatLevel0[ImPlotTimeUnit_COUNT] = { + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_Us), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_SMs), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_S), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_Hr), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMo, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Mo, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Yr, ImPlotTimeFmt_None) +}; + +static const ImPlotDateTimeFmt TimeFormatLevel1[ImPlotTimeUnit_COUNT] = { + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMinS), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Yr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Yr, ImPlotTimeFmt_None) +}; + +static const ImPlotDateTimeFmt TimeFormatLevel1First[ImPlotTimeUnit_COUNT] = { + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Yr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_Yr, ImPlotTimeFmt_None) +}; + +static const ImPlotDateTimeFmt TimeFormatMouseCursor[ImPlotTimeUnit_COUNT] = { + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_Us), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_SUs), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_SMs), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMinS), + ImPlotDateTimeFmt(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMo, ImPlotTimeFmt_Hr), + ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None), + ImPlotDateTimeFmt(ImPlotDateFmt_MoYr, ImPlotTimeFmt_None) +}; + +inline ImPlotDateTimeFmt GetDateTimeFmt(const ImPlotDateTimeFmt* ctx, ImPlotTimeUnit idx) { + ImPlotStyle& style = GetStyle(); + ImPlotDateTimeFmt fmt = ctx[idx]; + fmt.UseISO8601 = style.UseISO8601; + fmt.Use24HourClock = style.Use24HourClock; + return fmt; +} + +void AddTicksTime(const ImPlotRange& range, float plot_width, ImPlotTickCollection& ticks) { + // get units for level 0 and level 1 labels + const ImPlotTimeUnit unit0 = GetUnitForRange(range.Size() / (plot_width / 100)); // level = 0 (top) + const ImPlotTimeUnit unit1 = unit0 + 1; // level = 1 (bottom) + // get time format specs + const ImPlotDateTimeFmt fmt0 = GetDateTimeFmt(TimeFormatLevel0, unit0); + const ImPlotDateTimeFmt fmt1 = GetDateTimeFmt(TimeFormatLevel1, unit1); + const ImPlotDateTimeFmt fmtf = GetDateTimeFmt(TimeFormatLevel1First, unit1); + // min max times + const ImPlotTime t_min = ImPlotTime::FromDouble(range.Min); + const ImPlotTime t_max = ImPlotTime::FromDouble(range.Max); + // maximum allowable density of labels + const float max_density = 0.5f; + // book keeping + const char* last_major = NULL; + if (unit0 != ImPlotTimeUnit_Yr) { + // pixels per major (level 1) division + const float pix_per_major_div = plot_width / (float)(range.Size() / TimeUnitSpans[unit1]); + // nominal pixels taken up by labels + const float fmt0_width = GetDateTimeWidth(fmt0); + const float fmt1_width = GetDateTimeWidth(fmt1); + const float fmtf_width = GetDateTimeWidth(fmtf); + // the maximum number of minor (level 0) labels that can fit between major (level 1) divisions + const int minor_per_major = (int)(max_density * pix_per_major_div / fmt0_width); + // the minor step size (level 0) + const int step = GetTimeStep(minor_per_major, unit0); + // generate ticks + ImPlotTime t1 = FloorTime(ImPlotTime::FromDouble(range.Min), unit1); + while (t1 < t_max) { + // get next major + const ImPlotTime t2 = AddTime(t1, unit1, 1); + // add major tick + if (t1 >= t_min && t1 <= t_max) { + // minor level 0 tick + ImPlotTick tick_min(t1.ToDouble(),true,true); + tick_min.Level = 0; + LabelTickTime(tick_min,ticks.TextBuffer,t1,fmt0); + ticks.Append(tick_min); + // major level 1 tick + ImPlotTick tick_maj(t1.ToDouble(),true,true); + tick_maj.Level = 1; + LabelTickTime(tick_maj,ticks.TextBuffer,t1, last_major == NULL ? fmtf : fmt1); + const char* this_major = ticks.TextBuffer.Buf.Data + tick_maj.TextOffset; + if (last_major && TimeLabelSame(last_major,this_major)) + tick_maj.ShowLabel = false; + last_major = this_major; + ticks.Append(tick_maj); + } + // add minor ticks up until next major + if (minor_per_major > 1 && (t_min <= t2 && t1 <= t_max)) { + ImPlotTime t12 = AddTime(t1, unit0, step); + while (t12 < t2) { + float px_to_t2 = (float)((t2 - t12).ToDouble()/range.Size()) * plot_width; + if (t12 >= t_min && t12 <= t_max) { + ImPlotTick tick(t12.ToDouble(),false,px_to_t2 >= fmt0_width); + tick.Level = 0; + LabelTickTime(tick,ticks.TextBuffer,t12,fmt0); + ticks.Append(tick); + if (last_major == NULL && px_to_t2 >= fmt0_width && px_to_t2 >= (fmt1_width + fmtf_width) / 2) { + ImPlotTick tick_maj(t12.ToDouble(),true,true); + tick_maj.Level = 1; + LabelTickTime(tick_maj,ticks.TextBuffer,t12,fmtf); + last_major = ticks.TextBuffer.Buf.Data + tick_maj.TextOffset; + ticks.Append(tick_maj); + } + } + t12 = AddTime(t12, unit0, step); + } + } + t1 = t2; + } + } + else { + const ImPlotDateTimeFmt fmty = GetDateTimeFmt(TimeFormatLevel0, ImPlotTimeUnit_Yr); + const float label_width = GetDateTimeWidth(fmty); + const int max_labels = (int)(max_density * plot_width / label_width); + const int year_min = GetYear(t_min); + const int year_max = GetYear(CeilTime(t_max, ImPlotTimeUnit_Yr)); + const double nice_range = NiceNum((year_max - year_min)*0.99,false); + const double interval = NiceNum(nice_range / (max_labels - 1), true); + const int graphmin = (int)(floor(year_min / interval) * interval); + const int graphmax = (int)(ceil(year_max / interval) * interval); + const int step = (int)interval <= 0 ? 1 : (int)interval; + + for (int y = graphmin; y < graphmax; y += step) { + ImPlotTime t = MakeTime(y); + if (t >= t_min && t <= t_max) { + ImPlotTick tick(t.ToDouble(), true, true); + tick.Level = 0; + LabelTickTime(tick, ticks.TextBuffer, t, fmty); + ticks.Append(tick); + } + } + } +} + +//----------------------------------------------------------------------------- +// Axis Utils +//----------------------------------------------------------------------------- + +int LabelAxisValue(const ImPlotAxis& axis, const ImPlotTickCollection& ticks, double value, char* buff, int size) { + ImPlotContext& gp = *GImPlot; + if (ImHasFlag(axis.Flags, ImPlotAxisFlags_LogScale)) { + return snprintf(buff, size, "%.3E", value); + } + else if (ImHasFlag(axis.Flags, ImPlotAxisFlags_Time)) { + ImPlotTimeUnit unit = (axis.Orientation == ImPlotOrientation_Horizontal) + ? GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetWidth() / 100)) + : GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetHeight() / 100)); + return FormatDateTime(ImPlotTime::FromDouble(value), buff, size, GetDateTimeFmt(TimeFormatMouseCursor, unit)); + } + else { + double range = ticks.Size > 1 ? (ticks.Ticks[1].PlotPos - ticks.Ticks[0].PlotPos) : axis.Range.Size(); + return snprintf(buff, size, "%.*f", Precision(range), value); + } +} + +void UpdateAxisColors(int axis_flag, ImPlotAxis* axis) { + const ImVec4 col_label = GetStyleColorVec4(axis_flag); + const ImVec4 col_grid = GetStyleColorVec4(axis_flag + 1); + axis->ColorMaj = ImGui::GetColorU32(col_grid); + axis->ColorMin = ImGui::GetColorU32(col_grid*ImVec4(1,1,1,GImPlot->Style.MinorAlpha)); + axis->ColorTxt = ImGui::GetColorU32(col_label); +} + +//----------------------------------------------------------------------------- +// BeginPlot() +//----------------------------------------------------------------------------- + +bool BeginPlot(const char* title, const char* x_label, const char* y1_label, const ImVec2& size, + ImPlotFlags flags, ImPlotAxisFlags x_flags, ImPlotAxisFlags y1_flags, ImPlotAxisFlags y2_flags, ImPlotAxisFlags y3_flags, + const char* y2_label, const char* y3_label) +{ + IM_ASSERT_USER_ERROR(GImPlot != NULL, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?"); + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "Mismatched BeginPlot()/EndPlot()!"); + IM_ASSERT_USER_ERROR(!(ImHasFlag(x_flags, ImPlotAxisFlags_Time) && ImHasFlag(x_flags, ImPlotAxisFlags_LogScale)), "ImPlotAxisFlags_Time and ImPlotAxisFlags_LogScale cannot be enabled at the same time!"); + IM_ASSERT_USER_ERROR(!ImHasFlag(y1_flags, ImPlotAxisFlags_Time), "Y axes cannot display time formatted labels!"); + + // FRONT MATTER ----------------------------------------------------------- + + ImGuiContext &G = *GImGui; + ImGuiWindow * Window = G.CurrentWindow; + if (Window->SkipItems) { + Reset(GImPlot); + return false; + } + + const ImGuiID ID = Window->GetID(title); + const ImGuiStyle &Style = G.Style; + const ImGuiIO & IO = ImGui::GetIO(); + + bool just_created = gp.Plots.GetByKey(ID) == NULL; + gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID); + gp.CurrentPlot->ID = ID; + ImPlotPlot &plot = *gp.CurrentPlot; + + plot.CurrentYAxis = 0; + + if (just_created) { + plot.Flags = flags; + plot.XAxis.Flags = x_flags; + plot.YAxis[0].Flags = y1_flags; + plot.YAxis[1].Flags = y2_flags; + plot.YAxis[2].Flags = y3_flags; + } + else { + // TODO: Check which individual flags changed, and only reset those! + // There's probably an easy bit mask trick I'm not aware of. + if (flags != plot.PreviousFlags) + plot.Flags = flags; + if (x_flags != plot.XAxis.PreviousFlags) + plot.XAxis.Flags = x_flags; + if (y1_flags != plot.YAxis[0].PreviousFlags) + plot.YAxis[0].Flags = y1_flags; + if (y2_flags != plot.YAxis[1].PreviousFlags) + plot.YAxis[1].Flags = y2_flags; + if (y3_flags != plot.YAxis[2].PreviousFlags) + plot.YAxis[2].Flags = y3_flags; + } + + plot.PreviousFlags = flags; + plot.XAxis.PreviousFlags = x_flags; + plot.YAxis[0].PreviousFlags = y1_flags; + plot.YAxis[1].PreviousFlags = y2_flags; + plot.YAxis[2].PreviousFlags = y3_flags; + + // capture scroll with a child region + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoChild)) { + ImGui::BeginChild(title, ImVec2(size.x == 0 ? gp.Style.PlotDefaultSize.x : size.x, size.y == 0 ? gp.Style.PlotDefaultSize.y : size.y), false, ImGuiWindowFlags_NoScrollbar); + Window = ImGui::GetCurrentWindow(); + Window->ScrollMax.y = 1.0f; + gp.ChildWindowMade = true; + } + else { + gp.ChildWindowMade = false; + } + + ImDrawList &DrawList = *Window->DrawList; + + // NextPlotData ----------------------------------------------------------- + + // linked axes + plot.XAxis.LinkedMin = gp.NextPlotData.LinkedXmin; + plot.XAxis.LinkedMax = gp.NextPlotData.LinkedXmax; + PullLinkedAxis(plot.XAxis); + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + plot.YAxis[i].LinkedMin = gp.NextPlotData.LinkedYmin[i]; + plot.YAxis[i].LinkedMax = gp.NextPlotData.LinkedYmax[i]; + PullLinkedAxis(plot.YAxis[i]); + } + + if (gp.NextPlotData.HasXRange) { + if (just_created || gp.NextPlotData.XRangeCond == ImGuiCond_Always) + plot.XAxis.SetRange(gp.NextPlotData.X); + } + + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (gp.NextPlotData.HasYRange[i]) { + if (just_created || gp.NextPlotData.YRangeCond[i] == ImGuiCond_Always) + plot.YAxis[i].SetRange(gp.NextPlotData.Y[i]); + } + } + + // AXIS STATES ------------------------------------------------------------ + plot.XAxis.HasRange = gp.NextPlotData.HasXRange; plot.XAxis.RangeCond = gp.NextPlotData.XRangeCond; plot.XAxis.Present = true; + plot.YAxis[0].HasRange = gp.NextPlotData.HasYRange[0]; plot.YAxis[0].RangeCond = gp.NextPlotData.YRangeCond[0]; plot.YAxis[0].Present = true; + plot.YAxis[1].HasRange = gp.NextPlotData.HasYRange[1]; plot.YAxis[1].RangeCond = gp.NextPlotData.YRangeCond[1]; plot.YAxis[1].Present = ImHasFlag(plot.Flags, ImPlotFlags_YAxis2); + plot.YAxis[2].HasRange = gp.NextPlotData.HasYRange[2]; plot.YAxis[2].RangeCond = gp.NextPlotData.YRangeCond[2]; plot.YAxis[2].Present = ImHasFlag(plot.Flags, ImPlotFlags_YAxis3); + + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + if (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale) && !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_LogScale)) + gp.Scales[i] = ImPlotScale_LinLin; + else if (ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale) && !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_LogScale)) + gp.Scales[i] = ImPlotScale_LogLin; + else if (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale) && ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_LogScale)) + gp.Scales[i] = ImPlotScale_LinLog; + else if (ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale) && ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_LogScale)) + gp.Scales[i] = ImPlotScale_LogLog; + } + + // constraints + plot.XAxis.Constrain(); + for (int i = 0; i < IMPLOT_Y_AXES; ++i) + plot.YAxis[i].Constrain(); + + // constrain equal axes for primary x and y if not approximately equal + // constrains x to y since x pixel size depends on y labels width, and causes feedback loops in opposite case + if (ImHasFlag(plot.Flags, ImPlotFlags_Equal)) { + double xar = plot.XAxis.GetAspect(); + double yar = plot.YAxis[0].GetAspect(); + if (!ImAlmostEqual(xar,yar) && !plot.YAxis[0].IsInputLocked()) + plot.XAxis.SetAspect(yar); + } + + // AXIS COLORS ----------------------------------------------------------------- + + UpdateAxisColors(ImPlotCol_XAxis, &plot.XAxis); + UpdateAxisColors(ImPlotCol_YAxis, &plot.YAxis[0]); + UpdateAxisColors(ImPlotCol_YAxis2, &plot.YAxis[1]); + UpdateAxisColors(ImPlotCol_YAxis3, &plot.YAxis[2]); + + // BB, PADDING, HOVER ----------------------------------------------------------- + + // frame + ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y); + if (frame_size.x < gp.Style.PlotMinSize.x && size.x < 0.0f) + frame_size.x = gp.Style.PlotMinSize.x; + if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f) + frame_size.y = gp.Style.PlotMinSize.y; + plot.FrameRect = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size); + ImGui::ItemSize(plot.FrameRect); + if (!ImGui::ItemAdd(plot.FrameRect, ID, &plot.FrameRect)) { + Reset(GImPlot); + return false; + } + plot.FrameHovered = ImGui::ItemHoverable(plot.FrameRect, ID); + if (G.HoveredIdPreviousFrame != 0 && G.HoveredIdPreviousFrame != ID) + plot.FrameHovered = false; + ImGui::SetItemAllowOverlap(); + ImGui::RenderFrame(plot.FrameRect.Min, plot.FrameRect.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, Style.FrameRounding); + + // canvas/axes bb + plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding); + plot.AxesRect = plot.FrameRect; + + // outside legend adjustments + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.GetLegendCount() > 0 && plot.LegendOutside) { + const ImVec2 legend_size = CalcLegendSize(plot, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, plot.LegendOrientation); + const bool west = ImHasFlag(plot.LegendLocation, ImPlotLocation_West) && !ImHasFlag(plot.LegendLocation, ImPlotLocation_East); + const bool east = ImHasFlag(plot.LegendLocation, ImPlotLocation_East) && !ImHasFlag(plot.LegendLocation, ImPlotLocation_West); + const bool north = ImHasFlag(plot.LegendLocation, ImPlotLocation_North) && !ImHasFlag(plot.LegendLocation, ImPlotLocation_South); + const bool south = ImHasFlag(plot.LegendLocation, ImPlotLocation_South) && !ImHasFlag(plot.LegendLocation, ImPlotLocation_North); + const bool horz = plot.LegendOrientation == ImPlotOrientation_Horizontal; + if ((west && !horz) || (west && horz && !north && !south)) { + plot.CanvasRect.Min.x += (legend_size.x + gp.Style.LegendPadding.x); + plot.AxesRect.Min.x += (legend_size.x + gp.Style.PlotPadding.x); + } + if ((east && !horz) || (east && horz && !north && !south)) { + plot.CanvasRect.Max.x -= (legend_size.x + gp.Style.LegendPadding.x); + plot.AxesRect.Max.x -= (legend_size.x + gp.Style.PlotPadding.x); + } + if ((north && horz) || (north && !horz && !west && !east)) { + plot.CanvasRect.Min.y += (legend_size.y + gp.Style.LegendPadding.y); + plot.AxesRect.Min.y += (legend_size.y + gp.Style.PlotPadding.y); + } + if ((south && horz) || (south && !horz && !west && !east)) { + plot.CanvasRect.Max.y -= (legend_size.y + gp.Style.LegendPadding.y); + plot.AxesRect.Max.y -= (legend_size.y + gp.Style.PlotPadding.y); + } + } + + gp.RenderX = (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoGridLines) || + !ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoTickMarks) || + !ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoTickLabels)); + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + gp.RenderY[i] = plot.YAxis[i].Present && + (!ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoGridLines) || + !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoTickMarks) || + !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoTickLabels)); + } + + // plot bb + + // (1) calc top/bot padding and plot height + ImVec2 title_size(0.0f, 0.0f); + const float txt_height = ImGui::GetTextLineHeight(); + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoTitle)){ + title_size = ImGui::CalcTextSize(title, NULL, true); + } + + const bool show_x_label = x_label && !ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoLabel); + + const float pad_top = title_size.x > 0.0f ? txt_height + gp.Style.LabelPadding.y : 0; + const float pad_bot = (plot.XAxis.IsLabeled() ? txt_height + gp.Style.LabelPadding.y + (plot.XAxis.IsTime() ? txt_height + gp.Style.LabelPadding.y : 0) : 0) + + (show_x_label ? txt_height + gp.Style.LabelPadding.y : 0); + + const float plot_height = plot.CanvasRect.GetHeight() - pad_top - pad_bot; + + // (2) get y tick labels (needed for left/right pad) + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (gp.RenderY[i] && gp.NextPlotData.ShowDefaultTicksY[i]) { + if (ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_LogScale)) + AddTicksLogarithmic(plot.YAxis[i].Range, ImMax(2, (int)IM_ROUND(plot_height * 0.02f)) ,gp.YTicks[i]); + else + AddTicksDefault(plot.YAxis[i].Range, ImMax(2, (int)IM_ROUND(0.0025 * plot_height)), IMPLOT_SUB_DIV, gp.YTicks[i]); + } + } + + // (3) calc left/right pad + const bool show_y1_label = y1_label && !ImHasFlag(plot.YAxis[0].Flags, ImPlotAxisFlags_NoLabel); + const bool show_y2_label = y2_label && !ImHasFlag(plot.YAxis[1].Flags, ImPlotAxisFlags_NoLabel); + const bool show_y3_label = y3_label && !ImHasFlag(plot.YAxis[2].Flags, ImPlotAxisFlags_NoLabel); + + const float pad_left = (show_y1_label ? txt_height + gp.Style.LabelPadding.x : 0) + + (plot.YAxis[0].IsLabeled() ? gp.YTicks[0].MaxWidth + gp.Style.LabelPadding.x : 0); + const float pad_right = ((plot.YAxis[1].Present && plot.YAxis[1].IsLabeled()) ? gp.YTicks[1].MaxWidth + gp.Style.LabelPadding.x : 0) + + ((plot.YAxis[1].Present && show_y2_label) ? txt_height + gp.Style.LabelPadding.x : 0) + + ((plot.YAxis[1].Present && plot.YAxis[2].Present) ? gp.Style.LabelPadding.x + gp.Style.MinorTickLen.y : 0) + + ((plot.YAxis[2].Present && plot.YAxis[2].IsLabeled()) ? gp.YTicks[2].MaxWidth + gp.Style.LabelPadding.x : 0) + + ((plot.YAxis[2].Present && show_y3_label) ? txt_height + gp.Style.LabelPadding.x : 0); + + const float plot_width = plot.CanvasRect.GetWidth() - pad_left - pad_right; + + // (4) get x ticks + if (gp.RenderX && gp.NextPlotData.ShowDefaultTicksX) { + if (plot.XAxis.IsTime()) + AddTicksTime(plot.XAxis.Range, plot_width, gp.XTicks); + else if (ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale)) + AddTicksLogarithmic(plot.XAxis.Range, (int)IM_ROUND(plot_width * 0.01f), gp.XTicks); + else + AddTicksDefault(plot.XAxis.Range, ImMax(2, (int)IM_ROUND(0.0025 * plot_width)), IMPLOT_SUB_DIV, gp.XTicks); + } + + // (5) calc plot bb + plot.PlotRect = ImRect(plot.CanvasRect.Min + ImVec2(pad_left, pad_top), plot.CanvasRect.Max - ImVec2(pad_right, pad_bot)); + plot.PlotHovered = plot.PlotRect.Contains(IO.MousePos) && plot.FrameHovered; + + // x axis region bb and hover + plot.XAxis.HoverRect = ImRect(plot.PlotRect.GetBL(), ImVec2(plot.PlotRect.Max.x, plot.AxesRect.Max.y)); + plot.XAxis.ExtHovered = plot.XAxis.HoverRect.Contains(IO.MousePos); + plot.XAxis.AllHovered = plot.XAxis.ExtHovered || plot.PlotHovered; + + // axis label reference + gp.YAxisReference[0] = plot.PlotRect.Min.x; + gp.YAxisReference[1] = plot.PlotRect.Max.x; + gp.YAxisReference[2] = !plot.YAxis[1].Present ? plot.PlotRect.Max.x : gp.YAxisReference[1] + + (plot.YAxis[1].IsLabeled() ? gp.Style.LabelPadding.x + gp.YTicks[1].MaxWidth : 0) + + (show_y2_label ? txt_height + gp.Style.LabelPadding.x : 0) + + gp.Style.LabelPadding.x + gp.Style.MinorTickLen.y; + + // y axis regions bb and hover + plot.YAxis[0].HoverRect = ImRect(ImVec2(plot.AxesRect.Min.x, plot.PlotRect.Min.y), ImVec2(plot.PlotRect.Min.x, plot.PlotRect.Max.y)); + plot.YAxis[1].HoverRect = plot.YAxis[2].Present + ? ImRect(plot.PlotRect.GetTR(), ImVec2(gp.YAxisReference[2], plot.PlotRect.Max.y)) + : ImRect(plot.PlotRect.GetTR(), ImVec2(plot.AxesRect.Max.x, plot.PlotRect.Max.y)); + + plot.YAxis[2].HoverRect = ImRect(ImVec2(gp.YAxisReference[2], plot.PlotRect.Min.y), ImVec2(plot.AxesRect.Max.x, plot.PlotRect.Max.y)); + + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + plot.YAxis[i].ExtHovered = plot.YAxis[i].Present && plot.YAxis[i].HoverRect.Contains(IO.MousePos); + plot.YAxis[i].AllHovered = plot.YAxis[i].ExtHovered || plot.PlotHovered; + } + + const bool any_hov_y_axis_region = plot.YAxis[0].AllHovered || plot.YAxis[1].AllHovered || plot.YAxis[2].AllHovered; + + bool hov_query = false; + if (plot.FrameHovered && plot.PlotHovered && plot.Queried && !plot.Querying) { + ImRect bb_query = plot.QueryRect; + bb_query.Min += plot.PlotRect.Min; + bb_query.Max += plot.PlotRect.Min; + hov_query = bb_query.Contains(IO.MousePos); + } + + // AXIS ASPECT RATIOS + plot.XAxis.Pixels = plot.PlotRect.GetWidth(); + for (int i = 0; i < IMPLOT_Y_AXES; ++i) + plot.YAxis[i].Pixels = plot.PlotRect.GetHeight(); + + // QUERY DRAG ------------------------------------------------------------- + if (plot.DraggingQuery && (IO.MouseReleased[gp.InputMap.PanButton] || !IO.MouseDown[gp.InputMap.PanButton])) { + plot.DraggingQuery = false; + } + if (plot.DraggingQuery) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); + plot.QueryRect.Min += IO.MouseDelta; + plot.QueryRect.Max += IO.MouseDelta; + } + if (plot.FrameHovered && plot.PlotHovered && hov_query && !plot.DraggingQuery && !plot.Selecting && !plot.LegendHovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); + const bool any_y_dragging = plot.YAxis[0].Dragging || plot.YAxis[1].Dragging || plot.YAxis[2].Dragging; + if (IO.MouseDown[gp.InputMap.PanButton] && !plot.XAxis.Dragging && !any_y_dragging) { + plot.DraggingQuery = true; + } + } + + // DRAG INPUT ------------------------------------------------------------- + + const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal); + + // end drags + if (plot.XAxis.Dragging && (IO.MouseReleased[gp.InputMap.PanButton] || !IO.MouseDown[gp.InputMap.PanButton])) { + plot.XAxis.Dragging = false; + G.IO.MouseDragMaxDistanceSqr[0] = 0; + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (plot.YAxis[i].Dragging && (IO.MouseReleased[gp.InputMap.PanButton] || !IO.MouseDown[gp.InputMap.PanButton])) { + plot.YAxis[i].Dragging = false; + G.IO.MouseDragMaxDistanceSqr[0] = 0; + } + } + const bool any_y_dragging = plot.YAxis[0].Dragging || plot.YAxis[1].Dragging || plot.YAxis[2].Dragging; + bool drag_in_progress = plot.XAxis.Dragging || any_y_dragging; + // do drag + if (drag_in_progress) { + UpdateTransformCache(); + bool equal_dragged = false; + // special case for axis equal and both x and y0 hovered + if (axis_equal && !plot.XAxis.IsInputLocked() && plot.XAxis.Dragging && !plot.YAxis[0].IsInputLocked() && plot.YAxis[0].Dragging) { + ImPlotPoint plot_tl = PixelsToPlot(plot.PlotRect.Min - IO.MouseDelta, 0); + ImPlotPoint plot_br = PixelsToPlot(plot.PlotRect.Max - IO.MouseDelta, 0); + if (!plot.XAxis.IsLockedMin()) + plot.XAxis.SetMin(plot.XAxis.IsInverted() ? plot_br.x : plot_tl.x); + if (!plot.XAxis.IsLockedMax()) + plot.XAxis.SetMax(plot.XAxis.IsInverted() ? plot_tl.x : plot_br.x); + if (!plot.YAxis[0].IsLockedMin()) + plot.YAxis[0].SetMin(plot.YAxis[0].IsInverted() ? plot_tl.y : plot_br.y); + if (!plot.YAxis[0].IsLockedMax()) + plot.YAxis[0].SetMax(plot.YAxis[0].IsInverted() ? plot_br.y : plot_tl.y); + double xar = plot.XAxis.GetAspect(); + double yar = plot.YAxis[0].GetAspect(); + if (!ImAlmostEqual(xar,yar) && !plot.YAxis[0].IsInputLocked()) + plot.XAxis.SetAspect(yar); + equal_dragged = true; + } + if (!plot.XAxis.IsInputLocked() && plot.XAxis.Dragging && !equal_dragged) { + ImPlotPoint plot_tl = PixelsToPlot(plot.PlotRect.Min - IO.MouseDelta, 0); + ImPlotPoint plot_br = PixelsToPlot(plot.PlotRect.Max - IO.MouseDelta, 0); + if (!plot.XAxis.IsLockedMin()) + plot.XAxis.SetMin(plot.XAxis.IsInverted() ? plot_br.x : plot_tl.x); + if (!plot.XAxis.IsLockedMax()) + plot.XAxis.SetMax(plot.XAxis.IsInverted() ? plot_tl.x : plot_br.x); + if (axis_equal) + plot.YAxis[0].SetAspect(plot.XAxis.GetAspect()); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (!plot.YAxis[i].IsInputLocked() && plot.YAxis[i].Dragging && !(i == 0 && equal_dragged)) { + ImPlotPoint plot_tl = PixelsToPlot(plot.PlotRect.Min - IO.MouseDelta, i); + ImPlotPoint plot_br = PixelsToPlot(plot.PlotRect.Max - IO.MouseDelta, i); + if (!plot.YAxis[i].IsLockedMin()) + plot.YAxis[i].SetMin(plot.YAxis[i].IsInverted() ? plot_tl.y : plot_br.y); + if (!plot.YAxis[i].IsLockedMax()) + plot.YAxis[i].SetMax(plot.YAxis[i].IsInverted() ? plot_br.y : plot_tl.y); + if (i == 0 && axis_equal) + plot.XAxis.SetAspect(plot.YAxis[0].GetAspect()); + } + } + // Set the mouse cursor based on which axes are moving. + int direction = 0; + if (!plot.XAxis.IsInputLocked() && plot.XAxis.Dragging) { + direction |= (1 << 1); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (!plot.YAxis[i].Present) { continue; } + if (!plot.YAxis[i].IsInputLocked() && plot.YAxis[i].Dragging) { + direction |= (1 << 2); + break; + } + } + if (IO.MouseDragMaxDistanceSqr[0] > 5) { + if (direction == 0) + ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); + else if (direction == (1 << 1)) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + else if (direction == (1 << 2)) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); + else + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); + } + } + // start drag + if (!drag_in_progress && plot.FrameHovered && IO.MouseClicked[gp.InputMap.PanButton] && ImHasFlag(IO.KeyMods, gp.InputMap.PanMod) && !plot.Selecting && !plot.LegendHovered && !hov_query && !plot.DraggingQuery) { + if (plot.XAxis.AllHovered) { + plot.XAxis.Dragging = true; + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (plot.YAxis[i].AllHovered) { + plot.YAxis[i].Dragging = true; + } + } + } + + // SCROLL INPUT ----------------------------------------------------------- + + if (plot.FrameHovered && (plot.XAxis.AllHovered || any_hov_y_axis_region) && IO.MouseWheel != 0) { + UpdateTransformCache(); + float zoom_rate = IMPLOT_ZOOM_RATE; + if (IO.MouseWheel > 0) + zoom_rate = (-zoom_rate) / (1.0f + (2.0f * zoom_rate)); + float tx = ImRemap(IO.MousePos.x, plot.PlotRect.Min.x, plot.PlotRect.Max.x, 0.0f, 1.0f); + float ty = ImRemap(IO.MousePos.y, plot.PlotRect.Min.y, plot.PlotRect.Max.y, 0.0f, 1.0f); + bool equal_zoomed = false; + // special case for axis equal and both x and y0 hovered + if (axis_equal && plot.XAxis.AllHovered && !plot.XAxis.IsInputLocked() && plot.YAxis[0].AllHovered && !plot.YAxis[0].IsInputLocked()) { + const ImPlotPoint& plot_tl = PixelsToPlot(plot.PlotRect.Min - plot.PlotRect.GetSize() * ImVec2(tx * zoom_rate, ty * zoom_rate), 0); + const ImPlotPoint& plot_br = PixelsToPlot(plot.PlotRect.Max + plot.PlotRect.GetSize() * ImVec2((1 - tx) * zoom_rate, (1 - ty) * zoom_rate), 0); + if (!plot.XAxis.IsLockedMin()) + plot.XAxis.SetMin(plot.XAxis.IsInverted() ? plot_br.x : plot_tl.x); + if (!plot.XAxis.IsLockedMax()) + plot.XAxis.SetMax(plot.XAxis.IsInverted() ? plot_tl.x : plot_br.x); + if (!plot.YAxis[0].IsLockedMin()) + plot.YAxis[0].SetMin(plot.YAxis[0].IsInverted() ? plot_tl.y : plot_br.y); + if (!plot.YAxis[0].IsLockedMax()) + plot.YAxis[0].SetMax(plot.YAxis[0].IsInverted() ? plot_br.y : plot_tl.y); + double xar = plot.XAxis.GetAspect(); + double yar = plot.YAxis[0].GetAspect(); + if (!ImAlmostEqual(xar,yar) && !plot.YAxis[0].IsInputLocked()) + plot.XAxis.SetAspect(yar); + equal_zoomed = true; + } + if (plot.XAxis.AllHovered && !plot.XAxis.IsInputLocked() && !equal_zoomed) { + const ImPlotPoint& plot_tl = PixelsToPlot(plot.PlotRect.Min - plot.PlotRect.GetSize() * ImVec2(tx * zoom_rate, ty * zoom_rate), 0); + const ImPlotPoint& plot_br = PixelsToPlot(plot.PlotRect.Max + plot.PlotRect.GetSize() * ImVec2((1 - tx) * zoom_rate, (1 - ty) * zoom_rate), 0); + if (!plot.XAxis.IsLockedMin()) + plot.XAxis.SetMin(plot.XAxis.IsInverted() ? plot_br.x : plot_tl.x); + if (!plot.XAxis.IsLockedMax()) + plot.XAxis.SetMax(plot.XAxis.IsInverted() ? plot_tl.x : plot_br.x); + if (axis_equal) + plot.YAxis[0].SetAspect(plot.XAxis.GetAspect()); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (plot.YAxis[i].AllHovered && !plot.YAxis[i].IsInputLocked() && !(i == 0 && equal_zoomed)) { + const ImPlotPoint& plot_tl = PixelsToPlot(plot.PlotRect.Min - plot.PlotRect.GetSize() * ImVec2(tx * zoom_rate, ty * zoom_rate), i); + const ImPlotPoint& plot_br = PixelsToPlot(plot.PlotRect.Max + plot.PlotRect.GetSize() * ImVec2((1 - tx) * zoom_rate, (1 - ty) * zoom_rate), i); + if (!plot.YAxis[i].IsLockedMin()) + plot.YAxis[i].SetMin(plot.YAxis[i].IsInverted() ? plot_tl.y : plot_br.y); + if (!plot.YAxis[i].IsLockedMax()) + plot.YAxis[i].SetMax(plot.YAxis[i].IsInverted() ? plot_br.y : plot_tl.y); + if (i == 0 && axis_equal) + plot.XAxis.SetAspect(plot.YAxis[0].GetAspect()); + } + } + } + + // BOX-SELECTION AND QUERY ------------------------------------------------ + + // confirm selection + if (plot.Selecting && (IO.MouseReleased[gp.InputMap.BoxSelectButton] || !IO.MouseDown[gp.InputMap.BoxSelectButton])) { + UpdateTransformCache(); + ImVec2 select_size = plot.SelectStart - IO.MousePos; + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect)) { + const bool x_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.HorizontalMod) && ImFabs(select_size.x) > 2; + const bool y_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.VerticalMod) && ImFabs(select_size.y) > 2; + if (!plot.XAxis.IsInputLocked()) { + ImPlotPoint p1 = PixelsToPlot(plot.SelectStart); + ImPlotPoint p2 = PixelsToPlot(IO.MousePos); + if (!plot.XAxis.IsLockedMin() && x_can_change) + plot.XAxis.SetMin(ImMin(p1.x, p2.x)); + if (!plot.XAxis.IsLockedMax() && x_can_change) + plot.XAxis.SetMax(ImMax(p1.x, p2.x)); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (!plot.YAxis->IsInputLocked()) { + ImPlotPoint p1 = PixelsToPlot(plot.SelectStart, i); + ImPlotPoint p2 = PixelsToPlot(IO.MousePos, i); + if (!plot.YAxis[i].IsLockedMin() && y_can_change) + plot.YAxis[i].SetMin(ImMin(p1.y, p2.y)); + if (!plot.YAxis[i].IsLockedMax() && y_can_change) + plot.YAxis[i].SetMax(ImMax(p1.y, p2.y)); + } + } + if (x_can_change || y_can_change || (ImHasFlag(IO.KeyMods,gp.InputMap.HorizontalMod) && ImHasFlag(IO.KeyMods,gp.InputMap.VerticalMod))) + plot.ContextLocked = gp.InputMap.BoxSelectButton == gp.InputMap.ContextMenuButton; + } + plot.Selecting = false; + } + // bad selection + if (plot.Selecting && (ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect) || plot.IsInputLocked()) && ImLengthSqr(plot.SelectStart - IO.MousePos) > 4) { + ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); + plot.ContextLocked = gp.InputMap.BoxSelectButton == gp.InputMap.ContextMenuButton; + } + // cancel selection + if (plot.Selecting && (IO.MouseClicked[gp.InputMap.BoxSelectCancelButton] || IO.MouseDown[gp.InputMap.BoxSelectCancelButton])) { + plot.Selecting = false; + plot.ContextLocked = gp.InputMap.BoxSelectButton == gp.InputMap.ContextMenuButton; + } + // begin selection or query + if (plot.FrameHovered && plot.PlotHovered && IO.MouseClicked[gp.InputMap.BoxSelectButton] && ImHasFlag(IO.KeyMods, gp.InputMap.BoxSelectMod)) { + plot.SelectStart = IO.MousePos; + plot.Selecting = true; + } + // update query + if (plot.Querying) { + UpdateTransformCache(); + plot.QueryRect.Min.x = ImHasFlag(IO.KeyMods, gp.InputMap.HorizontalMod) ? plot.PlotRect.Min.x : ImMin(plot.QueryStart.x, IO.MousePos.x); + plot.QueryRect.Max.x = ImHasFlag(IO.KeyMods, gp.InputMap.HorizontalMod) ? plot.PlotRect.Max.x : ImMax(plot.QueryStart.x, IO.MousePos.x); + plot.QueryRect.Min.y = ImHasFlag(IO.KeyMods, gp.InputMap.VerticalMod) ? plot.PlotRect.Min.y : ImMin(plot.QueryStart.y, IO.MousePos.y); + plot.QueryRect.Max.y = ImHasFlag(IO.KeyMods, gp.InputMap.VerticalMod) ? plot.PlotRect.Max.y : ImMax(plot.QueryStart.y, IO.MousePos.y); + + plot.QueryRect.Min -= plot.PlotRect.Min; + plot.QueryRect.Max -= plot.PlotRect.Min; + } + // end query + if (plot.Querying && (IO.MouseReleased[gp.InputMap.QueryButton] || IO.MouseReleased[gp.InputMap.BoxSelectButton])) { + plot.Querying = false; + if (plot.QueryRect.GetWidth() > 2 && plot.QueryRect.GetHeight() > 2) { + plot.Queried = true; + plot.ContextLocked = gp.InputMap.BoxSelectButton == gp.InputMap.ContextMenuButton; + } + else + plot.Queried = false; + } + + // begin query + if (ImHasFlag(plot.Flags, ImPlotFlags_Query) && plot.FrameHovered && plot.PlotHovered && IO.MouseClicked[gp.InputMap.QueryButton] && ImHasFlag(IO.KeyMods, gp.InputMap.QueryMod)) { + plot.QueryRect = ImRect(0,0,0,0); + plot.Querying = true; + plot.Queried = true; + plot.QueryStart = IO.MousePos; + } + // toggle between select/query + if (ImHasFlag(plot.Flags, ImPlotFlags_Query) && plot.Selecting && ImHasFlag(IO.KeyMods,gp.InputMap.QueryToggleMod)) { + plot.Selecting = false; + plot.QueryRect = ImRect(0,0,0,0); + plot.Querying = true; + plot.Queried = true; + plot.QueryStart = plot.SelectStart; + } + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect) && plot.Querying && !ImHasFlag(IO.KeyMods, gp.InputMap.QueryToggleMod) && !IO.MouseDown[gp.InputMap.QueryButton]) { + plot.Selecting = true; + plot.Querying = false; + plot.Queried = false; + plot.QueryRect = ImRect(0,0,0,0); + } + if (!ImHasFlag(plot.Flags, ImPlotFlags_Query)) { + plot.Queried = false; + plot.Querying = false; + plot.QueryRect = ImRect(0,0,0,0); + } + + // FIT ----------------------------------------------------------- + + // fit from double click + if ( IO.MouseDoubleClicked[gp.InputMap.FitButton] && plot.FrameHovered && (plot.XAxis.AllHovered || any_hov_y_axis_region) && !plot.LegendHovered && !hov_query ) { + gp.FitThisFrame = true; + gp.FitX = plot.XAxis.AllHovered; + for (int i = 0; i < IMPLOT_Y_AXES; i++) + gp.FitY[i] = plot.YAxis[i].AllHovered; + } + // fit from FitNextPlotAxes or auto fit + if (gp.NextPlotData.FitX || ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_AutoFit)) { + gp.FitThisFrame = true; + gp.FitX = true; + } + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + if (gp.NextPlotData.FitY[i] || ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_AutoFit)) { + gp.FitThisFrame = true; + gp.FitY[i] = true; + } + } + + // FOCUS ------------------------------------------------------------------ + + // focus window + if ((IO.MouseClicked[0] || IO.MouseClicked[1] || IO.MouseClicked[2]) && plot.FrameHovered) + ImGui::FocusWindow(ImGui::GetCurrentWindow()); + + UpdateTransformCache(); + + // set mouse position + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + gp.MousePos[i] = PixelsToPlot(IO.MousePos, i); + } + + // RENDER ----------------------------------------------------------------- + + // grid bg + DrawList.AddRectFilled(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBg)); + + // render axes + PushPlotClipRect(); + + // transform ticks (TODO: Move this into ImPlotTickCollection) + if (gp.RenderX) { + for (int t = 0; t < gp.XTicks.Size; t++) { + ImPlotTick *xt = &gp.XTicks.Ticks[t]; + xt->PixelPos = PlotToPixels(xt->PlotPos, 0, 0).x; + } + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (gp.RenderY[i]) { + for (int t = 0; t < gp.YTicks[i].Size; t++) { + ImPlotTick *yt = &gp.YTicks[i].Ticks[t]; + yt->PixelPos = PlotToPixels(0, yt->PlotPos, i).y; + } + } + } + + // render grid + if (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoGridLines)) { + float density = gp.XTicks.Size / plot.PlotRect.GetWidth(); + ImVec4 col_min = ImGui::ColorConvertU32ToFloat4(plot.XAxis.ColorMin); + col_min.w *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f); + ImU32 col_min32 = ImGui::ColorConvertFloat4ToU32(col_min); + for (int t = 0; t < gp.XTicks.Size; t++) { + ImPlotTick& xt = gp.XTicks.Ticks[t]; + if (xt.Level == 0) { + if (xt.Major) + DrawList.AddLine(ImVec2(xt.PixelPos, plot.PlotRect.Min.y), ImVec2(xt.PixelPos, plot.PlotRect.Max.y), plot.XAxis.ColorMaj, gp.Style.MajorGridSize.x); + else if (density < 0.2f) + DrawList.AddLine(ImVec2(xt.PixelPos, plot.PlotRect.Min.y), ImVec2(xt.PixelPos, plot.PlotRect.Max.y), col_min32, gp.Style.MinorGridSize.x); + } + } + } + + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (plot.YAxis[i].Present && !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoGridLines)) { + float density = gp.YTicks[i].Size / plot.PlotRect.GetHeight(); + ImVec4 col_min = ImGui::ColorConvertU32ToFloat4(plot.YAxis[i].ColorMin); + col_min.w *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f); + ImU32 col_min32 = ImGui::ColorConvertFloat4ToU32(col_min); + for (int t = 0; t < gp.YTicks[i].Size; t++) { + ImPlotTick& yt = gp.YTicks[i].Ticks[t]; + if (yt.Major) + DrawList.AddLine(ImVec2(plot.PlotRect.Min.x, yt.PixelPos), ImVec2(plot.PlotRect.Max.x, yt.PixelPos), plot.YAxis[i].ColorMaj, gp.Style.MajorGridSize.y); + else if (density < 0.2f) + DrawList.AddLine(ImVec2(plot.PlotRect.Min.x, yt.PixelPos), ImVec2(plot.PlotRect.Max.x, yt.PixelPos), col_min32, gp.Style.MinorGridSize.y); + } + } + } + + PopPlotClipRect(); + + // render title + if (title_size.x > 0.0f && !ImHasFlag(plot.Flags, ImPlotFlags_NoTitle)) { + ImU32 col = GetStyleColorU32(ImPlotCol_TitleText); + const char* title_end = ImGui::FindRenderedTextEnd(title); + DrawList.AddText(ImVec2(plot.CanvasRect.GetCenter().x - title_size.x * 0.5f, plot.CanvasRect.Min.y),col,title,title_end); + } + + // render axis labels + if (show_x_label) { + const ImVec2 xLabel_size = ImGui::CalcTextSize(x_label); + const ImVec2 xLabel_pos(plot.PlotRect.GetCenter().x - xLabel_size.x * 0.5f, plot.CanvasRect.Max.y - txt_height); + DrawList.AddText(xLabel_pos, plot.XAxis.ColorTxt, x_label); + } + + if (show_y1_label) { + const ImVec2 yLabel_size = CalcTextSizeVertical(y1_label); + const ImVec2 yLabel_pos(plot.CanvasRect.Min.x, plot.PlotRect.GetCenter().y + yLabel_size.y * 0.5f); + AddTextVertical(&DrawList, yLabel_pos, plot.YAxis[0].ColorTxt, y1_label); + } + + const char* y_labels[] = {y2_label, y3_label}; + for (int i = 1; i < IMPLOT_Y_AXES; i++) { + const char* current_label = y_labels[i-1]; + if (plot.YAxis[i].Present && current_label && !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoLabel)) { + const ImVec2 yLabel_size = CalcTextSizeVertical(current_label); + float label_offset = (plot.YAxis[i].IsLabeled() ? gp.YTicks[i].MaxWidth + gp.Style.LabelPadding.x : 0.0f) + gp.Style.LabelPadding.x; + const ImVec2 yLabel_pos(gp.YAxisReference[i] + label_offset, plot.PlotRect.GetCenter().y + yLabel_size.y * 0.5f); + AddTextVertical(&DrawList, yLabel_pos, plot.YAxis[i].ColorTxt, current_label); + } + } + + // render tick labels + ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true); + if (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoTickLabels)) { + for (int t = 0; t < gp.XTicks.Size; t++) { + ImPlotTick *xt = &gp.XTicks.Ticks[t]; + if (xt->ShowLabel && xt->PixelPos >= plot.PlotRect.Min.x - 1 && xt->PixelPos <= plot.PlotRect.Max.x + 1) + DrawList.AddText(ImVec2(xt->PixelPos - xt->LabelSize.x * 0.5f, plot.PlotRect.Max.y + gp.Style.LabelPadding.y + xt->Level * (txt_height + gp.Style.LabelPadding.y)), + xt->Major ? plot.XAxis.ColorTxt : plot.XAxis.ColorTxt, gp.XTicks.GetText(t)); + } + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (plot.YAxis[i].Present && !ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoTickLabels)) { + for (int t = 0; t < gp.YTicks[i].Size; t++) { + const float x_start = gp.YAxisReference[i] + (i == 0 ? (-gp.Style.LabelPadding.x - gp.YTicks[i].Ticks[t].LabelSize.x) : gp.Style.LabelPadding.x); + ImPlotTick *yt = &gp.YTicks[i].Ticks[t]; + if (yt->ShowLabel && yt->PixelPos >= plot.PlotRect.Min.y - 1 && yt->PixelPos <= plot.PlotRect.Max.y + 1) { + ImVec2 start(x_start, yt->PixelPos - 0.5f * yt->LabelSize.y); + DrawList.AddText(start, yt->Major ? plot.YAxis[i].ColorTxt : plot.YAxis[i].ColorTxt, gp.YTicks[i].GetText(t)); + } + } + } + } + ImGui::PopClipRect(); + + // clear legend + plot.LegendData.Reset(); + // push plot ID into stack + ImGui::PushID(ID); + return true; +} + +//----------------------------------------------------------------------------- +// Context Menu +//----------------------------------------------------------------------------- + +template +bool DragFloat(const char*, F*, float, F, F) { + return false; +} + +template <> +bool DragFloat(const char* label, double* v, float v_speed, double v_min, double v_max) { + return ImGui::DragScalar(label, ImGuiDataType_Double, v, v_speed, &v_min, &v_max, "%.3f", 1); +} + +template <> +bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max) { + return ImGui::DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, "%.3f", 1); +} + +inline void BeginDisabledControls(bool cond) { + if (cond) { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.25f); + } +} + +inline void EndDisabledControls(bool cond) { + if (cond) { + ImGui::PopItemFlag(); + ImGui::PopStyleVar(); + } +} + +void ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool time_allowed) { + + ImGui::PushItemWidth(75); + bool always_locked = axis.IsRangeLocked() || axis.IsAutoFitting(); + bool label = !ImHasFlag(axis.Flags, ImPlotAxisFlags_NoLabel); + bool grid = !ImHasFlag(axis.Flags, ImPlotAxisFlags_NoGridLines); + bool ticks = !ImHasFlag(axis.Flags, ImPlotAxisFlags_NoTickMarks); + bool labels = !ImHasFlag(axis.Flags, ImPlotAxisFlags_NoTickLabels); + double drag_speed = (axis.Range.Size() <= DBL_EPSILON) ? DBL_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits. + + if (axis.IsTime()) { + ImPlotTime tmin = ImPlotTime::FromDouble(axis.Range.Min); + ImPlotTime tmax = ImPlotTime::FromDouble(axis.Range.Max); + + BeginDisabledControls(always_locked); + ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin); + EndDisabledControls(always_locked); + ImGui::SameLine(); + BeginDisabledControls(axis.IsLockedMin() || always_locked); + if (ImGui::BeginMenu("Min Time")) { + if (ShowTimePicker("mintime", &tmin)) { + if (tmin >= tmax) + tmax = AddTime(tmin, ImPlotTimeUnit_S, 1); + axis.SetRange(tmin.ToDouble(),tmax.ToDouble()); + } + ImGui::Separator(); + if (ShowDatePicker("mindate",&axis.PickerLevel,&axis.PickerTimeMin,&tmin,&tmax)) { + tmin = CombineDateTime(axis.PickerTimeMin, tmin); + if (tmin >= tmax) + tmax = AddTime(tmin, ImPlotTimeUnit_S, 1); + axis.SetRange(tmin.ToDouble(), tmax.ToDouble()); + } + ImGui::EndMenu(); + } + EndDisabledControls(axis.IsLockedMin() || always_locked); + + BeginDisabledControls(always_locked); + ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax); + EndDisabledControls(always_locked); + ImGui::SameLine(); + BeginDisabledControls(axis.IsLockedMax() || always_locked); + if (ImGui::BeginMenu("Max Time")) { + if (ShowTimePicker("maxtime", &tmax)) { + if (tmax <= tmin) + tmin = AddTime(tmax, ImPlotTimeUnit_S, -1); + axis.SetRange(tmin.ToDouble(),tmax.ToDouble()); + } + ImGui::Separator(); + if (ShowDatePicker("maxdate",&axis.PickerLevel,&axis.PickerTimeMax,&tmin,&tmax)) { + tmax = CombineDateTime(axis.PickerTimeMax, tmax); + if (tmax <= tmin) + tmin = AddTime(tmax, ImPlotTimeUnit_S, -1); + axis.SetRange(tmin.ToDouble(), tmax.ToDouble()); + } + ImGui::EndMenu(); + } + EndDisabledControls(axis.IsLockedMax() || always_locked); + } + else { + BeginDisabledControls(always_locked); + ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin); + EndDisabledControls(always_locked); + ImGui::SameLine(); + BeginDisabledControls(axis.IsLockedMin() || always_locked); + double temp_min = axis.Range.Min; + if (DragFloat("Min", &temp_min, (float)drag_speed, -HUGE_VAL, axis.Range.Max - DBL_EPSILON)) { + axis.SetMin(temp_min); + if (equal_axis != NULL) + equal_axis->SetAspect(axis.GetAspect()); + } + EndDisabledControls(axis.IsLockedMin() || always_locked); + + BeginDisabledControls(always_locked); + ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax); + EndDisabledControls(always_locked); + ImGui::SameLine(); + BeginDisabledControls(axis.IsLockedMax() || always_locked); + double temp_max = axis.Range.Max; + if (DragFloat("Max", &temp_max, (float)drag_speed, axis.Range.Min + DBL_EPSILON, HUGE_VAL)) { + axis.SetMax(temp_max); + if (equal_axis != NULL) + equal_axis->SetAspect(axis.GetAspect()); + } + EndDisabledControls(axis.IsLockedMax() || always_locked); + } + + ImGui::Separator(); + + ImGui::CheckboxFlags("Auto-Fit",(unsigned int*)&axis.Flags, ImPlotAxisFlags_AutoFit); + ImGui::CheckboxFlags("Invert",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Invert); + BeginDisabledControls(axis.IsTime() && time_allowed); + ImGui::CheckboxFlags("Log Scale",(unsigned int*)&axis.Flags, ImPlotAxisFlags_LogScale); + EndDisabledControls(axis.IsTime() && time_allowed); + + if (time_allowed) { + BeginDisabledControls(axis.IsLog()); + ImGui::CheckboxFlags("Time",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Time); + EndDisabledControls(axis.IsLog()); + } + + ImGui::Separator(); + if (ImGui::Checkbox("Label", &label)) + ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoLabel); + if (ImGui::Checkbox("Grid Lines", &grid)) + ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoGridLines); + if (ImGui::Checkbox("Tick Marks", &ticks)) + ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickMarks); + if (ImGui::Checkbox("Tick Labels", &labels)) + ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickLabels); +} + +void ShowPlotContextMenu(ImPlotPlot& plot) { + const bool equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal); + if (ImGui::BeginMenu("X-Axis")) { + ImGui::PushID("X"); + ShowAxisContextMenu(plot.XAxis, equal ? &plot.YAxis[0] : NULL, true); + ImGui::PopID(); + ImGui::EndMenu(); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (i == 1 && !ImHasFlag(plot.Flags, ImPlotFlags_YAxis2)) { + continue; + } + if (i == 2 && !ImHasFlag(plot.Flags, ImPlotFlags_YAxis3)) { + continue; + } + char buf[10] = {}; + if (i == 0) { + snprintf(buf, sizeof(buf) - 1, "Y-Axis"); + } else { + snprintf(buf, sizeof(buf) - 1, "Y-Axis %d", i + 1); + } + if (ImGui::BeginMenu(buf)) { + ImGui::PushID(i); + ShowAxisContextMenu(plot.YAxis[i], (equal && i == 0) ? &plot.XAxis : NULL, false); + ImGui::PopID(); + ImGui::EndMenu(); + } + } + + ImGui::Separator(); + if ((ImGui::BeginMenu("Settings"))) { + if (ImGui::MenuItem("Anti-Aliased Lines",NULL,ImHasFlag(plot.Flags, ImPlotFlags_AntiAliased))) + ImFlipFlag(plot.Flags, ImPlotFlags_AntiAliased); + if (ImGui::MenuItem("Equal", NULL, ImHasFlag(plot.Flags, ImPlotFlags_Equal))) + ImFlipFlag(plot.Flags, ImPlotFlags_Equal); + if (ImGui::MenuItem("Box Select",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect))) + ImFlipFlag(plot.Flags, ImPlotFlags_NoBoxSelect); + if (ImGui::MenuItem("Query",NULL,ImHasFlag(plot.Flags, ImPlotFlags_Query))) + ImFlipFlag(plot.Flags, ImPlotFlags_Query); + if (ImGui::MenuItem("Title",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoTitle))) + ImFlipFlag(plot.Flags, ImPlotFlags_NoTitle); + if (ImGui::MenuItem("Mouse Position",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoMousePos))) + ImFlipFlag(plot.Flags, ImPlotFlags_NoMousePos); + if (ImGui::MenuItem("Crosshairs",NULL,ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs))) + ImFlipFlag(plot.Flags, ImPlotFlags_Crosshairs); + if ((ImGui::BeginMenu("Legend"))) { + const float s = ImGui::GetFrameHeight(); + if (ImGui::RadioButton("H", plot.LegendOrientation == ImPlotOrientation_Horizontal)) + plot.LegendOrientation = ImPlotOrientation_Horizontal; + ImGui::SameLine(); + if (ImGui::RadioButton("V", plot.LegendOrientation == ImPlotOrientation_Vertical)) + plot.LegendOrientation = ImPlotOrientation_Vertical; + ImGui::Checkbox("Outside", &plot.LegendOutside); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(1,1)); + if (ImGui::Button("##NW",ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_NorthWest; } ImGui::SameLine(); + if (ImGui::Button("##N", ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_North; } ImGui::SameLine(); + if (ImGui::Button("##NE",ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_NorthEast; } + if (ImGui::Button("##W", ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_West; } ImGui::SameLine(); + if (ImGui::Button("##C", ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_Center; } ImGui::SameLine(); + if (ImGui::Button("##E", ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_East; } + if (ImGui::Button("##SW",ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_SouthWest; } ImGui::SameLine(); + if (ImGui::Button("##S", ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_South; } ImGui::SameLine(); + if (ImGui::Button("##SE",ImVec2(1.5f*s,s))) { plot.LegendLocation = ImPlotLocation_SouthEast; } + ImGui::PopStyleVar(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Legend",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend))) { + ImFlipFlag(plot.Flags, ImPlotFlags_NoLegend); + } +} + +//----------------------------------------------------------------------------- +// EndPlot() +//----------------------------------------------------------------------------- + +void EndPlot() { + IM_ASSERT_USER_ERROR(GImPlot != NULL, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?"); + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "Mismatched BeginPlot()/EndPlot()!"); + ImGuiContext &G = *GImGui; + ImPlotPlot &plot = *gp.CurrentPlot; + ImGuiWindow * Window = G.CurrentWindow; + ImDrawList & DrawList = *Window->DrawList; + const ImGuiIO & IO = ImGui::GetIO(); + + // AXIS STATES ------------------------------------------------------------ + + const bool any_y_locked = plot.YAxis[0].IsInputLocked() || plot.YAxis[1].Present ? plot.YAxis[1].IsInputLocked() : false || plot.YAxis[2].Present ? plot.YAxis[2].IsInputLocked() : false; + const bool any_y_dragging = plot.YAxis[0].Dragging || plot.YAxis[1].Dragging || plot.YAxis[2].Dragging; + + + // FINAL RENDER ----------------------------------------------------------- + + // render ticks + PushPlotClipRect(); + if (!ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_NoTickMarks)) { + for (int t = 0; t < gp.XTicks.Size; t++) { + ImPlotTick *xt = &gp.XTicks.Ticks[t]; + if (xt->Level == 0) + DrawList.AddLine(ImVec2(xt->PixelPos, plot.PlotRect.Max.y), + ImVec2(xt->PixelPos, plot.PlotRect.Max.y - (xt->Major ? gp.Style.MajorTickLen.x : gp.Style.MinorTickLen.x)), + plot.XAxis.ColorMaj, + xt->Major ? gp.Style.MajorTickSize.x : gp.Style.MinorTickSize.x); + } + } + PopPlotClipRect(); + + ImGui::PushClipRect(plot.PlotRect.Min, ImVec2(plot.FrameRect.Max.x, plot.PlotRect.Max.y), true); + int axis_count = 0; + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (!plot.YAxis[i].Present) { continue; } + axis_count++; + + float x_start = gp.YAxisReference[i]; + if (!ImHasFlag(plot.YAxis[i].Flags, ImPlotAxisFlags_NoTickMarks)) { + float direction = (i == 0) ? 1.0f : -1.0f; + bool no_major = axis_count >= 3; + for (int t = 0; t < gp.YTicks[i].Size; t++) { + ImPlotTick *yt = &gp.YTicks[i].Ticks[t]; + ImVec2 start = ImVec2(x_start, yt->PixelPos); + DrawList.AddLine(start, + start + ImVec2(direction * ((!no_major && yt->Major) ? gp.Style.MajorTickLen.y : gp.Style.MinorTickLen.y), 0), + plot.YAxis[i].ColorMaj, + (!no_major && yt->Major) ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y); + } + } + + if (axis_count >= 3) { + // Draw a bar next to the ticks to act as a visual separator. + DrawList.AddLine( + ImVec2(x_start, plot.PlotRect.Min.y), + ImVec2(x_start, plot.PlotRect.Max.y), + GetStyleColorU32(ImPlotCol_YAxisGrid3), 1); + } + } + ImGui::PopClipRect(); + + // render annotations + PushPlotClipRect(); + for (int i = 0; i < gp.Annotations.Size; ++i) { + const char* txt = gp.Annotations.GetText(i); + ImPlotAnnotation& an = gp.Annotations.Annotations[i]; + const ImVec2 txt_size = ImGui::CalcTextSize(txt); + const ImVec2 size = txt_size + gp.Style.AnnotationPadding * 2; + ImVec2 pos = an.Pos; + if (an.Offset.x == 0) + pos.x -= size.x / 2; + else if (an.Offset.x > 0) + pos.x += an.Offset.x; + else + pos.x -= size.x - an.Offset.x; + if (an.Offset.y == 0) + pos.y -= size.y / 2; + else if (an.Offset.y > 0) + pos.y += an.Offset.y; + else + pos.y -= size.y - an.Offset.y; + if (an.Clamp) + pos = ClampLabelPos(pos, size, plot.PlotRect.Min, plot.PlotRect.Max); + ImRect rect(pos,pos+size); + if (an.Offset.x != 0 || an.Offset.y != 0) { + ImVec2 corners[4] = {rect.GetTL(), rect.GetTR(), rect.GetBR(), rect.GetBL()}; + int min_corner = 0; + float min_len = FLT_MAX; + for (int c = 0; c < 4; ++c) { + float len = ImLengthSqr(an.Pos - corners[c]); + if (len < min_len) { + min_corner = c; + min_len = len; + } + } + DrawList.AddLine(an.Pos, corners[min_corner], an.ColorBg); + } + DrawList.AddRectFilled(rect.Min, rect.Max, an.ColorBg); + DrawList.AddText(pos + gp.Style.AnnotationPadding, an.ColorFg, txt); + } + + // render selection/query + if (plot.Selecting) { + const ImRect select_bb(ImMin(IO.MousePos, plot.SelectStart), ImMax(IO.MousePos, plot.SelectStart)); + const bool wide_enough = ImFabs(select_bb.GetWidth()) > 2; + const bool tall_enough = ImFabs(select_bb.GetHeight()) > 2; + const bool big_enough = wide_enough && tall_enough; + if (plot.Selecting && !plot.IsInputLocked() && !ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect)) { + const ImVec4 col = GetStyleColorVec4(ImPlotCol_Selection); + const ImU32 col_bg = ImGui::GetColorU32(col * ImVec4(1,1,1,0.25f)); + const ImU32 col_bd = ImGui::GetColorU32(col); + if (IO.KeyMods == (gp.InputMap.HorizontalMod | gp.InputMap.VerticalMod) && big_enough) { + DrawList.AddRectFilled(plot.PlotRect.Min, plot.PlotRect.Max, col_bg); + DrawList.AddRect( plot.PlotRect.Min, plot.PlotRect.Max, col_bd); + } + else if ((plot.XAxis.IsInputLocked() || IO.KeyMods == gp.InputMap.HorizontalMod) && tall_enough) { + DrawList.AddRectFilled(ImVec2(plot.PlotRect.Min.x, select_bb.Min.y), ImVec2(plot.PlotRect.Max.x, select_bb.Max.y), col_bg); + DrawList.AddRect( ImVec2(plot.PlotRect.Min.x, select_bb.Min.y), ImVec2(plot.PlotRect.Max.x, select_bb.Max.y), col_bd); + } + else if ((any_y_locked || IO.KeyMods == gp.InputMap.VerticalMod) && wide_enough) { + DrawList.AddRectFilled(ImVec2(select_bb.Min.x, plot.PlotRect.Min.y), ImVec2(select_bb.Max.x, plot.PlotRect.Max.y), col_bg); + DrawList.AddRect( ImVec2(select_bb.Min.x, plot.PlotRect.Min.y), ImVec2(select_bb.Max.x, plot.PlotRect.Max.y), col_bd); + } + else if (big_enough) { + DrawList.AddRectFilled(select_bb.Min, select_bb.Max, col_bg); + DrawList.AddRect( select_bb.Min, select_bb.Max, col_bd); + } + } + } + + if (ImHasFlag(plot.Flags, ImPlotFlags_Query)) // draw query rect only when query enabled. + { + const ImVec4 col = GetStyleColorVec4(ImPlotCol_Query); + const ImU32 col_bd = ImGui::GetColorU32(col * ImVec4(1,1,1,0.25f)); + const ImU32 col_bg = ImGui::GetColorU32(col); + if (plot.Querying || plot.Queried) { + if (plot.QueryRect.GetWidth() > 2 && plot.QueryRect.GetHeight() > 2) { + DrawList.AddRectFilled(plot.QueryRect.Min + plot.PlotRect.Min, plot.QueryRect.Max + plot.PlotRect.Min, col_bd); + DrawList.AddRect( plot.QueryRect.Min + plot.PlotRect.Min, plot.QueryRect.Max + plot.PlotRect.Min, col_bg); + } + } + else if (plot.Queried) { + ImRect bb_query = plot.QueryRect; + bb_query.Min += plot.PlotRect.Min; + bb_query.Max += plot.PlotRect.Min; + DrawList.AddRectFilled(bb_query.Min, bb_query.Max, col_bd); + DrawList.AddRect( bb_query.Min, bb_query.Max, col_bg); + } + } + + // render crosshairs + if (ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs) && plot.PlotHovered && plot.FrameHovered && + !(plot.XAxis.Dragging || any_y_dragging) && !plot.Selecting && !plot.Querying && !plot.LegendHovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_None); + ImVec2 xy = IO.MousePos; + ImVec2 h1(plot.PlotRect.Min.x, xy.y); + ImVec2 h2(xy.x - 5, xy.y); + ImVec2 h3(xy.x + 5, xy.y); + ImVec2 h4(plot.PlotRect.Max.x, xy.y); + ImVec2 v1(xy.x, plot.PlotRect.Min.y); + ImVec2 v2(xy.x, xy.y - 5); + ImVec2 v3(xy.x, xy.y + 5); + ImVec2 v4(xy.x, plot.PlotRect.Max.y); + ImU32 col = GetStyleColorU32(ImPlotCol_Crosshairs); + DrawList.AddLine(h1, h2, col); + DrawList.AddLine(h3, h4, col); + DrawList.AddLine(v1, v2, col); + DrawList.AddLine(v3, v4, col); + } + + // render mouse pos (TODO: use LabelAxisValue) + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMousePos) && plot.PlotHovered) { + char buffer[128] = {}; + ImBufferWriter writer(buffer, sizeof(buffer)); + + // x + if (ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_LogScale)) { + writer.Write("%.3E", gp.MousePos[0].x); + } + else if (ImHasFlag(plot.XAxis.Flags, ImPlotAxisFlags_Time)) { + ImPlotTimeUnit unit = GetUnitForRange(plot.XAxis.Range.Size() / (plot.PlotRect.GetWidth() / 100)); + const int written = FormatDateTime(ImPlotTime::FromDouble(gp.MousePos[0].x), &writer.Buffer[writer.Pos], writer.Size - writer.Pos - 1, GetDateTimeFmt(TimeFormatMouseCursor, unit)); + if (written > 0) + writer.Pos += ImMin(written, writer.Size - writer.Pos - 1); + } + else { + double range_x = gp.XTicks.Size > 1 ? (gp.XTicks.Ticks[1].PlotPos - gp.XTicks.Ticks[0].PlotPos) : plot.XAxis.Range.Size(); + writer.Write("%.*f", Precision(range_x), gp.MousePos[0].x); + } + // y1 + if (ImHasFlag(plot.YAxis[0].Flags, ImPlotAxisFlags_LogScale)) { + writer.Write(",%.3E", gp.MousePos[0].y); + } + else { + double range_y = gp.YTicks[0].Size > 1 ? (gp.YTicks[0].Ticks[1].PlotPos - gp.YTicks[0].Ticks[0].PlotPos) : plot.YAxis[0].Range.Size(); + writer.Write(",%.*f", Precision(range_y), gp.MousePos[0].y); + } + // y2 + if (ImHasFlag(plot.Flags, ImPlotFlags_YAxis2)) { + if (ImHasFlag(plot.YAxis[1].Flags, ImPlotAxisFlags_LogScale)) { + writer.Write(",(%.3E)", gp.MousePos[1].y); + } + else { + double range_y = gp.YTicks[1].Size > 1 ? (gp.YTicks[1].Ticks[1].PlotPos - gp.YTicks[1].Ticks[0].PlotPos) : plot.YAxis[1].Range.Size(); + writer.Write(",(%.*f)", Precision(range_y), gp.MousePos[1].y); + } + } + // y3 + if (ImHasFlag(plot.Flags, ImPlotFlags_YAxis3)) { + if (ImHasFlag(plot.YAxis[2].Flags, ImPlotAxisFlags_LogScale)) { + writer.Write(",(%.3E)", gp.MousePos[2].y); + } + else { + double range_y = gp.YTicks[2].Size > 1 ? (gp.YTicks[2].Ticks[1].PlotPos - gp.YTicks[2].Ticks[0].PlotPos) : plot.YAxis[2].Range.Size(); + writer.Write(",(%.*f)", Precision(range_y), gp.MousePos[2].y); + } + } + const ImVec2 size = ImGui::CalcTextSize(buffer); + const ImVec2 pos = GetLocationPos(plot.PlotRect, size, plot.MousePosLocation, gp.Style.MousePosPadding); + DrawList.AddText(pos, GetStyleColorU32(ImPlotCol_InlayText), buffer); + } + PopPlotClipRect(); + + // reset legend hovers + plot.LegendHovered = false; + for (int i = 0; i < plot.Items.GetSize(); ++i) + plot.Items.GetByIndex(i)->LegendHovered = false; + // render legend + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.GetLegendCount() > 0) { + const ImVec2 legend_size = CalcLegendSize(plot, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, plot.LegendOrientation); + const ImVec2 legend_pos = GetLocationPos(plot.LegendOutside ? plot.FrameRect : plot.PlotRect, + legend_size, + plot.LegendLocation, + plot.LegendOutside ? gp.Style.PlotPadding : gp.Style.LegendPadding); + plot.LegendRect = ImRect(legend_pos, legend_pos + legend_size); + // test hover + plot.LegendHovered = plot.FrameHovered && plot.LegendRect.Contains(IO.MousePos); + + if (plot.LegendOutside) + ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true); + else + PushPlotClipRect(); + ImU32 col_bg = GetStyleColorU32(ImPlotCol_LegendBg); + ImU32 col_bd = GetStyleColorU32(ImPlotCol_LegendBorder); + DrawList.AddRectFilled(plot.LegendRect.Min, plot.LegendRect.Max, col_bg); + DrawList.AddRect(plot.LegendRect.Min, plot.LegendRect.Max, col_bd); + ShowLegendEntries(plot, plot.LegendRect, plot.LegendHovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, plot.LegendOrientation, DrawList); + ImGui::PopClipRect(); + } + else { + plot.LegendRect = ImRect(); + } + if (plot.LegendFlipSideNextFrame) { + plot.LegendOutside = !plot.LegendOutside; + plot.LegendFlipSideNextFrame = false; + } + + // render border + if (gp.Style.PlotBorderSize > 0) + DrawList.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBorder), 0, ImDrawFlags_RoundCornersAll, gp.Style.PlotBorderSize); + + // FIT DATA -------------------------------------------------------------- + const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal); + if (gp.FitThisFrame && (gp.VisibleItemCount > 0 || plot.Queried)) { + if (gp.FitX) { + const double ext_size = gp.ExtentsX.Size() * 0.5; + gp.ExtentsX.Min -= ext_size * gp.Style.FitPadding.x; + gp.ExtentsX.Max += ext_size * gp.Style.FitPadding.x; + if (!plot.XAxis.IsLockedMin() && !ImNanOrInf(gp.ExtentsX.Min)) + plot.XAxis.Range.Min = (gp.ExtentsX.Min); + if (!plot.XAxis.IsLockedMax() && !ImNanOrInf(gp.ExtentsX.Max)) + plot.XAxis.Range.Max = (gp.ExtentsX.Max); + if (ImAlmostEqual(plot.XAxis.Range.Max, plot.XAxis.Range.Min)) { + plot.XAxis.Range.Max += 0.5; + plot.XAxis.Range.Min -= 0.5; + } + plot.XAxis.Constrain(); + if (axis_equal && !gp.FitY[0]) + plot.YAxis[0].SetAspect(plot.XAxis.GetAspect()); + } + for (int i = 0; i < IMPLOT_Y_AXES; i++) { + if (gp.FitY[i]) { + const double ext_size = gp.ExtentsY[i].Size() * 0.5; + gp.ExtentsY[i].Min -= ext_size * gp.Style.FitPadding.y; + gp.ExtentsY[i].Max += ext_size * gp.Style.FitPadding.y; + if (!plot.YAxis[i].IsLockedMin() && !ImNanOrInf(gp.ExtentsY[i].Min)) + plot.YAxis[i].Range.Min = (gp.ExtentsY[i].Min); + if (!plot.YAxis[i].IsLockedMax() && !ImNanOrInf(gp.ExtentsY[i].Max)) + plot.YAxis[i].Range.Max = (gp.ExtentsY[i].Max); + if (ImAlmostEqual(plot.YAxis[i].Range.Max, plot.YAxis[i].Range.Min)) { + plot.YAxis[i].Range.Max += 0.5; + plot.YAxis[i].Range.Min -= 0.5; + } + plot.YAxis[i].Constrain(); + if (i == 0 && axis_equal && !gp.FitX) + plot.XAxis.SetAspect(plot.YAxis[0].GetAspect()); + } + } + if (axis_equal && gp.FitX && gp.FitY[0]) { + double aspect = ImMax(plot.XAxis.GetAspect(), plot.YAxis[0].GetAspect()); + plot.XAxis.SetAspect(aspect); + plot.YAxis[0].SetAspect(aspect); + } + } + + // CONTEXT MENUS ----------------------------------------------------------- + + // main ctx menu + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMenus) && plot.FrameHovered && plot.PlotHovered && IO.MouseReleased[gp.InputMap.ContextMenuButton] && !plot.LegendHovered && !plot.ContextLocked) + ImGui::OpenPopup("##PlotContext"); + if (ImGui::BeginPopup("##PlotContext")) { + ShowPlotContextMenu(plot); + ImGui::EndPopup(); + } + + // x-axis ctx menu + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMenus) && plot.FrameHovered && plot.XAxis.ExtHovered && IO.MouseReleased[gp.InputMap.ContextMenuButton] && !plot.LegendHovered && !plot.ContextLocked) + ImGui::OpenPopup("##XContext"); + if (ImGui::BeginPopup("##XContext")) { + ImGui::Text("X-Axis"); ImGui::Separator(); + ShowAxisContextMenu(plot.XAxis, ImHasFlag(plot.Flags, ImPlotFlags_Equal) ? &plot.YAxis[0] : NULL, true); + ImGui::EndPopup(); + } + + // y-axes ctx menus + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + ImGui::PushID(i); + if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMenus) && plot.FrameHovered && plot.YAxis[i].ExtHovered && IO.MouseReleased[gp.InputMap.ContextMenuButton] && !plot.LegendHovered && !plot.ContextLocked) + ImGui::OpenPopup("##YContext"); + if (ImGui::BeginPopup("##YContext")) { + if (i == 0) { + ImGui::Text("Y-Axis"); ImGui::Separator(); + } + else { + ImGui::Text("Y-Axis %d", i + 1); ImGui::Separator(); + } + ShowAxisContextMenu(plot.YAxis[i], (i == 0 && ImHasFlag(plot.Flags, ImPlotFlags_Equal)) ? &plot.XAxis : NULL, false); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + + + // LINKED AXES ------------------------------------------------------------ + + PushLinkedAxis(plot.XAxis); + for (int i = 0; i < IMPLOT_Y_AXES; ++i) + PushLinkedAxis(plot.YAxis[i]); + + // CLEANUP ---------------------------------------------------------------- + + // resset context locked flag + if (plot.ContextLocked && IO.MouseReleased[gp.InputMap.BoxSelectButton]) + plot.ContextLocked = false; + + + // reset the plot items for the next frame + for (int i = 0; i < gp.CurrentPlot->Items.GetSize(); ++i) { + gp.CurrentPlot->Items.GetByIndex(i)->SeenThisFrame = false; + } + + // Pop ImGui::PushID at the end of BeginPlot + ImGui::PopID(); + // Reset context for next plot + Reset(GImPlot); +} + +//----------------------------------------------------------------------------- +// MISC API +//----------------------------------------------------------------------------- + +ImPlotInputMap& GetInputMap() { + return GImPlot->InputMap; +} + +void SetNextPlotLimits(double x_min, double x_max, double y_min, double y_max, ImGuiCond cond) { + IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot == NULL, "SetNextPlotLimits() needs to be called before BeginPlot()!"); + SetNextPlotLimitsX(x_min, x_max, cond); + SetNextPlotLimitsY(y_min, y_max, cond); +} + +void SetNextPlotLimitsX(double x_min, double x_max, ImGuiCond cond) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "SetNextPlotLSetNextPlotLimitsXimitsY() needs to be called before BeginPlot()!"); + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + gp.NextPlotData.HasXRange = true; + gp.NextPlotData.XRangeCond = cond; + gp.NextPlotData.X.Min = x_min; + gp.NextPlotData.X.Max = x_max; +} + +void SetNextPlotLimitsY(double y_min, double y_max, ImGuiCond cond, ImPlotYAxis y_axis) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "SetNextPlotLimitsY() needs to be called before BeginPlot()!"); + IM_ASSERT_USER_ERROR(y_axis >= 0 && y_axis < IMPLOT_Y_AXES, "y_axis needs to be between 0 and IMPLOT_Y_AXES"); + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + gp.NextPlotData.HasYRange[y_axis] = true; + gp.NextPlotData.YRangeCond[y_axis] = cond; + gp.NextPlotData.Y[y_axis].Min = y_min; + gp.NextPlotData.Y[y_axis].Max = y_max; +} + +void LinkNextPlotLimits(double* xmin, double* xmax, double* ymin, double* ymax, double* ymin2, double* ymax2, double* ymin3, double* ymax3) { + ImPlotContext& gp = *GImPlot; + gp.NextPlotData.LinkedXmin = xmin; + gp.NextPlotData.LinkedXmax = xmax; + gp.NextPlotData.LinkedYmin[0] = ymin; + gp.NextPlotData.LinkedYmax[0] = ymax; + gp.NextPlotData.LinkedYmin[1] = ymin2; + gp.NextPlotData.LinkedYmax[1] = ymax2; + gp.NextPlotData.LinkedYmin[2] = ymin3; + gp.NextPlotData.LinkedYmax[2] = ymax3; +} + +void FitNextPlotAxes(bool x, bool y, bool y2, bool y3) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "FitNextPlotAxes() needs to be called before BeginPlot()!"); + gp.NextPlotData.FitX = x; + gp.NextPlotData.FitY[0] = y; + gp.NextPlotData.FitY[1] = y2; + gp.NextPlotData.FitY[2] = y3; +} + +void SetNextPlotTicksX(const double* values, int n_ticks, const char* const labels[], bool show_default) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "SetNextPlotTicksX() needs to be called before BeginPlot()!"); + gp.NextPlotData.ShowDefaultTicksX = show_default; + AddTicksCustom(values, labels, n_ticks, gp.XTicks); +} + +void SetNextPlotTicksX(double x_min, double x_max, int n_ticks, const char* const labels[], bool show_default) { + IM_ASSERT_USER_ERROR(n_ticks > 1, "The number of ticks must be greater than 1"); + static ImVector buffer; + FillRange(buffer, n_ticks, x_min, x_max); + SetNextPlotTicksX(&buffer[0], n_ticks, labels, show_default); +} + +void SetNextPlotTicksY(const double* values, int n_ticks, const char* const labels[], bool show_default, ImPlotYAxis y_axis) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "SetNextPlotTicksY() needs to be called before BeginPlot()!"); + IM_ASSERT_USER_ERROR(y_axis >= 0 && y_axis < IMPLOT_Y_AXES, "y_axis needs to be between 0 and IMPLOT_Y_AXES"); + gp.NextPlotData.ShowDefaultTicksY[y_axis] = show_default; + AddTicksCustom(values, labels, n_ticks, gp.YTicks[y_axis]); +} + +void SetNextPlotTicksY(double y_min, double y_max, int n_ticks, const char* const labels[], bool show_default, ImPlotYAxis y_axis) { + IM_ASSERT_USER_ERROR(n_ticks > 1, "The number of ticks must be greater than 1"); + static ImVector buffer; + FillRange(buffer, n_ticks, y_min, y_max); + SetNextPlotTicksY(&buffer[0], n_ticks, labels, show_default,y_axis); +} + +void SetPlotYAxis(ImPlotYAxis y_axis) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "SetPlotYAxis() needs to be called between BeginPlot() and EndPlot()!"); + IM_ASSERT_USER_ERROR(y_axis >= 0 && y_axis < IMPLOT_Y_AXES, "y_axis needs to be between 0 and IMPLOT_Y_AXES"); + gp.CurrentPlot->CurrentYAxis = y_axis; +} + +ImVec2 GetPlotPos() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "GetPlotPos() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->PlotRect.Min; +} + +ImVec2 GetPlotSize() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "GetPlotSize() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->PlotRect.GetSize(); +} + +ImDrawList* GetPlotDrawList() { + return ImGui::GetWindowDrawList(); +} + +void PushPlotClipRect() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PushPlotClipRect() needs to be called between BeginPlot() and EndPlot()!"); + ImGui::PushClipRect(gp.CurrentPlot->PlotRect.Min, gp.CurrentPlot->PlotRect.Max, true); +} + +void PopPlotClipRect() { + ImGui::PopClipRect(); +} + +bool IsPlotHovered() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "IsPlotHovered() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->FrameHovered && gp.CurrentPlot->PlotHovered; +} + +bool IsPlotXAxisHovered() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "IsPlotXAxisHovered() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->XAxis.ExtHovered; +} + +bool IsPlotYAxisHovered(ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(y_axis_in >= -1 && y_axis_in < IMPLOT_Y_AXES, "y_axis needs to between -1 and IMPLOT_Y_AXES"); + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "IsPlotYAxisHovered() needs to be called between BeginPlot() and EndPlot()!"); + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + return gp.CurrentPlot->YAxis[y_axis].ExtHovered; +} + +ImPlotPoint GetPlotMousePos(ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(y_axis_in >= -1 && y_axis_in < IMPLOT_Y_AXES, "y_axis needs to between -1 and IMPLOT_Y_AXES"); + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "GetPlotMousePos() needs to be called between BeginPlot() and EndPlot()!"); + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + return gp.MousePos[y_axis]; +} + + +ImPlotLimits GetPlotLimits(ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(y_axis_in >= -1 && y_axis_in < IMPLOT_Y_AXES, "y_axis needs to between -1 and IMPLOT_Y_AXES"); + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "GetPlotLimits() needs to be called between BeginPlot() and EndPlot()!"); + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + + ImPlotPlot& plot = *gp.CurrentPlot; + ImPlotLimits limits; + limits.X = plot.XAxis.Range; + limits.Y = plot.YAxis[y_axis].Range; + return limits; +} + +bool IsPlotQueried() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "IsPlotQueried() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->Queried; +} + +ImPlotLimits GetPlotQuery(ImPlotYAxis y_axis_in) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(y_axis_in >= -1 && y_axis_in < IMPLOT_Y_AXES, "y_axis needs to between -1 and IMPLOT_Y_AXES"); + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "GetPlotQuery() needs to be called between BeginPlot() and EndPlot()!"); + ImPlotPlot& plot = *gp.CurrentPlot; + const ImPlotYAxis y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis; + + UpdateTransformCache(); + ImPlotPoint p1 = PixelsToPlot(plot.QueryRect.Min + plot.PlotRect.Min, y_axis); + ImPlotPoint p2 = PixelsToPlot(plot.QueryRect.Max + plot.PlotRect.Min, y_axis); + + ImPlotLimits result; + result.X.Min = ImMin(p1.x, p2.x); + result.X.Max = ImMax(p1.x, p2.x); + result.Y.Min = ImMin(p1.y, p2.y); + result.Y.Max = ImMax(p1.y, p2.y); + return result; +} + +void AnnotateEx(double x, double y, bool clamp, const ImVec4& col, const ImVec2& off, const char* fmt, va_list args) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "Annotate() needs to be called between BeginPlot() and EndPlot()!"); + ImVec2 pos = PlotToPixels(x,y); + ImU32 bg = ImGui::GetColorU32(col); + ImU32 fg = col.w == 0 ? GetStyleColorU32(ImPlotCol_InlayText) : CalcTextColor(col); + gp.Annotations.AppendV(pos, off, bg, fg, clamp, fmt, args); +} + +void AnnotateV(double x, double y, const ImVec2& offset, const char* fmt, va_list args) { + AnnotateEx(x,y,false,ImVec4(0,0,0,0),offset,fmt,args); +} + +void Annotate(double x, double y, const ImVec2& offset, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + AnnotateV(x,y,offset,fmt,args); + va_end(args); +} + +void AnnotateV(double x, double y, const ImVec2& offset, const ImVec4& col, const char* fmt, va_list args) { + AnnotateEx(x,y,false,col,offset,fmt,args); +} + +void Annotate(double x, double y, const ImVec2& offset, const ImVec4& col, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + AnnotateV(x,y,offset,col,fmt,args); + va_end(args); +} + +void AnnotateClampedV(double x, double y, const ImVec2& offset, const char* fmt, va_list args) { + AnnotateEx(x,y,true,ImVec4(0,0,0,0),offset,fmt,args); +} + +void AnnotateClamped(double x, double y, const ImVec2& offset, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + AnnotateClampedV(x,y,offset,fmt,args); + va_end(args); +} + +void AnnotateClampedV(double x, double y, const ImVec2& offset, const ImVec4& col, const char* fmt, va_list args) { + AnnotateEx(x,y,true,col,offset,fmt,args); +} + +void AnnotateClamped(double x, double y, const ImVec2& offset, const ImVec4& col, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + AnnotateClampedV(x,y,offset,col,fmt,args); + va_end(args); +} + +bool DragLineX(const char* id, double* value, bool show_label, const ImVec4& col, float thickness) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "DragLineX() needs to be called between BeginPlot() and EndPlot()!"); + const float grab_size = ImMax(5.0f, thickness); + float yt = gp.CurrentPlot->PlotRect.Min.y; + float yb = gp.CurrentPlot->PlotRect.Max.y; + float x = IM_ROUND(PlotToPixels(*value,0).x); + const bool outside = x < (gp.CurrentPlot->PlotRect.Min.x - grab_size / 2) || x > (gp.CurrentPlot->PlotRect.Max.x + grab_size / 2); + if (outside) + return false; + float len = gp.Style.MajorTickLen.x; + ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col; + ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color); + ImDrawList& DrawList = *GetPlotDrawList(); + PushPlotClipRect(); + DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yb), col32, thickness); + DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yt+len), col32, 3*thickness); + DrawList.AddLine(ImVec2(x,yb), ImVec2(x,yb-len), col32, 3*thickness); + PopPlotClipRect(); + if (gp.CurrentPlot->Selecting || gp.CurrentPlot->Querying) + return false; + ImVec2 old_cursor_pos = ImGui::GetCursorScreenPos(); + ImVec2 new_cursor_pos = ImVec2(x - grab_size / 2.0f, yt); + ImGui::GetCurrentWindow()->DC.CursorPos = new_cursor_pos; + ImGui::InvisibleButton(id, ImVec2(grab_size, yb-yt)); + ImGui::GetCurrentWindow()->DC.CursorPos = old_cursor_pos; + if (ImGui::IsItemHovered() || ImGui::IsItemActive()) { + gp.CurrentPlot->PlotHovered = false; + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + if (show_label) { + char buff[32]; + LabelAxisValue(gp.CurrentPlot->XAxis, gp.XTicks, *value, buff, 32); + gp.Annotations.Append(ImVec2(x,yb),ImVec2(0,0),col32,CalcTextColor(color),true,"%s = %s", id, buff); + } + } + bool dragging = false; + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { + *value = ImPlot::GetPlotMousePos().x; + *value = ImClamp(*value, gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max); + dragging = true; + } + return dragging; +} + +bool DragLineY(const char* id, double* value, bool show_label, const ImVec4& col, float thickness) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "DragLineY() needs to be called between BeginPlot() and EndPlot()!"); + const float grab_size = ImMax(5.0f, thickness); + float xl = gp.CurrentPlot->PlotRect.Min.x; + float xr = gp.CurrentPlot->PlotRect.Max.x; + float y = IM_ROUND(PlotToPixels(0, *value).y); + const bool outside = y < (gp.CurrentPlot->PlotRect.Min.y - grab_size / 2) || y > (gp.CurrentPlot->PlotRect.Max.y + grab_size / 2); + if (outside) + return false; + float len = gp.Style.MajorTickLen.y; + ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col; + ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color); + ImDrawList& DrawList = *GetPlotDrawList(); + PushPlotClipRect(); + DrawList.AddLine(ImVec2(xl,y), ImVec2(xr,y), col32, thickness); + DrawList.AddLine(ImVec2(xl,y), ImVec2(xl+len,y), col32, 3*thickness); + DrawList.AddLine(ImVec2(xr,y), ImVec2(xr-len,y), col32, 3*thickness); + PopPlotClipRect(); + if (gp.CurrentPlot->Selecting || gp.CurrentPlot->Querying) + return false; + ImVec2 old_cursor_pos = ImGui::GetCursorScreenPos(); + ImVec2 new_cursor_pos = ImVec2(xl, y - grab_size / 2.0f); + ImGui::SetItemAllowOverlap(); + ImGui::GetCurrentWindow()->DC.CursorPos = new_cursor_pos; + ImGui::InvisibleButton(id, ImVec2(xr - xl, grab_size)); + ImGui::GetCurrentWindow()->DC.CursorPos = old_cursor_pos; + int yax = GetCurrentYAxis(); + if (ImGui::IsItemHovered() || ImGui::IsItemActive()) { + gp.CurrentPlot->PlotHovered = false; + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); + if (show_label) { + char buff[32]; + LabelAxisValue(gp.CurrentPlot->YAxis[yax], gp.YTicks[yax], *value, buff, 32); + gp.Annotations.Append(ImVec2(yax == 0 ? xl : xr,y), ImVec2(0,0), col32, CalcTextColor(color), true, "%s = %s", id, buff); + } + } + bool dragging = false; + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { + *value = ImPlot::GetPlotMousePos().y; + *value = ImClamp(*value, gp.CurrentPlot->YAxis[yax].Range.Min, gp.CurrentPlot->YAxis[yax].Range.Max); + dragging = true; + } + return dragging; +} + +bool DragPoint(const char* id, double* x, double* y, bool show_label, const ImVec4& col, float radius) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "DragPoint() needs to be called between BeginPlot() and EndPlot()!"); + const float grab_size = ImMax(5.0f, 2*radius); + const bool outside = !GetPlotLimits().Contains(*x,*y); + if (outside) + return false; + ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col; + ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color); + ImDrawList& DrawList = *GetPlotDrawList(); + ImVec2 pos = PlotToPixels(*x,*y); + PushPlotClipRect(); + DrawList.AddCircleFilled(pos, radius, col32); + PopPlotClipRect(); + int yax = GetCurrentYAxis(); + ImVec2 old_cursor_pos = ImGui::GetCursorScreenPos(); + ImVec2 new_cursor_pos = ImVec2(pos - ImVec2(grab_size,grab_size)*0.5f); + ImGui::GetCurrentWindow()->DC.CursorPos = new_cursor_pos; + ImGui::InvisibleButton(id, ImVec2(grab_size, grab_size)); + ImGui::GetCurrentWindow()->DC.CursorPos = old_cursor_pos; + if (ImGui::IsItemHovered() || ImGui::IsItemActive()) { + gp.CurrentPlot->PlotHovered = false; + // ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); + if (show_label) { + ImVec2 label_pos = pos + ImVec2(16 * GImGui->Style.MouseCursorScale, 8 * GImGui->Style.MouseCursorScale); + char buff1[32]; + char buff2[32]; + LabelAxisValue(gp.CurrentPlot->XAxis, gp.XTicks, *x, buff1, 32); + LabelAxisValue(gp.CurrentPlot->YAxis[yax], gp.YTicks[yax], *y, buff2, 32); + gp.Annotations.Append(label_pos, ImVec2(0.0001f,0.00001f), col32, CalcTextColor(color), true, "%s = %s,%s", id, buff1, buff2); + } + } + bool dragging = false; + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { + *x = ImPlot::GetPlotMousePos().x; + *y = ImPlot::GetPlotMousePos().y; + *x = ImClamp(*x, gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max); + *y = ImClamp(*y, gp.CurrentPlot->YAxis[yax].Range.Min, gp.CurrentPlot->YAxis[yax].Range.Max); + dragging = true; + } + return dragging; +} + +//----------------------------------------------------------------------------- + +#define IMPLOT_ID_PLT 10030910 +#define IMPLOT_ID_LEG 10030911 +#define IMPLOT_ID_XAX 10030912 +#define IMPLOT_ID_YAX 10030913 + +bool BeginDragDropTargetEx(int id, const ImRect& rect) { + ImGuiContext& G = *GImGui; + const ImGuiID ID = G.CurrentWindow->GetID(id); + if (ImGui::ItemAdd(rect, ID, &rect) && + ImGui::BeginDragDropTarget()) + return true; + return false; +} + +bool BeginDragDropTarget() { + return BeginDragDropTargetEx(IMPLOT_ID_PLT, GImPlot->CurrentPlot->PlotRect); +} + +bool BeginDragDropTargetX() { + return BeginDragDropTargetEx(IMPLOT_ID_XAX, GImPlot->CurrentPlot->XAxis.HoverRect); +} + +bool BeginDragDropTargetY(ImPlotYAxis axis) { + return BeginDragDropTargetEx(IMPLOT_ID_YAX + axis, GImPlot->CurrentPlot->YAxis[axis].HoverRect); +} + +bool BeginDragDropTargetLegend() { + return !ImHasFlag(GImPlot->CurrentPlot->Flags,ImPlotFlags_NoLegend) && + BeginDragDropTargetEx(IMPLOT_ID_LEG, GImPlot->CurrentPlot->LegendRect); +} + +void EndDragDropTarget() { + ImGui::EndDragDropTarget(); +} + +bool BeginDragDropSourceEx(ImGuiID source_id, bool is_hovered, ImGuiDragDropFlags flags, ImGuiKeyModFlags key_mods) { + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiMouseButton mouse_button = ImGuiMouseButton_Left; + + if (g.IO.MouseDown[mouse_button] == false) { + if (g.ActiveId == source_id) + ImGui::ClearActiveID(); + return false; + } + + if (is_hovered && g.IO.MouseClicked[mouse_button] && g.IO.KeyMods == key_mods) { + ImGui::SetActiveID(source_id, window); + ImGui::FocusWindow(window); + } + + if (g.ActiveId != source_id) { + return false; + } + + g.ActiveIdAllowOverlap = is_hovered; + g.ActiveIdUsingNavDirMask = ~(ImU32)0; + g.ActiveIdUsingNavInputMask = ~(ImU32)0; + g.ActiveIdUsingKeyInputMask = ~(ImU64)0; + + if (ImGui::IsMouseDragging(mouse_button)) { + + if (!g.DragDropActive) { + ImGui::ClearDragDrop(); + ImGuiPayload& payload = g.DragDropPayload; + payload.SourceId = source_id; + payload.SourceParentId = 0; + g.DragDropActive = true; + g.DragDropSourceFlags = 0; + g.DragDropMouseButton = mouse_button; + } + g.DragDropSourceFrameCount = g.FrameCount; + g.DragDropWithinSource = true; + + if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { + ImGui::BeginTooltip(); + if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) { + ImGuiWindow* tooltip_window = g.CurrentWindow; + tooltip_window->SkipItems = true; + tooltip_window->HiddenFramesCanSkipItems = 1; + } + } + return true; + } + return false; +} + +bool BeginDragDropSource(ImGuiKeyModFlags key_mods, ImGuiDragDropFlags flags) { + if (ImGui::GetIO().KeyMods == key_mods) { + GImPlot->CurrentPlot->XAxis.Dragging = false; + for (int i = 0; i < IMPLOT_Y_AXES; ++i) + GImPlot->CurrentPlot->YAxis[i].Dragging = false; + } + const ImGuiID ID = GImGui->CurrentWindow->GetID(IMPLOT_ID_PLT); + ImRect rect = GImPlot->CurrentPlot->PlotRect; + return ImGui::ItemAdd(rect, ID, &rect) && BeginDragDropSourceEx(ID, GImPlot->CurrentPlot->PlotHovered, flags, key_mods); +} + +bool BeginDragDropSourceX(ImGuiKeyModFlags key_mods, ImGuiDragDropFlags flags) { + if (ImGui::GetIO().KeyMods == key_mods) + GImPlot->CurrentPlot->XAxis.Dragging = false; + const ImGuiID ID = GImGui->CurrentWindow->GetID(IMPLOT_ID_XAX); + ImRect rect = GImPlot->CurrentPlot->XAxis.HoverRect; + return ImGui::ItemAdd(rect, ID, &rect) && BeginDragDropSourceEx(ID, GImPlot->CurrentPlot->XAxis.ExtHovered, flags, key_mods); +} + +bool BeginDragDropSourceY(ImPlotYAxis axis, ImGuiKeyModFlags key_mods, ImGuiDragDropFlags flags) { + if (ImGui::GetIO().KeyMods == key_mods) + GImPlot->CurrentPlot->YAxis[axis].Dragging = false; + const ImGuiID ID = GImGui->CurrentWindow->GetID(IMPLOT_ID_YAX + axis); + ImRect rect = GImPlot->CurrentPlot->YAxis[axis].HoverRect; + return ImGui::ItemAdd(rect, ID, &rect) && BeginDragDropSourceEx(ID, GImPlot->CurrentPlot->YAxis[axis].ExtHovered, flags, key_mods); +} + +bool BeginDragDropSourceItem(const char* label_id, ImGuiDragDropFlags flags) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "BeginDragDropSourceItem() needs to be called between BeginPlot() and EndPlot()!"); + ImGuiID source_id = ImGui::GetID(label_id); + ImPlotItem* item = gp.CurrentPlot->Items.GetByKey(source_id); + bool is_hovered = item && item->LegendHovered; + return BeginDragDropSourceEx(source_id, is_hovered, flags, ImGuiKeyModFlags_None); +} + +void EndDragDropSource() { + ImGui::EndDragDropSource(); +} + +void ItemIcon(const ImVec4& col) { + ItemIcon(ImGui::ColorConvertFloat4ToU32(col)); +} + +void ItemIcon(ImU32 col) { + const float txt_size = ImGui::GetTextLineHeight(); + ImVec2 size(txt_size-4,txt_size); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImVec2 pos = window->DC.CursorPos; + ImGui::GetWindowDrawList()->AddRectFilled(pos + ImVec2(0,2), pos + size - ImVec2(0,2), col); + ImGui::Dummy(size); +} + +void ColormapIcon(ImPlotColormap cmap) { + ImPlotContext& gp = *GImPlot; + const float txt_size = ImGui::GetTextLineHeight(); + ImVec2 size(txt_size-4,txt_size); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImVec2 pos = window->DC.CursorPos; + ImRect rect(pos+ImVec2(0,2),pos+size-ImVec2(0,2)); + ImDrawList& DrawList = *ImGui::GetWindowDrawList(); + RenderColorBar(gp.ColormapData.GetKeys(cmap),gp.ColormapData.GetKeyCount(cmap),DrawList,rect,false,false,!gp.ColormapData.IsQual(cmap)); + ImGui::Dummy(size); +} + +//----------------------------------------------------------------------------- + +void SetLegendLocation(ImPlotLocation location, ImPlotOrientation orientation, bool outside) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "SetLegendLocation() needs to be called between BeginPlot() and EndPlot()!"); + gp.CurrentPlot->LegendLocation = location; + gp.CurrentPlot->LegendOrientation = orientation; + if (gp.CurrentPlot->LegendOutside != outside) + gp.CurrentPlot->LegendFlipSideNextFrame = true; +} + +void SetMousePosLocation(ImPlotLocation location) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "SetMousePosLocation() needs to be called between BeginPlot() and EndPlot()!"); + gp.CurrentPlot->MousePosLocation = location; +} + +bool IsLegendEntryHovered(const char* label_id) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "IsPlotItemHighlight() needs to be called between BeginPlot() and EndPlot()!"); + ImGuiID id = ImGui::GetID(label_id); + ImPlotItem* item = gp.CurrentPlot->Items.GetByKey(id); + return item && item->LegendHovered; +} + + + + + +bool BeginLegendPopup(const char* label_id, ImGuiMouseButton mouse_button) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "BeginLegendPopup() needs to be called between BeginPlot() and EndPlot()!"); + ImGuiWindow* window = GImGui->CurrentWindow; + if (window->SkipItems) + return false; + ImGuiID id = ImGui::GetID(label_id); + if (ImGui::IsMouseReleased(mouse_button)) { + ImPlotItem* item = gp.CurrentPlot->Items.GetByKey(id); + if (item && item->LegendHovered) + ImGui::OpenPopupEx(id); + } + return ImGui::BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +void EndLegendPopup() { + ImGui::EndPopup(); +} + +void ShowAltLegend(const char* title_id, ImPlotOrientation orientation, const ImVec2 size, bool interactable) { + ImPlotContext& gp = *GImPlot; + ImGuiContext &G = *GImGui; + ImGuiWindow * Window = G.CurrentWindow; + if (Window->SkipItems) + return; + ImDrawList &DrawList = *Window->DrawList; + ImPlotPlot* plot = GetPlot(title_id); + ImVec2 legend_size; + ImVec2 default_size = gp.Style.LegendPadding * 2; + if (plot != NULL) { + legend_size = CalcLegendSize(*plot, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, orientation); + default_size = legend_size + gp.Style.LegendPadding * 2; + } + ImVec2 frame_size = ImGui::CalcItemSize(size, default_size.x, default_size.y); + ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size); + ImGui::ItemSize(bb_frame); + if (!ImGui::ItemAdd(bb_frame, 0, &bb_frame)) + return; + ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding); + DrawList.PushClipRect(bb_frame.Min, bb_frame.Max, true); + if (plot != NULL) { + const ImVec2 legend_pos = GetLocationPos(bb_frame, legend_size, 0, gp.Style.LegendPadding); + const ImRect legend_bb(legend_pos, legend_pos + legend_size); + interactable = interactable && bb_frame.Contains(ImGui::GetIO().MousePos); + // render legend box + ImU32 col_bg = GetStyleColorU32(ImPlotCol_LegendBg); + ImU32 col_bd = GetStyleColorU32(ImPlotCol_LegendBorder); + DrawList.AddRectFilled(legend_bb.Min, legend_bb.Max, col_bg); + DrawList.AddRect(legend_bb.Min, legend_bb.Max, col_bd); + // render entries + ShowLegendEntries(*plot, legend_bb, interactable, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, orientation, DrawList); + } + DrawList.PopClipRect(); +} + +//----------------------------------------------------------------------------- +// STYLING +//----------------------------------------------------------------------------- + +ImPlotStyle& GetStyle() { + ImPlotContext& gp = *GImPlot; + return gp.Style; +} + +void PushStyleColor(ImPlotCol idx, ImU32 col) { + ImPlotContext& gp = *GImPlot; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = gp.Style.Colors[idx]; + gp.ColorModifiers.push_back(backup); + gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col); +} + +void PushStyleColor(ImPlotCol idx, const ImVec4& col) { + ImPlotContext& gp = *GImPlot; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = gp.Style.Colors[idx]; + gp.ColorModifiers.push_back(backup); + gp.Style.Colors[idx] = col; +} + +void PopStyleColor(int count) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) + { + ImGuiColorMod& backup = gp.ColorModifiers.back(); + gp.Style.Colors[backup.Col] = backup.BackupValue; + gp.ColorModifiers.pop_back(); + count--; + } +} + +void PushStyleVar(ImPlotStyleVar idx, float val) { + ImPlotContext& gp = *GImPlot; + const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { + float* pvar = (float*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); +} + +void PushStyleVar(ImPlotStyleVar idx, int val) { + ImPlotContext& gp = *GImPlot; + const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) { + int* pvar = (int*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { + float* pvar = (float*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = (float)val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() int variant but variable is not a int!"); +} + +void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + ImPlotContext& gp = *GImPlot; + const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) + { + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); +} + +void PopStyleVar(int count) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) { + ImGuiStyleMod& backup = gp.StyleModifiers.back(); + const ImPlotStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx); + void* data = info->GetVarPtr(&gp.Style); + if (info->Type == ImGuiDataType_Float && info->Count == 1) { + ((float*)data)[0] = backup.BackupFloat[0]; + } + else if (info->Type == ImGuiDataType_Float && info->Count == 2) { + ((float*)data)[0] = backup.BackupFloat[0]; + ((float*)data)[1] = backup.BackupFloat[1]; + } + else if (info->Type == ImGuiDataType_S32 && info->Count == 1) { + ((int*)data)[0] = backup.BackupInt[0]; + } + gp.StyleModifiers.pop_back(); + count--; + } +} + +//------------------------------------------------------------------------------ +// COLORMAPS +//------------------------------------------------------------------------------ + +ImPlotColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!"); + IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!"); + ImVector buffer; + buffer.resize(size); + for (int i = 0; i < size; ++i) + buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]); + return gp.ColormapData.Append(name, buffer.Data, size, qual); +} + +ImPlotColormap AddColormap(const char* name, const ImU32* colormap, int size, bool qual) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!"); + IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already be used!"); + return gp.ColormapData.Append(name, colormap, size, qual); +} + +int GetColormapCount() { + ImPlotContext& gp = *GImPlot; + return gp.ColormapData.Count; +} + +const char* GetColormapName(ImPlotColormap colormap) { + ImPlotContext& gp = *GImPlot; + return gp.ColormapData.GetName(colormap); +} + +ImPlotColormap GetColormapIndex(const char* name) { + ImPlotContext& gp = *GImPlot; + return gp.ColormapData.GetIndex(name); +} + +void PushColormap(ImPlotColormap colormap) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, "The colormap index is invalid!"); + gp.ColormapModifiers.push_back(gp.Style.Colormap); + gp.Style.Colormap = colormap; +} + +void PushColormap(const char* name) { + ImPlotContext& gp = *GImPlot; + ImPlotColormap idx = gp.ColormapData.GetIndex(name); + IM_ASSERT_USER_ERROR(idx != -1, "The colormap name is invalid!"); + PushColormap(idx); +} + +void PopColormap(int count) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) { + const ImPlotColormap& backup = gp.ColormapModifiers.back(); + gp.Style.Colormap = backup; + gp.ColormapModifiers.pop_back(); + count--; + } +} + +ImU32 NextColormapColorU32() { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!"); + int idx = gp.CurrentPlot->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap); + ImU32 col = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx); + gp.CurrentPlot->ColormapIdx++; + return col; +} + +ImVec4 NextColormapColor() { + return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32()); +} + +int GetColormapSize(ImPlotColormap cmap) { + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + return gp.ColormapData.GetKeyCount(gp.Style.Colormap); +} + +ImU32 GetColormapColorU32(int idx, ImPlotColormap cmap) { + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + idx = idx % gp.ColormapData.GetKeyCount(cmap); + return gp.ColormapData.GetKeyColor(cmap, idx); +} + +ImVec4 GetColormapColor(int idx, ImPlotColormap cmap) { + return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx,cmap)); +} + +ImU32 SampleColormapU32(float t, ImPlotColormap cmap) { + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + return gp.ColormapData.LerpTable(gp.Style.Colormap,t); +} + +ImVec4 SampleColormap(float t, ImPlotColormap cmap) { + return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t,cmap)); +} + +void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) { + const int n = continuous ? size - 1 : size; + ImU32 col1, col2; + if (vert) { + const float step = bounds.GetHeight() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size-i-1]; + col2 = continuous ? colors[size-i-2] : col1; + } + else { + col1 = colors[i]; + col2 = continuous ? colors[i+1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2); + rect.TranslateY(step); + } + } + else { + const float step = bounds.GetWidth() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size-i-1]; + col2 = continuous ? colors[size-i-2] : col1; + } + else { + col1 = colors[i]; + col2 = continuous ? colors[i+1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1); + rect.TranslateX(step); + } + } +} + +void ColormapScale(const char* label, double scale_min, double scale_max, const ImVec2& size, ImPlotColormap cmap) { + ImGuiContext &G = *GImGui; + ImGuiWindow * Window = G.CurrentWindow; + if (Window->SkipItems) + return; + + const ImGuiID ID = Window->GetID(label); + ImVec2 label_size(0,0); + label_size = ImGui::CalcTextSize(label,NULL,true); + + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + + ImVec2 frame_size = ImGui::CalcItemSize(size, 0, gp.Style.PlotDefaultSize.y); + if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f) + frame_size.y = gp.Style.PlotMinSize.y; + + ImPlotRange range(scale_min,scale_max); + gp.CTicks.Reset(); + AddTicksDefault(range, ImMax(2, (int)IM_ROUND(0.0025 * frame_size.y)), IMPLOT_SUB_DIV, gp.CTicks); + + const float txt_off = gp.Style.LabelPadding.x; + const float pad_right = txt_off + gp.CTicks.MaxWidth + (label_size.x > 0 ? txt_off + label_size.y : 0); + float bar_w = 20; + + if (frame_size.x == 0) + frame_size.x = bar_w + pad_right + 2 * gp.Style.PlotPadding.x; + else { + bar_w = frame_size.x - (pad_right + 2 * gp.Style.PlotPadding.x); + if (bar_w < gp.Style.MajorTickLen.y) + bar_w = gp.Style.MajorTickLen.y; + } + + ImDrawList &DrawList = *Window->DrawList; + ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size); + ImGui::ItemSize(bb_frame); + if (!ImGui::ItemAdd(bb_frame, ID, &bb_frame)) + return; + + ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding); + ImRect bb_grad(bb_frame.Min + gp.Style.PlotPadding, bb_frame.Min + ImVec2(bar_w + gp.Style.PlotPadding.x, frame_size.y - gp.Style.PlotPadding.y)); + + ImGui::PushClipRect(bb_frame.Min, bb_frame.Max, true); + RenderColorBar(gp.ColormapData.GetKeys(cmap), gp.ColormapData.GetKeyCount(cmap), DrawList, bb_grad, true, true, !gp.ColormapData.IsQual(cmap)); + const ImU32 col_tick = GetStyleColorU32(ImPlotCol_YAxis); + const ImU32 col_text = ImGui::GetColorU32(ImGuiCol_Text); + for (int i = 0; i < gp.CTicks.Size; ++i) { + const float ypos = ImRemap((float)gp.CTicks.Ticks[i].PlotPos, (float)range.Max, (float)range.Min, bb_grad.Min.y, bb_grad.Max.y); + const float tick_width = gp.CTicks.Ticks[i].Major ? gp.Style.MajorTickLen.y : gp.Style.MinorTickLen.y; + const float tick_thick = gp.CTicks.Ticks[i].Major ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y; + if (ypos < bb_grad.Max.y - 2 && ypos > bb_grad.Min.y + 2) + DrawList.AddLine(ImVec2(bb_grad.Max.x-1, ypos), ImVec2(bb_grad.Max.x - tick_width, ypos), col_tick, tick_thick); + DrawList.AddText(ImVec2(bb_grad.Max.x-1, ypos) + ImVec2(txt_off, -gp.CTicks.Ticks[i].LabelSize.y * 0.5f), col_text, gp.CTicks.GetText(i)); + } + if (label_size.x > 0) { + ImVec2 label_pos(bb_grad.Max.x - 1 + 2*txt_off + gp.CTicks.MaxWidth, bb_grad.GetCenter().y + label_size.x*0.5f ); + const char* label_end = ImGui::FindRenderedTextEnd(label); + AddTextVertical(&DrawList,label_pos,col_text,label,label_end); + } + DrawList.AddRect(bb_grad.Min, bb_grad.Max, GetStyleColorU32(ImPlotCol_PlotBorder)); + ImGui::PopClipRect(); +} + +bool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlotColormap cmap) { + *t = ImClamp(*t,0.0f,1.0f); + ImGuiContext &G = *GImGui; + ImGuiWindow * Window = G.CurrentWindow; + if (Window->SkipItems) + return false; + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + const ImU32* keys = GImPlot->ColormapData.GetKeys(cmap); + const int count = GImPlot->ColormapData.GetKeyCount(cmap); + const bool qual = GImPlot->ColormapData.IsQual(cmap); + const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; + const float w = ImGui::CalcItemWidth(); + const float h = ImGui::GetFrameHeight(); + const ImRect rect = ImRect(pos.x,pos.y,pos.x+w,pos.y+h); + RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual); + const ImU32 grab = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,*t)); + // const ImU32 text = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBg,IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive,IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered,ImVec4(1,1,1,0.1f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab,grab); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize,2); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0); + const bool changed = ImGui::SliderFloat(label,t,0,1,format); + ImGui::PopStyleColor(5); + ImGui::PopStyleVar(2); + if (out != NULL) + *out = ImGui::ColorConvertU32ToFloat4(GImPlot->ColormapData.LerpTable(cmap,*t)); + return changed; +} + +bool ColormapButton(const char* label, const ImVec2& size_arg, ImPlotColormap cmap) { + ImGuiContext &G = *GImGui; + const ImGuiStyle& style = G.Style; + ImGuiWindow * Window = G.CurrentWindow; + if (Window->SkipItems) + return false; + ImPlotContext& gp = *GImPlot; + cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + const ImU32* keys = GImPlot->ColormapData.GetKeys(cmap); + const int count = GImPlot->ColormapData.GetKeyCount(cmap); + const bool qual = GImPlot->ColormapData.IsQual(cmap); + const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; + const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + const ImRect rect = ImRect(pos.x,pos.y,pos.x+size.x,pos.y+size.y); + RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual); + const ImU32 text = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,G.Style.ButtonTextAlign.x)); + ImGui::PushStyleColor(ImGuiCol_Button,IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(1,1,1,0.1f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive,ImVec4(1,1,1,0.2f)); + ImGui::PushStyleColor(ImGuiCol_Text,text); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0); + const bool pressed = ImGui::Button(label,size); + ImGui::PopStyleColor(4); + ImGui::PopStyleVar(1); + return pressed; +} + + +//----------------------------------------------------------------------------- +// Style Editor etc. +//----------------------------------------------------------------------------- + +static void HelpMarker(const char* desc) { + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +bool ShowStyleSelector(const char* label) +{ + static int style_idx = -1; + if (ImGui::Combo(label, &style_idx, "Auto\0Classic\0Dark\0Light\0")) + { + switch (style_idx) + { + case 0: StyleColorsAuto(); break; + case 1: StyleColorsClassic(); break; + case 2: StyleColorsDark(); break; + case 3: StyleColorsLight(); break; + } + return true; + } + return false; +} + +bool ShowColormapSelector(const char* label) { + ImPlotContext& gp = *GImPlot; + bool set = false; + if (ImGui::BeginCombo(label, gp.ColormapData.GetName(gp.Style.Colormap))) { + for (int i = 0; i < gp.ColormapData.Count; ++i) { + const char* name = gp.ColormapData.GetName(i); + if (ImGui::Selectable(name, gp.Style.Colormap == i)) { + gp.Style.Colormap = i; + ImPlot::BustItemCache(); + set = true; + } + } + ImGui::EndCombo(); + } + return set; +} + +void ShowStyleEditor(ImPlotStyle* ref) { + ImPlotContext& gp = *GImPlot; + ImPlotStyle& style = GetStyle(); + static ImPlotStyle ref_saved_style; + // Default to using internal storage as reference + static bool init = true; + if (init && ref == NULL) + ref_saved_style = style; + init = false; + if (ref == NULL) + ref = &ref_saved_style; + + if (ImPlot::ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + + // Save/Revert button + if (ImGui::Button("Save Ref")) + *ref = ref_saved_style = style; + ImGui::SameLine(); + if (ImGui::Button("Revert Ref")) + style = *ref; + ImGui::SameLine(); + HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); + if (ImGui::BeginTabBar("##StyleEditor")) { + if (ImGui::BeginTabItem("Variables")) { + ImGui::Text("Item Styling"); + ImGui::SliderFloat("LineWeight", &style.LineWeight, 0.0f, 5.0f, "%.1f"); + ImGui::SliderFloat("MarkerSize", &style.MarkerSize, 2.0f, 10.0f, "%.1f"); + ImGui::SliderFloat("MarkerWeight", &style.MarkerWeight, 0.0f, 5.0f, "%.1f"); + ImGui::SliderFloat("FillAlpha", &style.FillAlpha, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat("ErrorBarSize", &style.ErrorBarSize, 0.0f, 10.0f, "%.1f"); + ImGui::SliderFloat("ErrorBarWeight", &style.ErrorBarWeight, 0.0f, 5.0f, "%.1f"); + ImGui::SliderFloat("DigitalBitHeight", &style.DigitalBitHeight, 0.0f, 20.0f, "%.1f"); + ImGui::SliderFloat("DigitalBitGap", &style.DigitalBitGap, 0.0f, 20.0f, "%.1f"); + float indent = ImGui::CalcItemWidth() - ImGui::GetFrameHeight(); + ImGui::Indent(ImGui::CalcItemWidth() - ImGui::GetFrameHeight()); + ImGui::Checkbox("AntiAliasedLines", &style.AntiAliasedLines); + ImGui::Unindent(indent); + ImGui::Text("Plot Styling"); + ImGui::SliderFloat("PlotBorderSize", &style.PlotBorderSize, 0.0f, 2.0f, "%.0f"); + ImGui::SliderFloat("MinorAlpha", &style.MinorAlpha, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat2("MajorTickLen", (float*)&style.MajorTickLen, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("MinorTickLen", (float*)&style.MinorTickLen, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("MajorTickSize", (float*)&style.MajorTickSize, 0.0f, 2.0f, "%.1f"); + ImGui::SliderFloat2("MinorTickSize", (float*)&style.MinorTickSize, 0.0f, 2.0f, "%.1f"); + ImGui::SliderFloat2("MajorGridSize", (float*)&style.MajorGridSize, 0.0f, 2.0f, "%.1f"); + ImGui::SliderFloat2("MinorGridSize", (float*)&style.MinorGridSize, 0.0f, 2.0f, "%.1f"); + ImGui::SliderFloat2("PlotDefaultSize", (float*)&style.PlotDefaultSize, 0.0f, 1000, "%.0f"); + ImGui::SliderFloat2("PlotMinSize", (float*)&style.PlotMinSize, 0.0f, 300, "%.0f"); + ImGui::Text("Plot Padding"); + ImGui::SliderFloat2("PlotPadding", (float*)&style.PlotPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LabelPadding", (float*)&style.LabelPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LegendPadding", (float*)&style.LegendPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LegendInnerPadding", (float*)&style.LegendInnerPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat2("LegendSpacing", (float*)&style.LegendSpacing, 0.0f, 5.0f, "%.0f"); + ImGui::SliderFloat2("MousePosPadding", (float*)&style.MousePosPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("AnnotationPadding", (float*)&style.AnnotationPadding, 0.0f, 5.0f, "%.0f"); + ImGui::SliderFloat2("FitPadding", (float*)&style.FitPadding, 0, 0.2f, "%.2f"); + + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Colors")) { + static int output_dest = 0; + static bool output_only_modified = false; + + if (ImGui::Button("Export", ImVec2(75,0))) { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImVec4* colors = ImPlot::GetStyle().Colors;\n"); + for (int i = 0; i < ImPlotCol_COUNT; i++) { + const ImVec4& col = style.Colors[i]; + const char* name = ImPlot::GetStyleColorName(i); + if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) { + if (IsColorAuto(i)) + ImGui::LogText("colors[ImPlotCol_%s]%*s= IMPLOT_AUTO_COL;\n",name,14 - (int)strlen(name), ""); + else + ImGui::LogText("colors[ImPlotCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n", + name, 14 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", ImGui::GetFontSize() * 16); + + static ImGuiColorEditFlags alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + HelpMarker( + "In the color list:\n" + "Left-click on colored square to open color picker,\n" + "Right-click to open edit options menu."); + ImGui::Separator(); + ImGui::PushItemWidth(-160); + for (int i = 0; i < ImPlotCol_COUNT; i++) { + const char* name = ImPlot::GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImVec4 temp = GetStyleColorVec4(i); + const bool is_auto = IsColorAuto(i); + if (!is_auto) + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f); + if (ImGui::Button("Auto")) { + if (is_auto) + style.Colors[i] = temp; + else + style.Colors[i] = IMPLOT_AUTO_COL; + BustItemCache(); + } + if (!is_auto) + ImGui::PopStyleVar(); + ImGui::SameLine(); + if (ImGui::ColorEdit4(name, &temp.x, ImGuiColorEditFlags_NoInputs | alpha_flags)) { + style.Colors[i] = temp; + BustItemCache(); + } + if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { + ImGui::SameLine(175); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } + ImGui::SameLine(); if (ImGui::Button("Revert")) { + style.Colors[i] = ref->Colors[i]; + BustItemCache(); + } + } + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::Separator(); + ImGui::Text("Colors that are set to Auto (i.e. IMPLOT_AUTO_COL) will\n" + "be automatically deduced from your ImGui style or the\n" + "current ImPlot Colormap. If you want to style individual\n" + "plot items, use Push/PopStyleColor around its function."); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Colormaps")) { + static int output_dest = 0; + if (ImGui::Button("Export", ImVec2(75,0))) { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + int size = GetColormapSize(); + const char* name = GetColormapName(gp.Style.Colormap); + ImGui::LogText("static const ImU32 %s_Data[%d] = {\n", name, size); + for (int i = 0; i < size; ++i) { + ImU32 col = GetColormapColorU32(i,gp.Style.Colormap); + ImGui::LogText(" %u%s\n", col, i == size - 1 ? "" : ","); + } + ImGui::LogText("};\nImPlotColormap %s = ImPlot::AddColormap(\"%s\", %s_Data, %d);", name, name, name, size); + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + ImGui::SameLine(); + static bool edit = false; + ImGui::Checkbox("Edit Mode",&edit); + + // built-in/added + ImGui::Separator(); + for (int i = 0; i < gp.ColormapData.Count; ++i) { + ImGui::PushID(i); + int size = gp.ColormapData.GetKeyCount(i); + bool selected = i == gp.Style.Colormap; + + const char* name = GetColormapName(i); + if (!selected) + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f); + if (ImGui::Button(name, ImVec2(100,0))) { + gp.Style.Colormap = i; + BustItemCache(); + } + if (!selected) + ImGui::PopStyleVar(); + ImGui::SameLine(); + ImGui::BeginGroup(); + if (edit) { + for (int c = 0; c < size; ++c) { + ImGui::PushID(c); + ImVec4 col4 = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetKeyColor(i,c)); + if (ImGui::ColorEdit4("",&col4.x,ImGuiColorEditFlags_NoInputs)) { + ImU32 col32 = ImGui::ColorConvertFloat4ToU32(col4); + gp.ColormapData.SetKeyColor(i,c,col32); + BustItemCache(); + } + if ((c + 1) % 12 != 0 && c != size -1) + ImGui::SameLine(); + ImGui::PopID(); + } + } + else { + if (ImPlot::ColormapButton("##",ImVec2(-1,0),i)) + edit = true; + } + ImGui::EndGroup(); + ImGui::PopID(); + } + + + static ImVector custom; + if (custom.Size == 0) { + custom.push_back(ImVec4(1,0,0,1)); + custom.push_back(ImVec4(0,1,0,1)); + custom.push_back(ImVec4(0,0,1,1)); + } + ImGui::Separator(); + ImGui::BeginGroup(); + static char name[16] = "MyColormap"; + + + if (ImGui::Button("+", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0))) + custom.push_back(ImVec4(0,0,0,1)); + ImGui::SameLine(); + if (ImGui::Button("-", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0)) && custom.Size > 2) + custom.pop_back(); + ImGui::SetNextItemWidth(100); + ImGui::InputText("##Name",name,16,ImGuiInputTextFlags_CharsNoBlank); + static bool qual = true; + ImGui::Checkbox("Qualitative",&qual); + if (ImGui::Button("Add", ImVec2(100, 0)) && gp.ColormapData.GetIndex(name)==-1) + AddColormap(name,custom.Data,custom.Size,qual); + + ImGui::EndGroup(); + ImGui::SameLine(); + ImGui::BeginGroup(); + for (int c = 0; c < custom.Size; ++c) { + ImGui::PushID(c); + if (ImGui::ColorEdit4("##Col1", &custom[c].x, ImGuiColorEditFlags_NoInputs)) { + + } + if ((c + 1) % 12 != 0) + ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::EndGroup(); + + + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } +} + +void ShowUserGuide() { + ImGui::BulletText("Left-click drag within the plot area to pan X and Y axes."); + ImGui::Indent(); + ImGui::BulletText("Left-click drag on axis labels to pan an individual axis."); + ImGui::Unindent(); + ImGui::BulletText("Scroll in the plot area to zoom both X any Y axes."); + ImGui::Indent(); + ImGui::BulletText("Scroll on axis labels to zoom an individual axis."); + ImGui::Unindent(); + ImGui::BulletText("Right-click drag to box select data."); + ImGui::Indent(); + ImGui::BulletText("Hold Alt to expand box selection horizontally."); + ImGui::BulletText("Hold Shift to expand box selection vertically."); + ImGui::BulletText("Left-click while box selecting to cancel the selection."); + ImGui::Unindent(); + ImGui::BulletText("Double left-click to fit all visible data."); + ImGui::Indent(); + ImGui::BulletText("Double left-click axis labels to fit the individual axis."); + ImGui::Unindent(); + ImGui::BulletText("Right-click open the full plot context menu."); + ImGui::Indent(); + ImGui::BulletText("Right-click axis labels to open an individual axis context menu."); + ImGui::Unindent(); + ImGui::BulletText("Click legend label icons to show/hide plot items."); +} + +void ShowAxisMetrics(ImPlotAxis* axis, bool show_axis_rects) { + ImGui::Bullet(); ImGui::Text("Flags: %d", axis->Flags); + ImGui::Bullet(); ImGui::Text("Range: [%f,%f]",axis->Range.Min, axis->Range.Max); + ImGui::Bullet(); ImGui::Text("Pixels: %f", axis->Pixels); + ImGui::Bullet(); ImGui::Text("Aspect: %f", axis->GetAspect()); + ImGui::Bullet(); ImGui::Text("Dragging: %s", axis->Dragging ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("ExtHovered: %s", axis->ExtHovered ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("AllHovered: %s", axis->AllHovered ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("Present: %s", axis->Present ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("HasRange: %s", axis->HasRange ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("LinkedMin: %p", (void*)axis->LinkedMin); + ImGui::Bullet(); ImGui::Text("LinkedMax: %p", (void*)axis->LinkedMax); + if (show_axis_rects) { + ImDrawList& fg = *ImGui::GetForegroundDrawList(); + fg.AddRect(axis->HoverRect.Min, axis->HoverRect.Max, IM_COL32(0,255,0,255)); + } +} + +void ShowMetricsWindow(bool* p_popen) { + + static bool show_plot_rects = false; + static bool show_axes_rects = false; + + ImDrawList& fg = *ImGui::GetForegroundDrawList(); + + ImPlotContext& gp = *GImPlot; + // ImGuiContext& g = *GImGui; + ImGuiIO& io = ImGui::GetIO(); + ImGui::Begin("ImPlot Metrics", p_popen); + ImGui::Text("ImPlot " IMPLOT_VERSION); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Separator(); + int n_plots = gp.Plots.GetSize(); + if (ImGui::TreeNode("Tools")) { + if (ImGui::Button("Bust Plot Cache")) + BustPlotCache(); + ImGui::SameLine(); + if (ImGui::Button("Bust Item Cache")) + BustItemCache(); + ImGui::Checkbox("Show Plot Rects", &show_plot_rects); + ImGui::Checkbox("Show Axes Rects", &show_axes_rects); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Plots","Plots (%d)", n_plots)) { + for (int p = 0; p < n_plots; ++p) { + // plot + ImPlotPlot* plot = gp.Plots.GetByIndex(p); + ImGui::PushID(p); + if (ImGui::TreeNode("Plot", "Plot [ID=%u]", plot->ID)) { + int n_items = plot->Items.GetSize(); + if (ImGui::TreeNode("Items", "Items (%d)", n_items)) { + for (int i = 0; i < n_items; ++i) { + ImPlotItem* item = plot->Items.GetByIndex(i); + ImGui::PushID(i); + if (ImGui::TreeNode("Item", "Item [ID=%u]", item->ID)) { + ImGui::Bullet(); ImGui::Checkbox("Show", &item->Show); + ImGui::Bullet(); + ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color); + if (ImGui::ColorEdit4("Color",&temp.x, ImGuiColorEditFlags_NoInputs)) + item->Color = ImGui::ColorConvertFloat4ToU32(temp); + + ImGui::Bullet(); ImGui::Text("NameOffset: %d",item->NameOffset); + ImGui::Bullet(); ImGui::Text("Name: %s", item->NameOffset != -1 ? plot->LegendData.Labels.Buf.Data + item->NameOffset : "N/A"); + ImGui::Bullet(); ImGui::Text("Hovered: %s",item->LegendHovered ? "true" : "false"); + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("X-Axis")) { + ShowAxisMetrics(&plot->XAxis, show_axes_rects); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Y-Axis")) { + ShowAxisMetrics(&plot->YAxis[0], show_axes_rects); + ImGui::TreePop(); + } + if (ImHasFlag(plot->Flags, ImPlotFlags_YAxis2) && ImGui::TreeNode("Y-Axis 2")) { + ShowAxisMetrics(&plot->YAxis[1], show_axes_rects); + ImGui::TreePop(); + } + if (ImHasFlag(plot->Flags, ImPlotFlags_YAxis3) && ImGui::TreeNode("Y-Axis 3")) { + ShowAxisMetrics(&plot->YAxis[2], show_axes_rects); + ImGui::TreePop(); + } + ImGui::Bullet(); ImGui::Text("Flags: %d", plot->Flags); + ImGui::Bullet(); ImGui::Text("Selecting: %s", plot->Selecting ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("Querying: %s", plot->Querying ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("Queried: %s", plot->Queried ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("FrameHovered: %s", plot->FrameHovered ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("PlotHovered: %s", plot->PlotHovered ? "true" : "false"); + ImGui::Bullet(); ImGui::Text("LegendHovered: %s", plot->LegendHovered ? "true" : "false"); + ImGui::TreePop(); + if (show_plot_rects) + fg.AddRect(plot->PlotRect.Min, plot->PlotRect.Max, IM_COL32(255,255,0,255)); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("Colormaps")) { + ImGui::BulletText("Colormaps: %d", gp.ColormapData.Count); + ImGui::BulletText("Memory: %d bytes", gp.ColormapData.Tables.Size * 4); + if (ImGui::TreeNode("Data")) { + for (int m = 0; m < gp.ColormapData.Count; ++m) { + if (ImGui::TreeNode(gp.ColormapData.GetName(m))) { + int count = gp.ColormapData.GetKeyCount(m); + int size = gp.ColormapData.GetTableSize(m); + bool qual = gp.ColormapData.IsQual(m); + ImGui::BulletText("Qualitative: %s", qual ? "true" : "false"); + ImGui::BulletText("Key Count: %d", count); + ImGui::BulletText("Table Size: %d", size); + ImGui::Indent(); + + static float t = 0.5; + ImVec4 samp; + float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x; + ImGui::SetNextItemWidth(wid); + ImPlot::ColormapSlider("##Sample",&t,&samp,"%.3f",m); + ImGui::SameLine(); + ImGui::ColorButton("Sampler",samp); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + for (int c = 0; c < size; ++c) { + ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m,c)); + ImGui::PushID(m*1000+c); + ImGui::ColorButton("",col,0,ImVec2(10,10)); + ImGui::PopID(); + if ((c + 1) % 32 != 0 && c != size - 1) + ImGui::SameLine(); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::Unindent(); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::End(); +} + +bool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1, const ImPlotTime* t2) { + + ImGui::PushID(id); + ImGui::BeginGroup(); + + ImGuiStyle& style = ImGui::GetStyle(); + ImVec4 col_txt = style.Colors[ImGuiCol_Text]; + ImVec4 col_dis = style.Colors[ImGuiCol_TextDisabled]; + ImVec4 col_btn = style.Colors[ImGuiCol_Button]; + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + + const float ht = ImGui::GetFrameHeight(); + ImVec2 cell_size(ht*1.25f,ht); + char buff[32]; + bool clk = false; + tm& Tm = GImPlot->Tm; + + const int min_yr = 1970; + const int max_yr = 2999; + + // t1 parts + int t1_mo = 0; int t1_md = 0; int t1_yr = 0; + if (t1 != NULL) { + GetTime(*t1,&Tm); + t1_mo = Tm.tm_mon; + t1_md = Tm.tm_mday; + t1_yr = Tm.tm_year + 1900; + } + + // t2 parts + int t2_mo = 0; int t2_md = 0; int t2_yr = 0; + if (t2 != NULL) { + GetTime(*t2,&Tm); + t2_mo = Tm.tm_mon; + t2_md = Tm.tm_mday; + t2_yr = Tm.tm_year + 1900; + } + + // day widget + if (*level == 0) { + *t = FloorTime(*t, ImPlotTimeUnit_Day); + GetTime(*t, &Tm); + const int this_year = Tm.tm_year + 1900; + const int last_year = this_year - 1; + const int next_year = this_year + 1; + const int this_mon = Tm.tm_mon; + const int last_mon = this_mon == 0 ? 11 : this_mon - 1; + const int next_mon = this_mon == 11 ? 0 : this_mon + 1; + const int days_this_mo = GetDaysInMonth(this_year, this_mon); + const int days_last_mo = GetDaysInMonth(this_mon == 0 ? last_year : this_year, last_mon); + ImPlotTime t_first_mo = FloorTime(*t,ImPlotTimeUnit_Mo); + GetTime(t_first_mo,&Tm); + const int first_wd = Tm.tm_wday; + // month year + snprintf(buff, 32, "%s %d", MONTH_NAMES[this_mon], this_year); + if (ImGui::Button(buff)) + *level = 1; + ImGui::SameLine(5*cell_size.x); + BeginDisabledControls(this_year <= min_yr && this_mon == 0); + if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size)) + *t = AddTime(*t, ImPlotTimeUnit_Mo, -1); + EndDisabledControls(this_year <= min_yr && this_mon == 0); + ImGui::SameLine(); + BeginDisabledControls(this_year >= max_yr && this_mon == 11); + if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size)) + *t = AddTime(*t, ImPlotTimeUnit_Mo, 1); + EndDisabledControls(this_year >= max_yr && this_mon == 11); + // render weekday abbreviations + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + for (int i = 0; i < 7; ++i) { + ImGui::Button(WD_ABRVS[i],cell_size); + if (i != 6) { ImGui::SameLine(); } + } + ImGui::PopItemFlag(); + // 0 = last mo, 1 = this mo, 2 = next mo + int mo = first_wd > 0 ? 0 : 1; + int day = mo == 1 ? 1 : days_last_mo - first_wd + 1; + for (int i = 0; i < 6; ++i) { + for (int j = 0; j < 7; ++j) { + if (mo == 0 && day > days_last_mo) { + mo = 1; day = 1; + } + else if (mo == 1 && day > days_this_mo) { + mo = 2; day = 1; + } + const int now_yr = (mo == 0 && this_mon == 0) ? last_year : ((mo == 2 && this_mon == 11) ? next_year : this_year); + const int now_mo = mo == 0 ? last_mon : (mo == 1 ? this_mon : next_mon); + const int now_md = day; + + const bool off_mo = mo == 0 || mo == 2; + const bool t1_or_t2 = (t1 != NULL && t1_mo == now_mo && t1_yr == now_yr && t1_md == now_md) || + (t2 != NULL && t2_mo == now_mo && t2_yr == now_yr && t2_md == now_md); + + if (off_mo) + ImGui::PushStyleColor(ImGuiCol_Text, col_dis); + if (t1_or_t2) { + ImGui::PushStyleColor(ImGuiCol_Button, col_btn); + ImGui::PushStyleColor(ImGuiCol_Text, col_txt); + } + ImGui::PushID(i*7+j); + snprintf(buff,32,"%d",day); + if (now_yr == min_yr-1 || now_yr == max_yr+1) { + ImGui::Dummy(cell_size); + } + else if (ImGui::Button(buff,cell_size) && !clk) { + *t = MakeTime(now_yr, now_mo, now_md); + clk = true; + } + ImGui::PopID(); + if (t1_or_t2) + ImGui::PopStyleColor(2); + if (off_mo) + ImGui::PopStyleColor(); + if (j != 6) + ImGui::SameLine(); + day++; + } + } + } + // month widget + else if (*level == 1) { + *t = FloorTime(*t, ImPlotTimeUnit_Mo); + GetTime(*t, &Tm); + int this_yr = Tm.tm_year + 1900; + snprintf(buff, 32, "%d", this_yr); + if (ImGui::Button(buff)) + *level = 2; + BeginDisabledControls(this_yr <= min_yr); + ImGui::SameLine(5*cell_size.x); + if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size)) + *t = AddTime(*t, ImPlotTimeUnit_Yr, -1); + EndDisabledControls(this_yr <= min_yr); + ImGui::SameLine(); + BeginDisabledControls(this_yr >= max_yr); + if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size)) + *t = AddTime(*t, ImPlotTimeUnit_Yr, 1); + EndDisabledControls(this_yr >= max_yr); + // ImGui::Dummy(cell_size); + cell_size.x *= 7.0f/4.0f; + cell_size.y *= 7.0f/3.0f; + int mo = 0; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { + const bool t1_or_t2 = (t1 != NULL && t1_yr == this_yr && t1_mo == mo) || + (t2 != NULL && t2_yr == this_yr && t2_mo == mo); + if (t1_or_t2) + ImGui::PushStyleColor(ImGuiCol_Button, col_btn); + if (ImGui::Button(MONTH_ABRVS[mo],cell_size) && !clk) { + *t = MakeTime(this_yr, mo); + *level = 0; + } + if (t1_or_t2) + ImGui::PopStyleColor(); + if (j != 3) + ImGui::SameLine(); + mo++; + } + } + } + else if (*level == 2) { + *t = FloorTime(*t, ImPlotTimeUnit_Yr); + int this_yr = GetYear(*t); + int yr = this_yr - this_yr % 20; + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + snprintf(buff,32,"%d-%d",yr,yr+19); + ImGui::Button(buff); + ImGui::PopItemFlag(); + ImGui::SameLine(5*cell_size.x); + BeginDisabledControls(yr <= min_yr); + if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size)) + *t = MakeTime(yr-20); + EndDisabledControls(yr <= min_yr); + ImGui::SameLine(); + BeginDisabledControls(yr + 20 >= max_yr); + if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size)) + *t = MakeTime(yr+20); + EndDisabledControls(yr+ 20 >= max_yr); + // ImGui::Dummy(cell_size); + cell_size.x *= 7.0f/4.0f; + cell_size.y *= 7.0f/5.0f; + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 4; ++j) { + const bool t1_or_t2 = (t1 != NULL && t1_yr == yr) || (t2 != NULL && t2_yr == yr); + if (t1_or_t2) + ImGui::PushStyleColor(ImGuiCol_Button, col_btn); + snprintf(buff,32,"%d",yr); + if (yr<1970||yr>3000) { + ImGui::Dummy(cell_size); + } + else if (ImGui::Button(buff,cell_size)) { + *t = MakeTime(yr); + *level = 1; + } + if (t1_or_t2) + ImGui::PopStyleColor(); + if (j != 3) + ImGui::SameLine(); + yr++; + } + } + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::EndGroup(); + ImGui::PopID(); + return clk; +} + +bool ShowTimePicker(const char* id, ImPlotTime* t) { + ImGui::PushID(id); + tm& Tm = GImPlot->Tm; + GetTime(*t,&Tm); + + static const char* nums[] = { "00","01","02","03","04","05","06","07","08","09", + "10","11","12","13","14","15","16","17","18","19", + "20","21","22","23","24","25","26","27","28","29", + "30","31","32","33","34","35","36","37","38","39", + "40","41","42","43","44","45","46","47","48","49", + "50","51","52","53","54","55","56","57","58","59"}; + + static const char* am_pm[] = {"am","pm"}; + + bool hour24 = GImPlot->Style.Use24HourClock; + + int hr = hour24 ? Tm.tm_hour : ((Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12); + int min = Tm.tm_min; + int sec = Tm.tm_sec; + int ap = Tm.tm_hour < 12 ? 0 : 1; + + bool changed = false; + + ImVec2 spacing = ImGui::GetStyle().ItemSpacing; + spacing.x = 0; + float width = ImGui::CalcTextSize("888").x; + float height = ImGui::GetFrameHeight(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, spacing); + ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize,2.0f); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered)); + + ImGui::SetNextItemWidth(width); + if (ImGui::BeginCombo("##hr",nums[hr],ImGuiComboFlags_NoArrowButton)) { + const int ia = hour24 ? 0 : 1; + const int ib = hour24 ? 24 : 13; + for (int i = ia; i < ib; ++i) { + if (ImGui::Selectable(nums[i],i==hr)) { + hr = i; + changed = true; + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + ImGui::Text(":"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(width); + if (ImGui::BeginCombo("##min",nums[min],ImGuiComboFlags_NoArrowButton)) { + for (int i = 0; i < 60; ++i) { + if (ImGui::Selectable(nums[i],i==min)) { + min = i; + changed = true; + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + ImGui::Text(":"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(width); + if (ImGui::BeginCombo("##sec",nums[sec],ImGuiComboFlags_NoArrowButton)) { + for (int i = 0; i < 60; ++i) { + if (ImGui::Selectable(nums[i],i==sec)) { + sec = i; + changed = true; + } + } + ImGui::EndCombo(); + } + if (!hour24) { + ImGui::SameLine(); + if (ImGui::Button(am_pm[ap],ImVec2(height,height))) { + ap = 1 - ap; + changed = true; + } + } + + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(2); + ImGui::PopID(); + + if (changed) { + if (!hour24) + hr = hr % 12 + ap * 12; + Tm.tm_hour = hr; + Tm.tm_min = min; + Tm.tm_sec = sec; + *t = MkTime(&Tm); + } + + return changed; +} + +void StyleColorsAuto(ImPlotStyle* dst) { + ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle(); + ImVec4* colors = style->Colors; + + style->MinorAlpha = 0.25f; + + colors[ImPlotCol_Line] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL; + colors[ImPlotCol_FrameBg] = IMPLOT_AUTO_COL; + colors[ImPlotCol_PlotBg] = IMPLOT_AUTO_COL; + colors[ImPlotCol_PlotBorder] = IMPLOT_AUTO_COL; + colors[ImPlotCol_LegendBg] = IMPLOT_AUTO_COL; + colors[ImPlotCol_LegendBorder] = IMPLOT_AUTO_COL; + colors[ImPlotCol_LegendText] = IMPLOT_AUTO_COL; + colors[ImPlotCol_TitleText] = IMPLOT_AUTO_COL; + colors[ImPlotCol_InlayText] = IMPLOT_AUTO_COL; + colors[ImPlotCol_PlotBorder] = IMPLOT_AUTO_COL; + colors[ImPlotCol_XAxis] = IMPLOT_AUTO_COL; + colors[ImPlotCol_XAxisGrid] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxis] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxisGrid] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxis2] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxisGrid2] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxis3] = IMPLOT_AUTO_COL; + colors[ImPlotCol_YAxisGrid3] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Selection] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Query] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Crosshairs] = IMPLOT_AUTO_COL; +} + +void StyleColorsClassic(ImPlotStyle* dst) { + ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle(); + ImVec4* colors = style->Colors; + + style->MinorAlpha = 0.5f; + + colors[ImPlotCol_Line] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_ErrorBar] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); + colors[ImPlotCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.35f); + colors[ImPlotCol_PlotBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImPlotCol_LegendBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); + colors[ImPlotCol_LegendBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImPlotCol_LegendText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_TitleText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_InlayText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_XAxis] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_XAxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f); + colors[ImPlotCol_YAxis] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_YAxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f); + colors[ImPlotCol_YAxis2] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_YAxisGrid2] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f); + colors[ImPlotCol_YAxis3] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlotCol_YAxisGrid3] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f); + colors[ImPlotCol_Selection] = ImVec4(0.97f, 0.97f, 0.39f, 1.00f); + colors[ImPlotCol_Query] = ImVec4(0.00f, 1.00f, 0.59f, 1.00f); + colors[ImPlotCol_Crosshairs] = ImVec4(0.50f, 0.50f, 0.50f, 0.75f); +} + +void StyleColorsDark(ImPlotStyle* dst) { + ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle(); + ImVec4* colors = style->Colors; + + style->MinorAlpha = 0.25f; + + colors[ImPlotCol_Line] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL; + colors[ImPlotCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImPlotCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); + colors[ImPlotCol_PlotBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImPlotCol_LegendBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImPlotCol_LegendBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImPlotCol_LegendText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_TitleText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_InlayText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_XAxis] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_XAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f); + colors[ImPlotCol_YAxis] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f); + colors[ImPlotCol_YAxis2] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxisGrid2] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f); + colors[ImPlotCol_YAxis3] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxisGrid3] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f); + colors[ImPlotCol_Selection] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImPlotCol_Query] = ImVec4(0.00f, 1.00f, 0.44f, 1.00f); + colors[ImPlotCol_Crosshairs] = ImVec4(1.00f, 1.00f, 1.00f, 0.50f); +} + +void StyleColorsLight(ImPlotStyle* dst) { + ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle(); + ImVec4* colors = style->Colors; + + style->MinorAlpha = 1.0f; + + colors[ImPlotCol_Line] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL; + colors[ImPlotCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_PlotBg] = ImVec4(0.42f, 0.57f, 1.00f, 0.13f); + colors[ImPlotCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImPlotCol_LegendBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); + colors[ImPlotCol_LegendBorder] = ImVec4(0.82f, 0.82f, 0.82f, 0.80f); + colors[ImPlotCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_XAxis] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_XAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxis] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxis2] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid2] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); + colors[ImPlotCol_YAxis3] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid3] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); + colors[ImPlotCol_Selection] = ImVec4(0.82f, 0.64f, 0.03f, 1.00f); + colors[ImPlotCol_Query] = ImVec4(0.00f, 0.84f, 0.37f, 1.00f); + colors[ImPlotCol_Crosshairs] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); +} + +} // namespace ImPlot diff --git a/DearPyGui/vendor/implot/implot.h b/DearPyGui/vendor/implot/implot.h new file mode 100644 index 000000000..8503e8130 --- /dev/null +++ b/DearPyGui/vendor/implot/implot.h @@ -0,0 +1,821 @@ +// MIT License + +// Copyright (c) 2021 Evan Pezent + +// 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. + +// ImPlot v0.9 WIP + +#pragma once +#include "imgui.h" + +//----------------------------------------------------------------------------- +// Macros and Defines +//----------------------------------------------------------------------------- + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// Using ImPlot via a shared library is not recommended, because we don't guarantee +// backward nor forward ABI compatibility and also function call overhead. If you +// do use ImPlot as a DLL, be sure to call SetImGuiContext (see Miscellanous section). +#ifndef IMPLOT_API +#define IMPLOT_API +#endif + +// ImPlot version string +#define IMPLOT_VERSION "0.9 WIP" +// Indicates variable should deduced automatically. +#define IMPLOT_AUTO -1 +// Special color used to indicate that a color should be deduced automatically. +#define IMPLOT_AUTO_COL ImVec4(0,0,0,-1) + +//----------------------------------------------------------------------------- +// Forward Declarations and Basic Types +//----------------------------------------------------------------------------- + +// Forward declarations +struct ImPlotContext; // ImPlot context (opaque struct, see implot_internal.h) + +// Enums/Flags +typedef int ImPlotFlags; // -> enum ImPlotFlags_ +typedef int ImPlotAxisFlags; // -> enum ImPlotAxisFlags_ +typedef int ImPlotCol; // -> enum ImPlotCol_ +typedef int ImPlotStyleVar; // -> enum ImPlotStyleVar_ +typedef int ImPlotMarker; // -> enum ImPlotMarker_ +typedef int ImPlotColormap; // -> enum ImPlotColormap_ +typedef int ImPlotLocation; // -> enum ImPlotLocation_ +typedef int ImPlotOrientation; // -> enum ImPlotOrientation_ +typedef int ImPlotYAxis; // -> enum ImPlotYAxis_; +typedef int ImPlotBin; // -> enum ImPlotBin_ + +// Options for plots. +enum ImPlotFlags_ { + ImPlotFlags_None = 0, // default + ImPlotFlags_NoTitle = 1 << 0, // the plot title will not be displayed (titles are also hidden if preceeded by double hashes, e.g. "##MyPlot") + ImPlotFlags_NoLegend = 1 << 1, // the legend will not be displayed + ImPlotFlags_NoMenus = 1 << 2, // the user will not be able to open context menus with right-click + ImPlotFlags_NoBoxSelect = 1 << 3, // the user will not be able to box-select with right-click drag + ImPlotFlags_NoMousePos = 1 << 4, // the mouse position, in plot coordinates, will not be displayed inside of the plot + ImPlotFlags_NoHighlight = 1 << 5, // plot items will not be highlighted when their legend entry is hovered + ImPlotFlags_NoChild = 1 << 6, // a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications) + ImPlotFlags_Equal = 1 << 7, // primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes) + ImPlotFlags_YAxis2 = 1 << 8, // enable a 2nd y-axis on the right side + ImPlotFlags_YAxis3 = 1 << 9, // enable a 3rd y-axis on the right side + ImPlotFlags_Query = 1 << 10, // the user will be able to draw query rects with middle-mouse or CTRL + right-click drag + ImPlotFlags_Crosshairs = 1 << 11, // the default mouse cursor will be replaced with a crosshair when hovered + ImPlotFlags_AntiAliased = 1 << 12, // plot lines will be software anti-aliased (not recommended for high density plots, prefer MSAA) + ImPlotFlags_CanvasOnly = ImPlotFlags_NoTitle | ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMousePos +}; + +// Options for plot axes (X and Y). +enum ImPlotAxisFlags_ { + ImPlotAxisFlags_None = 0, // default + ImPlotAxisFlags_NoLabel = 1 << 0, // the axis label will not be displayed (axis labels also hidden if the supplied string name is NULL) + ImPlotAxisFlags_NoGridLines = 1 << 1, // no grid lines will be displayed + ImPlotAxisFlags_NoTickMarks = 1 << 2, // no tick marks will be displayed + ImPlotAxisFlags_NoTickLabels = 1 << 3, // no text labels will be displayed + ImPlotAxisFlags_LogScale = 1 << 4, // a logartithmic (base 10) axis scale will be used (mutually exclusive with ImPlotAxisFlags_Time) + ImPlotAxisFlags_Time = 1 << 5, // axis will display date/time formatted labels (mutually exclusive with ImPlotAxisFlags_LogScale) + ImPlotAxisFlags_Invert = 1 << 6, // the axis will be inverted + ImPlotAxisFlags_AutoFit = 1 << 7, // axis will be auto-fitting to data extents + ImPlotAxisFlags_LockMin = 1 << 8, // the axis minimum value will be locked when panning/zooming + ImPlotAxisFlags_LockMax = 1 << 9, // the axis maximum value will be locked when panning/zooming + ImPlotAxisFlags_Lock = ImPlotAxisFlags_LockMin | ImPlotAxisFlags_LockMax, + ImPlotAxisFlags_NoDecorations = ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_NoTickMarks | ImPlotAxisFlags_NoTickLabels +}; + +// Plot styling colors. +enum ImPlotCol_ { + // item styling colors + ImPlotCol_Line, // plot line/outline color (defaults to next unused color in current colormap) + ImPlotCol_Fill, // plot fill color for bars (defaults to the current line color) + ImPlotCol_MarkerOutline, // marker outline color (defaults to the current line color) + ImPlotCol_MarkerFill, // marker fill color (defaults to the current line color) + ImPlotCol_ErrorBar, // error bar color (defaults to ImGuiCol_Text) + // plot styling colors + ImPlotCol_FrameBg, // plot frame background color (defaults to ImGuiCol_FrameBg) + ImPlotCol_PlotBg, // plot area background color (defaults to ImGuiCol_WindowBg) + ImPlotCol_PlotBorder, // plot area border color (defaults to ImGuiCol_Border) + ImPlotCol_LegendBg, // legend background color (defaults to ImGuiCol_PopupBg) + ImPlotCol_LegendBorder, // legend border color (defaults to ImPlotCol_PlotBorder) + ImPlotCol_LegendText, // legend text color (defaults to ImPlotCol_InlayText) + ImPlotCol_TitleText, // plot title text color (defaults to ImGuiCol_Text) + ImPlotCol_InlayText, // color of text appearing inside of plots (defaults to ImGuiCol_Text) + ImPlotCol_XAxis, // x-axis label and tick lables color (defaults to ImGuiCol_Text) + ImPlotCol_XAxisGrid, // x-axis grid color (defaults to 25% ImPlotCol_XAxis) + ImPlotCol_YAxis, // y-axis label and tick labels color (defaults to ImGuiCol_Text) + ImPlotCol_YAxisGrid, // y-axis grid color (defaults to 25% ImPlotCol_YAxis) + ImPlotCol_YAxis2, // 2nd y-axis label and tick labels color (defaults to ImGuiCol_Text) + ImPlotCol_YAxisGrid2, // 2nd y-axis grid/label color (defaults to 25% ImPlotCol_YAxis2) + ImPlotCol_YAxis3, // 3rd y-axis label and tick labels color (defaults to ImGuiCol_Text) + ImPlotCol_YAxisGrid3, // 3rd y-axis grid/label color (defaults to 25% ImPlotCol_YAxis3) + ImPlotCol_Selection, // box-selection color (defaults to yellow) + ImPlotCol_Query, // box-query color (defaults to green) + ImPlotCol_Crosshairs, // crosshairs color (defaults to ImPlotCol_PlotBorder) + ImPlotCol_COUNT +}; + +// Plot styling variables. +enum ImPlotStyleVar_ { + // item styling variables + ImPlotStyleVar_LineWeight, // float, plot item line weight in pixels + ImPlotStyleVar_Marker, // int, marker specification + ImPlotStyleVar_MarkerSize, // float, marker size in pixels (roughly the marker's "radius") + ImPlotStyleVar_MarkerWeight, // float, plot outline weight of markers in pixels + ImPlotStyleVar_FillAlpha, // float, alpha modifier applied to all plot item fills + ImPlotStyleVar_ErrorBarSize, // float, error bar whisker width in pixels + ImPlotStyleVar_ErrorBarWeight, // float, error bar whisker weight in pixels + ImPlotStyleVar_DigitalBitHeight, // float, digital channels bit height (at 1) in pixels + ImPlotStyleVar_DigitalBitGap, // float, digital channels bit padding gap in pixels + // plot styling variables + ImPlotStyleVar_PlotBorderSize, // float, thickness of border around plot area + ImPlotStyleVar_MinorAlpha, // float, alpha multiplier applied to minor axis grid lines + ImPlotStyleVar_MajorTickLen, // ImVec2, major tick lengths for X and Y axes + ImPlotStyleVar_MinorTickLen, // ImVec2, minor tick lengths for X and Y axes + ImPlotStyleVar_MajorTickSize, // ImVec2, line thickness of major ticks + ImPlotStyleVar_MinorTickSize, // ImVec2, line thickness of minor ticks + ImPlotStyleVar_MajorGridSize, // ImVec2, line thickness of major grid lines + ImPlotStyleVar_MinorGridSize, // ImVec2, line thickness of minor grid lines + ImPlotStyleVar_PlotPadding, // ImVec2, padding between widget frame and plot area, labels, or outside legends (i.e. main padding) + ImPlotStyleVar_LabelPadding, // ImVec2, padding between axes labels, tick labels, and plot edge + ImPlotStyleVar_LegendPadding, // ImVec2, legend padding from plot edges + ImPlotStyleVar_LegendInnerPadding, // ImVec2, legend inner padding from legend edges + ImPlotStyleVar_LegendSpacing, // ImVec2, spacing between legend entries + ImPlotStyleVar_MousePosPadding, // ImVec2, padding between plot edge and interior info text + ImPlotStyleVar_AnnotationPadding, // ImVec2, text padding around annotation labels + ImPlotStyleVar_FitPadding, // ImVec2, additional fit padding as a percentage of the fit extents (e.g. ImVec2(0.1f,0.1f) adds 10% to the fit extents of X and Y) + ImPlotStyleVar_PlotDefaultSize, // ImVec2, default size used when ImVec2(0,0) is passed to BeginPlot + ImPlotStyleVar_PlotMinSize, // ImVec2, minimum size plot frame can be when shrunk + ImPlotStyleVar_COUNT +}; + +// Marker specifications. +enum ImPlotMarker_ { + ImPlotMarker_None = -1, // no marker + ImPlotMarker_Circle, // a circle marker + ImPlotMarker_Square, // a square maker + ImPlotMarker_Diamond, // a diamond marker + ImPlotMarker_Up, // an upward-pointing triangle marker + ImPlotMarker_Down, // an downward-pointing triangle marker + ImPlotMarker_Left, // an leftward-pointing triangle marker + ImPlotMarker_Right, // an rightward-pointing triangle marker + ImPlotMarker_Cross, // a cross marker (not fillable) + ImPlotMarker_Plus, // a plus marker (not fillable) + ImPlotMarker_Asterisk, // a asterisk marker (not fillable) + ImPlotMarker_COUNT +}; + +// Built-in colormaps +enum ImPlotColormap_ { + ImPlotColormap_Deep = 0, // a.k.a. seaborn deep (qual=true, n=10) (default) + ImPlotColormap_Dark = 1, // a.k.a. matplotlib "Set1" (qual=true, n=9 ) + ImPlotColormap_Pastel = 2, // a.k.a. matplotlib "Pastel1" (qual=true, n=9 ) + ImPlotColormap_Paired = 3, // a.k.a. matplotlib "Paired" (qual=true, n=12) + ImPlotColormap_Viridis = 4, // a.k.a. matplotlib "viridis" (qual=false, n=11) + ImPlotColormap_Plasma = 5, // a.k.a. matplotlib "plasma" (qual=false, n=11) + ImPlotColormap_Hot = 6, // a.k.a. matplotlib/MATLAB "hot" (qual=false, n=11) + ImPlotColormap_Cool = 7, // a.k.a. matplotlib/MATLAB "cool" (qual=false, n=11) + ImPlotColormap_Pink = 8, // a.k.a. matplotlib/MATLAB "pink" (qual=false, n=11) + ImPlotColormap_Jet = 9, // a.k.a. MATLAB "jet" (qual=false, n=11) + ImPlotColormap_Twilight = 10, // a.k.a. matplotlib "twilight" (qual=false, n=11) + ImPlotColormap_RdBu = 11, // red/blue, Color Brewer (qual=false, n=11) + ImPlotColormap_BrBG = 12, // brown/blue-green, Color Brewer (qual=false, n=11) + ImPlotColormap_PiYG = 13, // pink/yellow-green, Color Brewer (qual=false, n=11) + ImPlotColormap_Spectral = 14, // color spectrum, Color Brewer (qual=false, n=11) + ImPlotColormap_Greys = 15, // white/black (qual=false, n=2 ) +}; + +// Used to position items on a plot (e.g. legends, labels, etc.) +enum ImPlotLocation_ { + ImPlotLocation_Center = 0, // center-center + ImPlotLocation_North = 1 << 0, // top-center + ImPlotLocation_South = 1 << 1, // bottom-center + ImPlotLocation_West = 1 << 2, // center-left + ImPlotLocation_East = 1 << 3, // center-right + ImPlotLocation_NorthWest = ImPlotLocation_North | ImPlotLocation_West, // top-left + ImPlotLocation_NorthEast = ImPlotLocation_North | ImPlotLocation_East, // top-right + ImPlotLocation_SouthWest = ImPlotLocation_South | ImPlotLocation_West, // bottom-left + ImPlotLocation_SouthEast = ImPlotLocation_South | ImPlotLocation_East // bottom-right +}; + +// Used to orient items on a plot (e.g. legends, labels, etc.) +enum ImPlotOrientation_ { + ImPlotOrientation_Horizontal, // left/right + ImPlotOrientation_Vertical // up/down +}; + +// Enums for different y-axes. +enum ImPlotYAxis_ { + ImPlotYAxis_1 = 0, // left (default) + ImPlotYAxis_2 = 1, // first on right side + ImPlotYAxis_3 = 2 // second on right side +}; + +// Enums for different automatic histogram binning methods (k = bin count or w = bin width) +enum ImPlotBin_ { + ImPlotBin_Sqrt = -1, // k = sqrt(n) + ImPlotBin_Sturges = -2, // k = 1 + log2(n) + ImPlotBin_Rice = -3, // k = 2 * cbrt(n) + ImPlotBin_Scott = -4, // w = 3.49 * sigma / cbrt(n) +}; + +// Double precision version of ImVec2 used by ImPlot. Extensible by end users. +struct ImPlotPoint { + double x, y; + ImPlotPoint() { x = y = 0.0; } + ImPlotPoint(double _x, double _y) { x = _x; y = _y; } + ImPlotPoint(const ImVec2& p) { x = p.x; y = p.y; } + double operator[] (size_t idx) const { return (&x)[idx]; } + double& operator[] (size_t idx) { return (&x)[idx]; } +#ifdef IMPLOT_POINT_CLASS_EXTRA + IMPLOT_POINT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h + // to convert back and forth between your math types and ImPlotPoint. +#endif +}; + +// A range defined by a min/max value. Used for plot axes ranges. +struct ImPlotRange { + double Min, Max; + ImPlotRange() { Min = 0; Max = 0; } + ImPlotRange(double _min, double _max) { Min = _min; Max = _max; } + bool Contains(double value) const { return value >= Min && value <= Max; }; + double Size() const { return Max - Min; }; +}; + +// Combination of two ranges for X and Y axes. +struct ImPlotLimits { + ImPlotRange X, Y; + ImPlotLimits() { } + ImPlotLimits(double x_min, double x_max, double y_min, double y_max) { X.Min = x_min; X.Max = x_max; Y.Min = y_min; Y.Max = y_max; } + bool Contains(const ImPlotPoint& p) const { return Contains(p.x, p.y); } + bool Contains(double x, double y) const { return X.Contains(x) && Y.Contains(y); } + ImPlotPoint Min() const { return ImPlotPoint(X.Min, Y.Min); } + ImPlotPoint Max() const { return ImPlotPoint(X.Max, Y.Max); } +}; + +// Plot style structure +struct ImPlotStyle { + // item styling variables + float LineWeight; // = 1, item line weight in pixels + int Marker; // = ImPlotMarker_None, marker specification + float MarkerSize; // = 4, marker size in pixels (roughly the marker's "radius") + float MarkerWeight; // = 1, outline weight of markers in pixels + float FillAlpha; // = 1, alpha modifier applied to plot fills + float ErrorBarSize; // = 5, error bar whisker width in pixels + float ErrorBarWeight; // = 1.5, error bar whisker weight in pixels + float DigitalBitHeight; // = 8, digital channels bit height (at y = 1.0f) in pixels + float DigitalBitGap; // = 4, digital channels bit padding gap in pixels + // plot styling variables + float PlotBorderSize; // = 1, line thickness of border around plot area + float MinorAlpha; // = 0.25 alpha multiplier applied to minor axis grid lines + ImVec2 MajorTickLen; // = 10,10 major tick lengths for X and Y axes + ImVec2 MinorTickLen; // = 5,5 minor tick lengths for X and Y axes + ImVec2 MajorTickSize; // = 1,1 line thickness of major ticks + ImVec2 MinorTickSize; // = 1,1 line thickness of minor ticks + ImVec2 MajorGridSize; // = 1,1 line thickness of major grid lines + ImVec2 MinorGridSize; // = 1,1 line thickness of minor grid lines + ImVec2 PlotPadding; // = 10,10 padding between widget frame and plot area, labels, or outside legends (i.e. main padding) + ImVec2 LabelPadding; // = 5,5 padding between axes labels, tick labels, and plot edge + ImVec2 LegendPadding; // = 10,10 legend padding from plot edges + ImVec2 LegendInnerPadding; // = 5,5 legend inner padding from legend edges + ImVec2 LegendSpacing; // = 5,0 spacing between legend entries + ImVec2 MousePosPadding; // = 10,10 padding between plot edge and interior mouse location text + ImVec2 AnnotationPadding; // = 2,2 text padding around annotation labels + ImVec2 FitPadding; // = 0,0 additional fit padding as a percentage of the fit extents (e.g. ImVec2(0.1f,0.1f) adds 10% to the fit extents of X and Y) + ImVec2 PlotDefaultSize; // = 400,300 default size used when ImVec2(0,0) is passed to BeginPlot + ImVec2 PlotMinSize; // = 300,225 minimum size plot frame can be when shrunk + // style colors + ImVec4 Colors[ImPlotCol_COUNT]; // Array of styling colors. Indexable with ImPlotCol_ enums. + // colormap + ImPlotColormap Colormap; // The current colormap. Set this to either an ImPlotColormap_ enum or an index returned by AddColormap. + // settings/flags + bool AntiAliasedLines; // = false, enable global anti-aliasing on plot lines (overrides ImPlotFlags_AntiAliased) + bool UseLocalTime; // = false, axis labels will be formatted for your timezone when ImPlotAxisFlag_Time is enabled + bool UseISO8601; // = false, dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.) + bool Use24HourClock; // = false, times will be formatted using a 24 hour clock + IMPLOT_API ImPlotStyle(); +}; + +//----------------------------------------------------------------------------- +// ImPlot End-User API +//----------------------------------------------------------------------------- + +namespace ImPlot { + +//----------------------------------------------------------------------------- +// ImPlot Context +//----------------------------------------------------------------------------- + +// Creates a new ImPlot context. Call this after ImGui::CreateContext. +IMPLOT_API ImPlotContext* CreateContext(); +// Destroys an ImPlot context. Call this before ImGui::DestroyContext. NULL = destroy current context. +IMPLOT_API void DestroyContext(ImPlotContext* ctx = NULL); +// Returns the current ImPlot context. NULL if no context has ben set. +IMPLOT_API ImPlotContext* GetCurrentContext(); +// Sets the current ImPlot context. +IMPLOT_API void SetCurrentContext(ImPlotContext* ctx); + +// Sets the current **ImGui** context. This is ONLY necessary if you are compiling +// ImPlot as a DLL (not recommended) separate from your ImGui compilation. It +// sets the global variable GImGui, which is not shared across DLL boundaries. +// See GImGui documentation in imgui.cpp for more details. +IMPLOT_API void SetImGuiContext(ImGuiContext* ctx); + +//----------------------------------------------------------------------------- +// Begin/End Plot +//----------------------------------------------------------------------------- + +// Starts a 2D plotting context. If this function returns true, EndPlot() must +// be called! You are encouraged to use the following call convention: +// +// if (BeginPlot(...)) { +// ImPlot::PlotLine(...); +// EndPlot(); +// } +// +// Important notes: +// +// - #title_id must be unique to the current ImGui window. If you need to avoid ID +// collisions or don't want to display a title in the plot, use double hashes +// (e.g. "MyPlot##Hidden" or "##NoTitle"). +// - If #x_label and/or #y_label are provided, axes labels will be displayed. +// - #size is the **frame** size of the plot widget, not the plot area. The default +// size of plots (i.e. when ImVec2(0,0)) can be modified in your ImPlotStyle +// (default is 400x300). +// - Auxiliary y-axes must be enabled with ImPlotFlags_YAxis2/3 to be displayed. +// - See ImPlotFlags and ImPlotAxisFlags for more available options. + +IMPLOT_API bool BeginPlot(const char* title_id, + const char* x_label = NULL, + const char* y_label = NULL, + const ImVec2& size = ImVec2(-1,0), + ImPlotFlags flags = ImPlotFlags_None, + ImPlotAxisFlags x_flags = ImPlotAxisFlags_None, + ImPlotAxisFlags y_flags = ImPlotAxisFlags_None, + ImPlotAxisFlags y2_flags = ImPlotAxisFlags_NoGridLines, + ImPlotAxisFlags y3_flags = ImPlotAxisFlags_NoGridLines, + const char* y2_label = NULL, + const char* y3_label = NULL); + +// Only call EndPlot() if BeginPlot() returns true! Typically called at the end +// of an if statement conditioned on BeginPlot(). See above. +IMPLOT_API void EndPlot(); + +//----------------------------------------------------------------------------- +// Plot Items +//----------------------------------------------------------------------------- + +// The template functions below are explicitly instantiated in implot_items.cpp. +// They are not intended to be used generically with custom types. You will get +// a linker error if you try! All functions support the following scalar types: +// +// float, double, ImS8, ImU8, ImS16, ImU16, ImS32, ImU32, ImS64, ImU64 +// +// +// If you need to plot custom or non-homogenous data you have a few options: +// +// 1. If your data is a simple struct/class (e.g. Vector2f), you can use striding. +// This is the most performant option if applicable. +// +// struct Vector2f { float X, Y; }; +// ... +// Vector2f data[42]; +// ImPlot::PlotLine("line", &data[0].x, &data[0].y, 42, 0, sizeof(Vector2f)); // or sizeof(float)*2 +// +// 2. Write a custom getter C function or C++ lambda and pass it and your data to +// an ImPlot function post-fixed with a G (e.g. PlotScatterG). This has a +// slight performance cost, but probably not enough to worry about. Example: +// +// ImPlotPoint MyDataGetter(void* data, int idx) { +// MyData* my_data = (MyData*)data; +// ImPlotPoint p; +// p.x = my_data->GetTime(idx); +// p.y = my_data->GetValue(idx); +// return p +// } +// ... +// auto my_lambda = [](void*, int idx) { +// double t = idx / 999.0; +// return ImPlotPoint(t, 0.5+0.5*std::sin(2*PI*10*t)); +// }; +// ... +// if (ImPlot::BeginPlot("MyPlot")) { +// MyData my_data; +// ImPlot::PlotScatterG("scatter", MyDataGetter, &my_data, my_data.Size()); +// ImPlot::PlotLineG("line", my_lambda, nullptr, 1000); +// ImPlot::EndPlot(); +// } +// +// NB: All types are converted to double before plotting. You may lose information +// if you try plotting extremely large 64-bit integral types. Proceed with caution! + +// Plots a standard 2D line plot. +template IMPLOT_API void PlotLine(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotLine(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotLineG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, int offset=0); + +// Plots a standard 2D scatter plot. Default marker is ImPlotMarker_Circle. +template IMPLOT_API void PlotScatter(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotScatter(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotScatterG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, int offset=0); + +// Plots a a stairstep graph. The y value is continued constantly from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i]. +template IMPLOT_API void PlotStairs(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotStairs(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotStairsG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, int offset=0); + +// Plots a shaded (filled) region between two lines, or a line and a horizontal reference. Set y_ref to +/-INFINITY for infinite fill extents. +template IMPLOT_API void PlotShaded(const char* label_id, const T* values, int count, double y_ref=0, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotShaded(const char* label_id, const T* xs, const T* ys, int count, double y_ref=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotShaded(const char* label_id, const T* xs, const T* ys1, const T* ys2, int count, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotShadedG(const char* label_id, ImPlotPoint (*getter1)(void* data, int idx), void* data1, ImPlotPoint (*getter2)(void* data, int idx), void* data2, int count, int offset=0); + +// Plots a vertical bar graph. #width and #shift are in X units. +template IMPLOT_API void PlotBars(const char* label_id, const T* values, int count, double width=0.67, double shift=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotBars(const char* label_id, const T* xs, const T* ys, int count, double width, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotBarsG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, double width, int offset=0); + +// Plots a horizontal bar graph. #height and #shift are in Y units. +template IMPLOT_API void PlotBarsH(const char* label_id, const T* values, int count, double height=0.67, double shift=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotBarsH(const char* label_id, const T* xs, const T* ys, int count, double height, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotBarsHG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, double height, int offset=0); + +// Plots vertical error bar. The label_id should be the same as the label_id of the associated line or bar plot. +template IMPLOT_API void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset=0, int stride=sizeof(T)); + +// Plots horizontal error bars. The label_id should be the same as the label_id of the associated line or bar plot. +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset=0, int stride=sizeof(T)); + +/// Plots vertical stems. +template IMPLOT_API void PlotStems(const char* label_id, const T* values, int count, double y_ref=0, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotStems(const char* label_id, const T* xs, const T* ys, int count, double y_ref=0, int offset=0, int stride=sizeof(T)); + +/// Plots infinite vertical or horizontal lines (e.g. for references or asymptotes). +template IMPLOT_API void PlotVLines(const char* label_id, const T* xs, int count, int offset=0, int stride=sizeof(T)); +template IMPLOT_API void PlotHLines(const char* label_id, const T* ys, int count, int offset=0, int stride=sizeof(T)); + +// Plots a pie chart. If the sum of values > 1 or normalize is true, each value will be normalized. Center and radius are in plot units. #label_fmt can be set to NULL for no labels. +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const T* values, int count, double x, double y, double radius, bool normalize=false, const char* label_fmt="%.1f", double angle0=90); + +// Plots a 2D heatmap chart. Values are expected to be in row-major order. #label_fmt can be set to NULL for no labels. +template IMPLOT_API void PlotHeatmap(const char* label_id, const T* values, int rows, int cols, double scale_min, double scale_max, const char* label_fmt="%.1f", const ImPlotPoint& bounds_min=ImPlotPoint(0,0), const ImPlotPoint& bounds_max=ImPlotPoint(1,1)); + +// Plots a horizontal histogram. #bins can be a positive integer or an ImPlotBin_ method. If #cumulative is true, each bin contains its count plus the counts of all previous bins. +// If #density is true, the PDF is visualized. If both are true, the CDF is visualized. If #range is left unspecified, the min/max of #values will be used as the range. +// If #range is specified, outlier values outside of the range are not binned. However, outliers still count toward normalizing and cumulative counts unless #outliers is false. The largest bin count or density is returned. +template IMPLOT_API double PlotHistogram(const char* label_id, const T* values, int count, int bins=ImPlotBin_Sturges, bool cumulative=false, bool density=false, ImPlotRange range=ImPlotRange(), bool outliers=true, double bar_scale=1.0); + +// Plots two dimensional, bivariate histogram as a heatmap. #x_bins and #y_bins can be a positive integer or an ImPlotBin. If #density is true, the PDF is visualized. +// If #range is left unspecified, the min/max of #xs an #ys will be used as the ranges. If #range is specified, outlier values outside of range are not binned. +// However, outliers still count toward the normalizing count for density plots unless #outliers is false. The largest bin count or density is returned. +template IMPLOT_API double PlotHistogram2D(const char* label_id, const T* xs, const T* ys, int count, int x_bins=ImPlotBin_Sturges, int y_bins=ImPlotBin_Sturges, bool density=false, ImPlotLimits range=ImPlotLimits(), bool outliers=true); + +// Plots digital data. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot. +template IMPLOT_API void PlotDigital(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T)); + IMPLOT_API void PlotDigitalG(const char* label_id, ImPlotPoint (*getter)(void* data, int idx), void* data, int count, int offset=0); + +// Plots an axis-aligned image. #bounds_min/bounds_max are in plot coordinatse (y-up) and #uv0/uv1 are in texture coordinates (y-down). +IMPLOT_API void PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, const ImVec2& uv0=ImVec2(0,0), const ImVec2& uv1=ImVec2(1,1), const ImVec4& tint_col=ImVec4(1,1,1,1)); + +// Plots a centered text label at point x,y with optional pixel offset. Text color can be changed with ImPlot::PushStyleColor(ImPlotCol_InlayText, ...). +IMPLOT_API void PlotText(const char* text, double x, double y, bool vertical=false, const ImVec2& pix_offset=ImVec2(0,0)); + +// Plots a dummy item (i.e. adds a legend entry colored by ImPlotCol_Line) +IMPLOT_API void PlotDummy(const char* label_id); + +//----------------------------------------------------------------------------- +// Plot Utils +//----------------------------------------------------------------------------- + +// The following functions MUST be called BEFORE BeginPlot! + +// Set the axes range limits of the next plot. Call right before BeginPlot(). If ImGuiCond_Always is used, the axes limits will be locked. +IMPLOT_API void SetNextPlotLimits(double xmin, double xmax, double ymin, double ymax, ImGuiCond cond = ImGuiCond_Once); +// Set the X axis range limits of the next plot. Call right before BeginPlot(). If ImGuiCond_Always is used, the X axis limits will be locked. +IMPLOT_API void SetNextPlotLimitsX(double xmin, double xmax, ImGuiCond cond = ImGuiCond_Once); +// Set the Y axis range limits of the next plot. Call right before BeginPlot(). If ImGuiCond_Always is used, the Y axis limits will be locked. +IMPLOT_API void SetNextPlotLimitsY(double ymin, double ymax, ImGuiCond cond = ImGuiCond_Once, ImPlotYAxis y_axis = 0); +// Links the next plot limits to external values. Set to NULL for no linkage. The pointer data must remain valid until the matching call EndPlot. +IMPLOT_API void LinkNextPlotLimits(double* xmin, double* xmax, double* ymin, double* ymax, double* ymin2 = NULL, double* ymax2 = NULL, double* ymin3 = NULL, double* ymax3 = NULL); +// Fits the next plot axes to all plotted data if they are unlocked (equivalent to double-clicks). +IMPLOT_API void FitNextPlotAxes(bool x = true, bool y = true, bool y2 = true, bool y3 = true); + +// Set the X axis ticks and optionally the labels for the next plot. +IMPLOT_API void SetNextPlotTicksX(const double* values, int n_ticks, const char* const labels[] = NULL, bool show_default = false); +IMPLOT_API void SetNextPlotTicksX(double x_min, double x_max, int n_ticks, const char* const labels[] = NULL, bool show_default = false); + +// Set the Y axis ticks and optionally the labels for the next plot. +IMPLOT_API void SetNextPlotTicksY(const double* values, int n_ticks, const char* const labels[] = NULL, bool show_default = false, ImPlotYAxis y_axis = 0); +IMPLOT_API void SetNextPlotTicksY(double y_min, double y_max, int n_ticks, const char* const labels[] = NULL, bool show_default = false, ImPlotYAxis y_axis = 0); + +// The following functions MUST be called BETWEEN Begin/EndPlot! + +// Select which Y axis will be used for subsequent plot elements. The default is ImPlotYAxis_1, or the first (left) Y axis. Enable 2nd and 3rd axes with ImPlotFlags_YAxisX. +IMPLOT_API void SetPlotYAxis(ImPlotYAxis y_axis); +// Hides or shows the next plot item (i.e. as if it were toggled from the legend). Use ImGuiCond_Always if you need to forcefully set this every frame. +IMPLOT_API void HideNextItem(bool hidden = true, ImGuiCond cond = ImGuiCond_Once); + +// Convert pixels to a position in the current plot's coordinate system. A negative y_axis uses the current value of SetPlotYAxis (ImPlotYAxis_1 initially). +IMPLOT_API ImPlotPoint PixelsToPlot(const ImVec2& pix, ImPlotYAxis y_axis = IMPLOT_AUTO); +IMPLOT_API ImPlotPoint PixelsToPlot(float x, float y, ImPlotYAxis y_axis = IMPLOT_AUTO); +// Convert a position in the current plot's coordinate system to pixels. A negative y_axis uses the current value of SetPlotYAxis (ImPlotYAxis_1 initially). +IMPLOT_API ImVec2 PlotToPixels(const ImPlotPoint& plt, ImPlotYAxis y_axis = IMPLOT_AUTO); +IMPLOT_API ImVec2 PlotToPixels(double x, double y, ImPlotYAxis y_axis = IMPLOT_AUTO); +// Get the current Plot position (top-left) in pixels. +IMPLOT_API ImVec2 GetPlotPos(); +// Get the curent Plot size in pixels. +IMPLOT_API ImVec2 GetPlotSize(); +// Returns true if the plot area in the current plot is hovered. +IMPLOT_API bool IsPlotHovered(); +// Returns true if the XAxis plot area in the current plot is hovered. +IMPLOT_API bool IsPlotXAxisHovered(); +// Returns true if the YAxis[n] plot area in the current plot is hovered. +IMPLOT_API bool IsPlotYAxisHovered(ImPlotYAxis y_axis = 0); +// Returns the mouse position in x,y coordinates of the current plot. A negative y_axis uses the current value of SetPlotYAxis (ImPlotYAxis_1 initially). +IMPLOT_API ImPlotPoint GetPlotMousePos(ImPlotYAxis y_axis = IMPLOT_AUTO); +// Returns the current plot axis range. A negative y_axis uses the current value of SetPlotYAxis (ImPlotYAxis_1 initially). +IMPLOT_API ImPlotLimits GetPlotLimits(ImPlotYAxis y_axis = IMPLOT_AUTO); + +// Returns true if the current plot is being queried. Query must be enabled with ImPlotFlags_Query. +IMPLOT_API bool IsPlotQueried(); +// Returns the current plot query bounds. Query must be enabled with ImPlotFlags_Query. +IMPLOT_API ImPlotLimits GetPlotQuery(ImPlotYAxis y_axis = IMPLOT_AUTO); + +//----------------------------------------------------------------------------- +// Plot Tools +//----------------------------------------------------------------------------- + +// The following functions MUST be called BETWEEN Begin/EndPlot! + +// Shows an annotation callout at a chosen point. +IMPLOT_API void Annotate(double x, double y, const ImVec2& pix_offset, const char* fmt, ...) IM_FMTARGS(4); +IMPLOT_API void Annotate(double x, double y, const ImVec2& pix_offset, const ImVec4& color, const char* fmt, ...) IM_FMTARGS(5); +IMPLOT_API void AnnotateV(double x, double y, const ImVec2& pix_offset, const char* fmt, va_list args) IM_FMTLIST(4); +IMPLOT_API void AnnotateV(double x, double y, const ImVec2& pix_offset, const ImVec4& color, const char* fmt, va_list args) IM_FMTLIST(5); + +// Same as above, but the annotation will always be clamped to stay inside the plot area. +IMPLOT_API void AnnotateClamped(double x, double y, const ImVec2& pix_offset, const char* fmt, ...) IM_FMTARGS(4); +IMPLOT_API void AnnotateClamped(double x, double y, const ImVec2& pix_offset, const ImVec4& color, const char* fmt, ...) IM_FMTARGS(5); +IMPLOT_API void AnnotateClampedV(double x, double y, const ImVec2& pix_offset, const char* fmt, va_list args) IM_FMTLIST(4); +IMPLOT_API void AnnotateClampedV(double x, double y, const ImVec2& pix_offset, const ImVec4& color, const char* fmt, va_list args) IM_FMTLIST(5); + +// Shows a draggable vertical guide line at an x-value. #col defaults to ImGuiCol_Text. +IMPLOT_API bool DragLineX(const char* id, double* x_value, bool show_label = true, const ImVec4& col = IMPLOT_AUTO_COL, float thickness = 1); +// Shows a draggable horizontal guide line at a y-value. #col defaults to ImGuiCol_Text. +IMPLOT_API bool DragLineY(const char* id, double* y_value, bool show_label = true, const ImVec4& col = IMPLOT_AUTO_COL, float thickness = 1); +// Shows a draggable point at x,y. #col defaults to ImGuiCol_Text. +IMPLOT_API bool DragPoint(const char* id, double* x, double* y, bool show_label = true, const ImVec4& col = IMPLOT_AUTO_COL, float radius = 4); + +//----------------------------------------------------------------------------- +// Legend Utils and Tools +//----------------------------------------------------------------------------- + +// The following functions MUST be called BETWEEN Begin/EndPlot! + +// Set the location of the current plot's legend (default = North|West). +IMPLOT_API void SetLegendLocation(ImPlotLocation location, ImPlotOrientation orientation = ImPlotOrientation_Vertical, bool outside = false); +// Set the location of the current plot's mouse position text (default = South|East). +IMPLOT_API void SetMousePosLocation(ImPlotLocation location); +// Returns true if a plot item legend entry is hovered. +IMPLOT_API bool IsLegendEntryHovered(const char* label_id); + +// Begin a popup for a legend entry. +IMPLOT_API bool BeginLegendPopup(const char* label_id, ImGuiMouseButton mouse_button = 1); +// End a popup for a legend entry. +IMPLOT_API void EndLegendPopup(); + +//----------------------------------------------------------------------------- +// Drag and Drop Utils +//----------------------------------------------------------------------------- + +// The following functions MUST be called BETWEEN Begin/EndPlot! + +// Turns the current plot's plotting area into a drag and drop target. Don't forget to call EndDragDropTarget! +IMPLOT_API bool BeginDragDropTarget(); +// Turns the current plot's X-axis into a drag and drop target. Don't forget to call EndDragDropTarget! +IMPLOT_API bool BeginDragDropTargetX(); +// Turns the current plot's Y-Axis into a drag and drop target. Don't forget to call EndDragDropTarget! +IMPLOT_API bool BeginDragDropTargetY(ImPlotYAxis axis = ImPlotYAxis_1); +// Turns the current plot's legend into a drag and drop target. Don't forget to call EndDragDropTarget! +IMPLOT_API bool BeginDragDropTargetLegend(); +// Ends a drag and drop target (currently just an alias for ImGui::EndDragDropTarget). +IMPLOT_API void EndDragDropTarget(); + +// NB: By default, plot and axes drag and drop sources require holding the Ctrl modifier to initiate the drag. +// You can change the modifier if desired. If ImGuiKeyModFlags_None is provided, the axes will be locked from panning. + +// Turns the current plot's plotting area into a drag and drop source. Don't forget to call EndDragDropSource! +IMPLOT_API bool BeginDragDropSource(ImGuiKeyModFlags key_mods = ImGuiKeyModFlags_Ctrl, ImGuiDragDropFlags flags = 0); +// Turns the current plot's X-axis into a drag and drop source. Don't forget to call EndDragDropSource! +IMPLOT_API bool BeginDragDropSourceX(ImGuiKeyModFlags key_mods = ImGuiKeyModFlags_Ctrl, ImGuiDragDropFlags flags = 0); +// Turns the current plot's Y-axis into a drag and drop source. Don't forget to call EndDragDropSource! +IMPLOT_API bool BeginDragDropSourceY(ImPlotYAxis axis = ImPlotYAxis_1, ImGuiKeyModFlags key_mods = ImGuiKeyModFlags_Ctrl, ImGuiDragDropFlags flags = 0); +// Turns an item in the current plot's legend into drag and drop source. Don't forget to call EndDragDropSource! +IMPLOT_API bool BeginDragDropSourceItem(const char* label_id, ImGuiDragDropFlags flags = 0); +// Ends a drag and drop source (currently just an alias for ImGui::EndDragDropSource). +IMPLOT_API void EndDragDropSource(); + +//----------------------------------------------------------------------------- +// Plot and Item Styling +//----------------------------------------------------------------------------- + +// Styling colors in ImPlot works similarly to styling colors in ImGui, but +// with one important difference. Like ImGui, all style colors are stored in an +// indexable array in ImPlotStyle. You can permanently modify these values through +// GetStyle().Colors, or temporarily modify them with Push/Pop functions below. +// However, by default all style colors in ImPlot default to a special color +// IMPLOT_AUTO_COL. The behavior of this color depends upon the style color to +// which it as applied: +// +// 1) For style colors associated with plot items (e.g. ImPlotCol_Line), +// IMPLOT_AUTO_COL tells ImPlot to color the item with the next unused +// color in the current colormap. Thus, every item will have a different +// color up to the number of colors in the colormap, at which point the +// colormap will roll over. For most use cases, you should not need to +// modify these style colors to anything but IMPLOT_COL_AUTO. You are +// probably better off changing the current colormap. However, if you +// need to explicitly color a particular item you may either Push/Pop +// the style color around the item in question, or use the SetNextXXXStyle +// API below. If you permanently set one of these style colors to a specific +// color, or forget to call Pop, then all subsequent items will be styled +// with the color you set. +// +// 2) For style colors associated with plot styling (e.g. ImPlotCol_PlotBg), +// IMPLOT_AUTO_COL tells ImPlot to set that color from color data in your +// **ImGuiStyle**. The ImGuiCol_ that these style colors default to are +// detailed above, and in general have been mapped to produce plots visually +// consistent with your current ImGui style. Of course, you are free to +// manually set these colors to whatever you like, and further can Push/Pop +// them around individual plots. + +// Provides access to plot style structure for permanant modifications to colors, sizes, etc. +IMPLOT_API ImPlotStyle& GetStyle(); + +// Style plot colors for current ImGui style (default). +IMPLOT_API void StyleColorsAuto(ImPlotStyle* dst = NULL); +// Style plot colors for ImGui "Classic". +IMPLOT_API void StyleColorsClassic(ImPlotStyle* dst = NULL); +// Style plot colors for ImGui "Dark". +IMPLOT_API void StyleColorsDark(ImPlotStyle* dst = NULL); +// Style plot colors for ImGui "Light". +IMPLOT_API void StyleColorsLight(ImPlotStyle* dst = NULL); + +// Use PushStyleX to temporarily modify your ImPlotStyle. The modification +// will last until the matching call to PopStyleX. You MUST call a pop for +// every push, otherwise you will leak memory! This behaves just like ImGui. + +// Temporarily modify a style color. Don't forget to call PopStyleColor! +IMPLOT_API void PushStyleColor(ImPlotCol idx, ImU32 col); +IMPLOT_API void PushStyleColor(ImPlotCol idx, const ImVec4& col); +// Undo temporary style color modification(s). Undo multiple pushes at once by increasing count. +IMPLOT_API void PopStyleColor(int count = 1); + +// Temporarily modify a style variable of float type. Don't forget to call PopStyleVar! +IMPLOT_API void PushStyleVar(ImPlotStyleVar idx, float val); +// Temporarily modify a style variable of int type. Don't forget to call PopStyleVar! +IMPLOT_API void PushStyleVar(ImPlotStyleVar idx, int val); +// Temporarily modify a style variable of ImVec2 type. Don't forget to call PopStyleVar! +IMPLOT_API void PushStyleVar(ImPlotStyleVar idx, const ImVec2& val); +// Undo temporary style variable modification(s). Undo multiple pushes at once by increasing count. +IMPLOT_API void PopStyleVar(int count = 1); + +// The following can be used to modify the style of the next plot item ONLY. They do +// NOT require calls to PopStyleX. Leave style attributes you don't want modified to +// IMPLOT_AUTO or IMPLOT_AUTO_COL. Automatic styles will be deduced from the current +// values in your ImPlotStyle or from Colormap data. + +// Set the line color and weight for the next item only. +IMPLOT_API void SetNextLineStyle(const ImVec4& col = IMPLOT_AUTO_COL, float weight = IMPLOT_AUTO); +// Set the fill color for the next item only. +IMPLOT_API void SetNextFillStyle(const ImVec4& col = IMPLOT_AUTO_COL, float alpha_mod = IMPLOT_AUTO); +// Set the marker style for the next item only. +IMPLOT_API void SetNextMarkerStyle(ImPlotMarker marker = IMPLOT_AUTO, float size = IMPLOT_AUTO, const ImVec4& fill = IMPLOT_AUTO_COL, float weight = IMPLOT_AUTO, const ImVec4& outline = IMPLOT_AUTO_COL); +// Set the error bar style for the next item only. +IMPLOT_API void SetNextErrorBarStyle(const ImVec4& col = IMPLOT_AUTO_COL, float size = IMPLOT_AUTO, float weight = IMPLOT_AUTO); + +// Gets the last item primary color (i.e. its legend icon color) +IMPLOT_API ImVec4 GetLastItemColor(); + +// Returns the null terminated string name for an ImPlotCol. +IMPLOT_API const char* GetStyleColorName(ImPlotCol idx); +// Returns the null terminated string name for an ImPlotMarker. +IMPLOT_API const char* GetMarkerName(ImPlotMarker idx); + +//----------------------------------------------------------------------------- +// Colormaps +//----------------------------------------------------------------------------- + +// Item styling is based on colormaps when the relevant ImPlotCol_XXX is set to +// IMPLOT_AUTO_COL (default). Several built-in colormaps are available. You can +// add and then push/pop your own colormaps as well. To permanently set a colormap, +// modify the Colormap index member of your ImPlotStyle. + +// Colormap data will be ignored and a custom color will be used if you have done one of the following: +// 1) Modified an item style color in your ImPlotStyle to anything other than IMPLOT_AUTO_COL. +// 2) Pushed an item style color using PushStyleColor(). +// 3) Set the next item style with a SetNextXXXStyle function. + +// Add a new colormap. The colormap can be used by pushing either the returned index or the string name with PushColormap. +// The colormap name must be unique and the size must be greater than 1. You will receive an assert otherwise! By default +// colormaps are considered to be qualitative (i.e. discrete). If you want to create a continuous colormap, set #qual=false. +// This will treat the colors you provide as keys, and ImPlot will build a linearly interpolated lookup table that fills +// in the gaps. The memory footprint of this table will be exactly ((size-1)*255+1)*4 bytes. +IMPLOT_API ImPlotColormap AddColormap(const char* name, const ImVec4* cols, int size, bool qual=true); +IMPLOT_API ImPlotColormap AddColormap(const char* name, const ImU32* cols, int size, bool qual=true); + +// Returns the number of available colormaps. +IMPLOT_API int GetColormapCount(); +// Returns a null terminated string name for a colormap given an index. Returns NULL if index is invalid. +IMPLOT_API const char* GetColormapName(ImPlotColormap cmap); +// Returns an index number for a colormap given a valid string name. Returns -1 if name is invalid. +IMPLOT_API ImPlotColormap GetColormapIndex(const char* name); + +// Temporarily switch to one of the built-in (i.e. ImPlotColormap_XXX) or user-added colormaps (i.e. a return value of AddColormap). Don't forget to call PopColormap! +IMPLOT_API void PushColormap(ImPlotColormap cmap); +// Push a colormap by string name. Use built-in names such as "Default", "Deep", "Jet", etc or a string you provided to AddColormap. Don't forget to call PopColormap! +IMPLOT_API void PushColormap(const char* name); +// Undo temporary colormap modification(s). Undo multiple pushes at once by increasing count. +IMPLOT_API void PopColormap(int count = 1); + +// Returns the next color from the current colormap and advances the colormap for the current plot. +// Can also be used with no return value to skip colors if desired. You need to call this between Begin/EndPlot! +IMPLOT_API ImVec4 NextColormapColor(); + +// Colormap utils. If cmap = IMPLOT_AUTO (default), the current colormap is assumed. +// Pass an explicit colormap index (built-in or user added) to specify otherwise. + +// Returns the size of a colormap. +IMPLOT_API int GetColormapSize(ImPlotColormap cmap = IMPLOT_AUTO); +// Returns a color from a colormap given an index >= 0 (modulo will be performed). +IMPLOT_API ImVec4 GetColormapColor(int idx, ImPlotColormap cmap = IMPLOT_AUTO); +// Sample a color from the current colormap given t between 0 and 1. +IMPLOT_API ImVec4 SampleColormap(float t, ImPlotColormap cmap = IMPLOT_AUTO); + +// Shows a vertical color scale with linear spaced ticks using the specified color map. Use double hashes to hide label (e.g. "##NoLabel"). +IMPLOT_API void ColormapScale(const char* label, double scale_min, double scale_max, const ImVec2& size = ImVec2(0,0), ImPlotColormap cmap = IMPLOT_AUTO); +// Shows a horizontal slider with a colormap gradient background. Optionally returns the color sampled at t in [0 1]. +IMPLOT_API bool ColormapSlider(const char* label, float* t, ImVec4* out = NULL, const char* format = "", ImPlotColormap cmap = IMPLOT_AUTO); +// Shows a button with a colormap gradient brackground. +IMPLOT_API bool ColormapButton(const char* label, const ImVec2& size = ImVec2(0,0), ImPlotColormap cmap = IMPLOT_AUTO); + +// When items in a plot sample their color from a colormap, the color is cached and does not change +// unless explicitly overriden. Therefore, if you change the colormap after the item has already been plotted, +// item colors will not update. If you need item colors to resample the new colormap, then use this +// function to bust the cached colors. If #plot_title_id is NULL, then every item in EVERY existing plot +// will be cache busted. Otherwise only the plot specified by #plot_title_id will be busted. For the +// latter, this function must be called in the ImGui window that the plot is in. You should rarely if ever +// need this function, but it is available for applications that require runtime swaps (see Heatmaps demo). +IMPLOT_API void BustColorCache(const char* plot_title_id = NULL); + +//----------------------------------------------------------------------------- +// Miscellaneous +//----------------------------------------------------------------------------- + +// Render icons similar to those that appear in legends (nifty for data lists). +IMPLOT_API void ItemIcon(const ImVec4& col); +IMPLOT_API void ItemIcon(ImU32 col); +IMPLOT_API void ColormapIcon(ImPlotColormap cmap); + +// Get the plot draw list for custom rendering to the current plot area. Call between Begin/EndPlot. +IMPLOT_API ImDrawList* GetPlotDrawList(); +// Push clip rect for rendering to current plot area. Call between Begin/EndPlot. +IMPLOT_API void PushPlotClipRect(); +// Pop plot clip rect. Call between Begin/EndPlot. +IMPLOT_API void PopPlotClipRect(); + +// Shows ImPlot style selector dropdown menu. +IMPLOT_API bool ShowStyleSelector(const char* label); +// Shows ImPlot colormap selector dropdown menu. +IMPLOT_API bool ShowColormapSelector(const char* label); +// Shows ImPlot style editor block (not a window). +IMPLOT_API void ShowStyleEditor(ImPlotStyle* ref = NULL); +// Add basic help/info block for end users (not a window). +IMPLOT_API void ShowUserGuide(); +// Shows ImPlot metrics/debug information. +IMPLOT_API void ShowMetricsWindow(bool* p_popen = NULL); + +//----------------------------------------------------------------------------- +// Demo (add implot_demo.cpp to your sources!) +//----------------------------------------------------------------------------- + +// Shows the ImPlot demo. +IMPLOT_API void ShowDemoWindow(bool* p_open = NULL); + +} // namespace ImPlot diff --git a/DearPyGui/vendor/implot/implot_demo.cpp b/DearPyGui/vendor/implot/implot_demo.cpp new file mode 100644 index 000000000..d76316d6c --- /dev/null +++ b/DearPyGui/vendor/implot/implot_demo.cpp @@ -0,0 +1,1880 @@ +// MIT License + +// Copyright (c) 2021 Evan Pezent + +// 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. + +// ImPlot v0.9 WIP + +#include "implot.h" +#include +#include +#include +#include + +#ifdef _MSC_VER +#define sprintf sprintf_s +#endif + +#ifndef PI +#define PI 3.14159265358979323846 +#endif + +// Encapsulates examples for customizing ImPlot. +namespace MyImPlot { + +// Example for Custom Data and Getters section. +struct Vector2f { + Vector2f(float _x, float _y) { x = _x; y = _y; } + float x, y; +}; + +// Example for Custom Data and Getters section. +struct WaveData { + double X, Amp, Freq, Offset; + WaveData(double x, double amp, double freq, double offset) { X = x; Amp = amp; Freq = freq; Offset = offset; } +}; +ImPlotPoint SineWave(void* wave_data, int idx); +ImPlotPoint SawWave(void* wave_data, int idx); +ImPlotPoint Spiral(void*, int idx); + +// Example for Tables section. +void Sparkline(const char* id, const float* values, int count, float min_v, float max_v, int offset, const ImVec4& col, const ImVec2& size); + +// Example for Custom Plotters and Tooltips section. +void PlotCandlestick(const char* label_id, const double* xs, const double* opens, const double* closes, const double* lows, const double* highs, int count, bool tooltip = true, float width_percent = 0.25f, ImVec4 bullCol = ImVec4(0,1,0,1), ImVec4 bearCol = ImVec4(1,0,0,1)); + +// Example for Custom Styles section. +void StyleSeaborn(); + +} // namespace MyImPlot + +namespace ImPlot { + +void ShowBenchmarkTool(); + +template +inline T RandomRange(T min, T max) { + T scale = rand() / (T) RAND_MAX; + return min + scale * ( max - min ); +} + +ImVec4 RandomColor() { + ImVec4 col; + col.x = RandomRange(0.0f,1.0f); + col.y = RandomRange(0.0f,1.0f); + col.z = RandomRange(0.0f,1.0f); + col.w = 1.0f; + return col; +} + +double RandomGauss() { + static double V1, V2, S; + static int phase = 0; + double X; + if(phase == 0) { + do { + double U1 = (double)rand() / RAND_MAX; + double U2 = (double)rand() / RAND_MAX; + V1 = 2 * U1 - 1; + V2 = 2 * U2 - 1; + S = V1 * V1 + V2 * V2; + } while(S >= 1 || S == 0); + + X = V1 * sqrt(-2 * log(S) / S); + } else + X = V2 * sqrt(-2 * log(S) / S); + phase = 1 - phase; + return X; +} + +template +struct NormalDistribution { + NormalDistribution(double mean, double sd) { + for (int i = 0; i < N; ++i) + Data[i] = RandomGauss()*sd + mean; + } + double Data[N]; +}; + +// utility structure for realtime plot +struct ScrollingBuffer { + int MaxSize; + int Offset; + ImVector Data; + ScrollingBuffer(int max_size = 2000) { + MaxSize = max_size; + Offset = 0; + Data.reserve(MaxSize); + } + void AddPoint(float x, float y) { + if (Data.size() < MaxSize) + Data.push_back(ImVec2(x,y)); + else { + Data[Offset] = ImVec2(x,y); + Offset = (Offset + 1) % MaxSize; + } + } + void Erase() { + if (Data.size() > 0) { + Data.shrink(0); + Offset = 0; + } + } +}; + +// utility structure for realtime plot +struct RollingBuffer { + float Span; + ImVector Data; + RollingBuffer() { + Span = 10.0f; + Data.reserve(2000); + } + void AddPoint(float x, float y) { + float xmod = fmodf(x, Span); + if (!Data.empty() && xmod < Data.back().x) + Data.shrink(0); + Data.push_back(ImVec2(xmod, y)); + } +}; + +// Huge data used by Time Formatting example (~500 MB allocation!) +struct HugeTimeData { + HugeTimeData(double min) { + Ts = new double[Size]; + Ys = new double[Size]; + for (int i = 0; i < Size; ++i) { + Ts[i] = min + i; + Ys[i] = GetY(Ts[i]); + } + } + ~HugeTimeData() { delete[] Ts; delete[] Ys; } + static double GetY(double t) { + return 0.5 + 0.25 * sin(t/86400/12) + 0.005 * sin(t/3600); + } + double* Ts; + double* Ys; + static const int Size = 60*60*24*366; +}; + +void ShowDemoWindow(bool* p_open) { + double DEMO_TIME = ImGui::GetTime(); + static bool show_imgui_metrics = false; + static bool show_implot_metrics = false; + static bool show_imgui_style_editor = false; + static bool show_implot_style_editor = false; + static bool show_implot_benchmark = false; + if (show_imgui_metrics) { + ImGui::ShowMetricsWindow(&show_imgui_metrics); + } + if (show_implot_metrics) { + ImPlot::ShowMetricsWindow(&show_implot_metrics); + } + if (show_imgui_style_editor) { + ImGui::Begin("Style Editor (ImGui)", &show_imgui_style_editor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } + if (show_implot_style_editor) { + ImGui::SetNextWindowSize(ImVec2(415,762), ImGuiCond_Appearing); + ImGui::Begin("Style Editor (ImPlot)", &show_implot_style_editor); + ImPlot::ShowStyleEditor(); + ImGui::End(); + } + if (show_implot_benchmark) { + ImGui::SetNextWindowSize(ImVec2(530,740), ImGuiCond_Appearing); + ImGui::Begin("ImPlot Benchmark Tool", &show_implot_benchmark); + ImPlot::ShowBenchmarkTool(); + ImGui::End(); + return; + } + ImGui::SetNextWindowPos(ImVec2(50, 50), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(600, 750), ImGuiCond_FirstUseEver); + ImGui::Begin("ImPlot Demo", p_open, ImGuiWindowFlags_MenuBar); + if (ImGui::BeginMenuBar()) { + if (ImGui::BeginMenu("Tools")) { + ImGui::MenuItem("Metrics (ImGui)", NULL, &show_imgui_metrics); + ImGui::MenuItem("Metrics (ImPlot)", NULL, &show_implot_metrics); + ImGui::MenuItem("Style Editor (ImGui)", NULL, &show_imgui_style_editor); + ImGui::MenuItem("Style Editor (ImPlot)", NULL, &show_implot_style_editor); + ImGui::MenuItem("Benchmark", NULL, &show_implot_benchmark); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + //------------------------------------------------------------------------- + ImGui::Text("ImPlot says hello. (%s)", IMPLOT_VERSION); + ImGui::Spacing(); + + if (ImGui::CollapsingHeader("Help")) { + ImGui::Text("ABOUT THIS DEMO:"); + ImGui::BulletText("Sections below are demonstrating many aspects of the library."); + ImGui::BulletText("The \"Tools\" menu above gives access to: Style Editors (ImPlot/ImGui)\n" + "and Metrics (general purpose Dear ImGui debugging tool)."); + ImGui::Separator(); + ImGui::Text("PROGRAMMER GUIDE:"); + ImGui::BulletText("See the ShowDemoWindow() code in implot_demo.cpp. <- you are here!"); + ImGui::BulletText("By default, anti-aliased lines are turned OFF."); + ImGui::Indent(); + ImGui::BulletText("Software AA can be enabled globally with ImPlotStyle.AntiAliasedLines."); + ImGui::BulletText("Software AA can be enabled per plot with ImPlotFlags_AntiAliased."); + ImGui::BulletText("AA for plots can be toggled from the plot's context menu."); + ImGui::BulletText("If permitable, you are better off using hardware AA (e.g. MSAA)."); + ImGui::Unindent(); + ImGui::BulletText("If you see visual artifacts, do one of the following:"); + ImGui::Indent(); + ImGui::BulletText("Handle ImGuiBackendFlags_RendererHasVtxOffset for 16-bit indices in your backend."); + ImGui::BulletText("Or, enable 32-bit indices in imconfig.h."); + ImGui::BulletText("Your current configuration is:"); + ImGui::Indent(); + ImGui::BulletText("ImDrawIdx: %d-bit", (int)(sizeof(ImDrawIdx) * 8)); + ImGui::BulletText("ImGuiBackendFlags_RendererHasVtxOffset: %s", (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ? "True" : "False"); + ImGui::Unindent(); + ImGui::Unindent(); +#ifdef IMPLOT_DEMO_USE_DOUBLE + ImGui::BulletText("The demo data precision is: double"); +#else + ImGui::BulletText("The demo data precision is: float"); +#endif + ImGui::Separator(); + ImGui::Text("USER GUIDE:"); + ShowUserGuide(); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Configuration")) { + ImGui::ShowFontSelector("Font"); + ImGui::ShowStyleSelector("ImGui Style"); + ImPlot::ShowStyleSelector("ImPlot Style"); + ImPlot::ShowColormapSelector("ImPlot Colormap"); + float indent = ImGui::CalcItemWidth() - ImGui::GetFrameHeight(); + ImGui::Indent(ImGui::CalcItemWidth() - ImGui::GetFrameHeight()); + ImGui::Checkbox("Anti-Aliased Lines", &ImPlot::GetStyle().AntiAliasedLines); + ImGui::Unindent(indent); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Line Plots")) { + static float xs1[1001], ys1[1001]; + for (int i = 0; i < 1001; ++i) { + xs1[i] = i * 0.001f; + ys1[i] = 0.5f + 0.5f * sinf(50 * (xs1[i] + (float)DEMO_TIME / 10)); + } + static double xs2[11], ys2[11]; + for (int i = 0; i < 11; ++i) { + xs2[i] = i * 0.1f; + ys2[i] = xs2[i] * xs2[i]; + } + ImGui::BulletText("Anti-aliasing can be enabled from the plot's context menu (see Help)."); + if (ImPlot::BeginPlot("Line Plot", "x", "f(x)")) { + ImPlot::PlotLine("sin(x)", xs1, ys1, 1001); + ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle); + ImPlot::PlotLine("x^2", xs2, ys2, 11); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Filled Line Plots")) { + static double xs1[101], ys1[101], ys2[101], ys3[101]; + srand(0); + for (int i = 0; i < 101; ++i) { + xs1[i] = (float)i; + ys1[i] = RandomRange(400.0,450.0); + ys2[i] = RandomRange(275.0,350.0); + ys3[i] = RandomRange(150.0,225.0); + } + static bool show_lines = true; + static bool show_fills = true; + static float fill_ref = 0; + static int shade_mode = 0; + ImGui::Checkbox("Lines",&show_lines); ImGui::SameLine(); + ImGui::Checkbox("Fills",&show_fills); + if (show_fills) { + ImGui::SameLine(); + if (ImGui::RadioButton("To -INF",shade_mode == 0)) + shade_mode = 0; + ImGui::SameLine(); + if (ImGui::RadioButton("To +INF",shade_mode == 1)) + shade_mode = 1; + ImGui::SameLine(); + if (ImGui::RadioButton("To Ref",shade_mode == 2)) + shade_mode = 2; + if (shade_mode == 2) { + ImGui::SameLine(); + ImGui::SetNextItemWidth(100); + ImGui::DragFloat("##Ref",&fill_ref, 1, -100, 500); + } + } + + + ImPlot::SetNextPlotLimits(0,100,0,500); + if (ImPlot::BeginPlot("Stock Prices", "Days", "Price")) { + if (show_fills) { + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); + ImPlot::PlotShaded("Stock 1", xs1, ys1, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref); + ImPlot::PlotShaded("Stock 2", xs1, ys2, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref); + ImPlot::PlotShaded("Stock 3", xs1, ys3, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref); + ImPlot::PopStyleVar(); + } + if (show_lines) { + ImPlot::PlotLine("Stock 1", xs1, ys1, 101); + ImPlot::PlotLine("Stock 2", xs1, ys2, 101); + ImPlot::PlotLine("Stock 3", xs1, ys3, 101); + } + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Shaded Plots##")) { + static float xs[1001], ys[1001], ys1[1001], ys2[1001], ys3[1001], ys4[1001]; + srand(0); + for (int i = 0; i < 1001; ++i) { + xs[i] = i * 0.001f; + ys[i] = 0.25f + 0.25f * sinf(25 * xs[i]) * sinf(5 * xs[i]) + RandomRange(-0.01f, 0.01f); + ys1[i] = ys[i] + RandomRange(0.1f, 0.12f); + ys2[i] = ys[i] - RandomRange(0.1f, 0.12f); + ys3[i] = 0.75f + 0.2f * sinf(25 * xs[i]); + ys4[i] = 0.75f + 0.1f * cosf(25 * xs[i]); + } + static float alpha = 0.25f; + ImGui::DragFloat("Alpha",&alpha,0.01f,0,1); + + if (ImPlot::BeginPlot("Shaded Plots", "X-Axis", "Y-Axis")) { + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, alpha); + ImPlot::PlotShaded("Uncertain Data",xs,ys1,ys2,1001); + ImPlot::PlotLine("Uncertain Data", xs, ys, 1001); + ImPlot::PlotShaded("Overlapping",xs,ys3,ys4,1001); + ImPlot::PlotLine("Overlapping",xs,ys3,1001); + ImPlot::PlotLine("Overlapping",xs,ys4,1001); + ImPlot::PopStyleVar(); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Scatter Plots")) { + srand(0); + static float xs1[100], ys1[100]; + for (int i = 0; i < 100; ++i) { + xs1[i] = i * 0.01f; + ys1[i] = xs1[i] + 0.1f * ((float)rand() / (float)RAND_MAX); + } + static float xs2[50], ys2[50]; + for (int i = 0; i < 50; i++) { + xs2[i] = 0.25f + 0.2f * ((float)rand() / (float)RAND_MAX); + ys2[i] = 0.75f + 0.2f * ((float)rand() / (float)RAND_MAX); + } + + if (ImPlot::BeginPlot("Scatter Plot", NULL, NULL)) { + ImPlot::PlotScatter("Data 1", xs1, ys1, 100); + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); + ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 6, ImVec4(0,1,0,0.5f), IMPLOT_AUTO, ImVec4(0,1,0,1)); + ImPlot::PlotScatter("Data 2", xs2, ys2, 50); + ImPlot::PopStyleVar(); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Stairstep Plots")) { + static float ys1[101], ys2[101]; + for (int i = 0; i < 101; ++i) { + ys1[i] = 0.5f + 0.4f * sinf(50 * i * 0.01f); + ys2[i] = 0.5f + 0.2f * sinf(25 * i * 0.01f); + } + if (ImPlot::BeginPlot("Stairstep Plot", "x", "f(x)")) { + ImPlot::PlotStairs("Signal 1", ys1, 101, 0.01f); + ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 2.0f); + ImPlot::PlotStairs("Signal 2", ys2, 101, 0.01f); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Bar Plots")) { + + static bool horz = false; + static ImS8 midtm[10] = {83, 67, 23, 89, 83, 78, 91, 82, 85, 90}; + static ImS16 final[10] = {80, 62, 56, 99, 55, 78, 88, 78, 90, 100}; + static ImS32 grade[10] = {80, 69, 52, 92, 72, 78, 75, 76, 89, 95}; + + static const char* labels[] = {"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10"}; + static const double positions[] = {0,1,2,3,4,5,6,7,8,9}; + + ImGui::Checkbox("Horizontal",&horz); + + if (horz) { + ImPlot::SetNextPlotLimits(0, 110, -0.5, 9.5, ImGuiCond_Always); + ImPlot::SetNextPlotTicksY(positions, 10, labels); + } + else { + ImPlot::SetNextPlotLimits(-0.5, 9.5, 0, 110, ImGuiCond_Always); + ImPlot::SetNextPlotTicksX(positions, 10, labels); + } + if (ImPlot::BeginPlot("Bar Plot", horz ? "Score" : "Student", horz ? "Student" : "Score", + ImVec2(-1,0), 0, 0, horz ? ImPlotAxisFlags_Invert : 0)) + { + if (horz) { + ImPlot::SetLegendLocation(ImPlotLocation_West, ImPlotOrientation_Vertical); + ImPlot::PlotBarsH("Midterm Exam", midtm, 10, 0.2, -0.2); + ImPlot::PlotBarsH("Final Exam", final, 10, 0.2, 0); + ImPlot::PlotBarsH("Course Grade", grade, 10, 0.2, 0.2); + } + else { + ImPlot::SetLegendLocation(ImPlotLocation_South, ImPlotOrientation_Horizontal); + ImPlot::PlotBars("Midterm Exam", midtm, 10, 0.2, -0.2); + ImPlot::PlotBars("Final Exam", final, 10, 0.2, 0); + ImPlot::PlotBars("Course Grade", grade, 10, 0.2, 0.2); + } + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Error Bars")) { + static float xs[5] = {1,2,3,4,5}; + static float bar[5] = {1,2,5,3,4}; + static float lin1[5] = {8,8,9,7,8}; + static float lin2[5] = {6,7,6,9,6}; + static float err1[5] = {0.2f, 0.4f, 0.2f, 0.6f, 0.4f}; + static float err2[5] = {0.4f, 0.2f, 0.4f, 0.8f, 0.6f}; + static float err3[5] = {0.09f, 0.14f, 0.09f, 0.12f, 0.16f}; + static float err4[5] = {0.02f, 0.08f, 0.15f, 0.05f, 0.2f}; + + + ImPlot::SetNextPlotLimits(0, 6, 0, 10); + if (ImPlot::BeginPlot("##ErrorBars",NULL,NULL)) { + + ImPlot::PlotBars("Bar", xs, bar, 5, 0.5f); + ImPlot::PlotErrorBars("Bar", xs, bar, err1, 5); + + ImPlot::SetNextErrorBarStyle(ImPlot::GetColormapColor(1), 0); + ImPlot::PlotErrorBars("Line", xs, lin1, err1, err2, 5); + ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle); + ImPlot::PlotLine("Line", xs, lin1, 5); + + ImPlot::PushStyleColor(ImPlotCol_ErrorBar, ImPlot::GetColormapColor(2)); + ImPlot::PlotErrorBars("Scatter", xs, lin2, err2, 5); + ImPlot::PlotErrorBarsH("Scatter", xs, lin2, err3, err4, 5); + ImPlot::PopStyleColor(); + ImPlot::PlotScatter("Scatter", xs, lin2, 5); + + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Stem Plots##")) { + static double xs[51], ys1[51], ys2[51]; + for (int i = 0; i < 51; ++i) { + xs[i] = i * 0.02; + ys1[i] = 1.0 + 0.5 * sin(25*xs[i])*cos(2*xs[i]); + ys2[i] = 0.5 + 0.25 * sin(10*xs[i]) * sin(xs[i]); + } + ImPlot::SetNextPlotLimits(0,1,0,1.6); + if (ImPlot::BeginPlot("Stem Plots")) { + + ImPlot::PlotStems("Stems 1",xs,ys1,51); + + ImPlot::SetNextLineStyle(ImVec4(1,0.5f,0,0.75f)); + ImPlot::SetNextMarkerStyle(ImPlotMarker_Square,5,ImVec4(1,0.5f,0,0.25f)); + ImPlot::PlotStems("Stems 2", xs, ys2,51); + + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Infinite Lines")) { + static double vals[] = {0.25, 0.5, 0.75}; + if (ImPlot::BeginPlot("##Infinite")) { + ImPlot::PlotVLines("VLines",vals,3); + ImPlot::PlotHLines("HLines",vals,3); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Pie Charts")) { + static const char* labels1[] = {"Frogs","Hogs","Dogs","Logs"}; + static float data1[] = {0.15f, 0.30f, 0.2f, 0.05f}; + static bool normalize = false; + ImGui::SetNextItemWidth(250); + ImGui::DragFloat4("Values", data1, 0.01f, 0, 1); + if ((data1[0] + data1[1] + data1[2] + data1[3]) < 1) { + ImGui::SameLine(); + ImGui::Checkbox("Normalize", &normalize); + } + + ImPlot::SetNextPlotLimits(0,1,0,1,ImGuiCond_Always); + if (ImPlot::BeginPlot("##Pie1", NULL, NULL, ImVec2(250,250), ImPlotFlags_Equal | ImPlotFlags_NoMousePos, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations)) { + ImPlot::PlotPieChart(labels1, data1, 4, 0.5, 0.5, 0.4, normalize, "%.2f"); + ImPlot::EndPlot(); + } + + ImGui::SameLine(); + + static const char* labels2[] = {"A","B","C","D","E"}; + static int data2[] = {1,1,2,3,5}; + + ImPlot::PushColormap(ImPlotColormap_Pastel); + ImPlot::SetNextPlotLimits(0,1,0,1,ImGuiCond_Always); + if (ImPlot::BeginPlot("##Pie2", NULL, NULL, ImVec2(250,250), ImPlotFlags_Equal | ImPlotFlags_NoMousePos, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations)) { + ImPlot::PlotPieChart(labels2, data2, 5, 0.5, 0.5, 0.4, true, "%.0f", 180); + ImPlot::EndPlot(); + } + ImPlot::PopColormap(); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Heatmaps")) { + static float values1[7][7] = {{0.8f, 2.4f, 2.5f, 3.9f, 0.0f, 4.0f, 0.0f}, + {2.4f, 0.0f, 4.0f, 1.0f, 2.7f, 0.0f, 0.0f}, + {1.1f, 2.4f, 0.8f, 4.3f, 1.9f, 4.4f, 0.0f}, + {0.6f, 0.0f, 0.3f, 0.0f, 3.1f, 0.0f, 0.0f}, + {0.7f, 1.7f, 0.6f, 2.6f, 2.2f, 6.2f, 0.0f}, + {1.3f, 1.2f, 0.0f, 0.0f, 0.0f, 3.2f, 5.1f}, + {0.1f, 2.0f, 0.0f, 1.4f, 0.0f, 1.9f, 6.3f}}; + static float scale_min = 0; + static float scale_max = 6.3f; + static const char* xlabels[] = {"C1","C2","C3","C4","C5","C6","C7"}; + static const char* ylabels[] = {"R1","R2","R3","R4","R5","R6","R7"}; + + static ImPlotColormap map = ImPlotColormap_Viridis; + if (ImPlot::ColormapButton(ImPlot::GetColormapName(map),ImVec2(225,0),map)) { + map = (map + 1) % ImPlot::GetColormapCount(); + // We bust the color cache of our plots so that item colors will + // resample the new colormap in the event that they have already + // been created. See documentation in implot.h. + BustColorCache("##Heatmap1"); + BustColorCache("##Heatmap2"); + } + + ImGui::SameLine(); + ImGui::LabelText("##Colormap Index", "%s", "Change Colormap"); + ImGui::SetNextItemWidth(225); + ImGui::DragFloatRange2("Min / Max",&scale_min, &scale_max, 0.01f, -20, 20); + static ImPlotAxisFlags axes_flags = ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_NoTickMarks; + + ImPlot::PushColormap(map); + SetNextPlotTicksX(0 + 1.0/14.0, 1 - 1.0/14.0, 7, xlabels); + SetNextPlotTicksY(1 - 1.0/14.0, 0 + 1.0/14.0, 7, ylabels); + if (ImPlot::BeginPlot("##Heatmap1",NULL,NULL,ImVec2(225,225),ImPlotFlags_NoLegend|ImPlotFlags_NoMousePos,axes_flags,axes_flags)) { + ImPlot::PlotHeatmap("heat",values1[0],7,7,scale_min,scale_max); + ImPlot::EndPlot(); + } + ImGui::SameLine(); + ImPlot::ColormapScale("##HeatScale",scale_min, scale_max, ImVec2(60,225)); + + ImGui::SameLine(); + + const int size = 200; + static double values2[size*size]; + srand((unsigned int)(DEMO_TIME*1000000)); + for (int i = 0; i < size*size; ++i) + values2[i] = RandomRange(0.0,1.0); + + ImPlot::SetNextPlotLimits(-1,1,-1,1); + if (ImPlot::BeginPlot("##Heatmap2",NULL,NULL,ImVec2(225,225),0,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations)) { + ImPlot::PlotHeatmap("heat1",values2,size,size,0,1,NULL); + ImPlot::PlotHeatmap("heat2",values2,size,size,0,1,NULL, ImPlotPoint(-1,-1), ImPlotPoint(0,0)); + ImPlot::EndPlot(); + } + ImPlot::PopColormap(); + + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Histograms")) { + static int bins = 50; + static bool cumulative = false; + static bool density = true; + static bool outliers = true; + static double mu = 5; + static double sigma = 2; + static NormalDistribution<10000> dist(mu, sigma); + static double x[100]; + static double y[100]; + if (density) { + for (int i = 0; i < 100; ++i) { + x[i] = -3 + 16 * (double)i/99.0; + y[i] = exp( - (x[i]-mu)*(x[i]-mu) / (2*sigma*sigma)) / (sigma * sqrt(2*3.141592653589793238)); + } + if (cumulative) { + for (int i = 1; i < 100; ++i) + y[i] += y[i-1]; + for (int i = 0; i < 100; ++i) + y[i] /= y[99]; + } + } + ImGui::SetNextItemWidth(200); + if (ImGui::RadioButton("Sqrt",bins==ImPlotBin_Sqrt)) { bins = ImPlotBin_Sqrt; } ImGui::SameLine(); + if (ImGui::RadioButton("Sturges",bins==ImPlotBin_Sturges)) { bins = ImPlotBin_Sturges; } ImGui::SameLine(); + if (ImGui::RadioButton("Rice",bins==ImPlotBin_Rice)) { bins = ImPlotBin_Rice; } ImGui::SameLine(); + if (ImGui::RadioButton("Scott",bins==ImPlotBin_Scott)) { bins = ImPlotBin_Scott; } ImGui::SameLine(); + if (ImGui::RadioButton("N Bins",bins>=0)) bins = 50; + if (bins>=0) { + ImGui::SameLine(); + ImGui::SetNextItemWidth(200); + ImGui::SliderInt("##Bins", &bins, 1, 100); + } + ImGui::Checkbox("Density", &density); + ImGui::SameLine(); + ImGui::Checkbox("Cumulative", &cumulative); + ImGui::SameLine(); + static bool range = false; + ImGui::Checkbox("Range", &range); + static float rmin = -3; + static float rmax = 13; + if (range) { + ImGui::SameLine(); + ImGui::SetNextItemWidth(200); + ImGui::DragFloat2("##Range",&rmin,0.1f,-3,13); + ImGui::SameLine(); + ImGui::Checkbox("Outliers",&outliers); + } + ImPlot::SetNextPlotLimits(-3, 13, 0, 0.25); + if (ImPlot::BeginPlot("##Histograms")) { + ImPlot::SetNextFillStyle(IMPLOT_AUTO_COL, 0.5f); + ImPlot::PlotHistogram("Empirical", dist.Data, 10000, bins, cumulative, density, range ? ImPlotRange(rmin,rmax) : ImPlotRange(), outliers); + if (density && outliers) + ImPlot::PlotLine("Theoretical",x,y,100); + ImPlot::EndPlot(); + } + + static int count = 500000; + static int xybins[2] = {200,200}; + static bool density2 = false; + ImGui::SliderInt("Count",&count,100,500000); + ImGui::SliderInt2("Bins",xybins,1,500); + ImGui::SameLine(); + ImGui::Checkbox("Density##2",&density2); + static NormalDistribution<500000> dist1(1, 2); + static NormalDistribution<500000> dist2(1, 1); + double max_count = 0; + ImPlot::PushColormap("Twilight"); + if (ImPlot::BeginPlot("##Hist2D",0,0,ImVec2(ImGui::GetContentRegionAvail().x-100-ImGui::GetStyle().ItemSpacing.x,0),0,ImPlotAxisFlags_AutoFit,ImPlotAxisFlags_AutoFit)) { + max_count = ImPlot::PlotHistogram2D("Hist2D",dist1.Data,dist2.Data,count,xybins[0],xybins[1],density2,ImPlotLimits(-6,6,-6,6)); + ImPlot::EndPlot(); + } + ImGui::SameLine(); + ImPlot::ColormapScale(density2 ? "Density" : "Count",0,max_count,ImVec2(100,0)); + ImPlot::PopColormap(); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Digital Plots")) { + ImGui::BulletText("Digital plots do not respond to Y drag and zoom, so that"); + ImGui::Indent(); + ImGui::Text("you can drag analog plots over the rising/falling digital edge."); + ImGui::Unindent(); + + static bool paused = false; + static ScrollingBuffer dataDigital[2]; + static ScrollingBuffer dataAnalog[2]; + static bool showDigital[2] = {true, false}; + static bool showAnalog[2] = {true, false}; + + char label[32]; + ImGui::Checkbox("digital_0", &showDigital[0]); ImGui::SameLine(); + ImGui::Checkbox("digital_1", &showDigital[1]); ImGui::SameLine(); + ImGui::Checkbox("analog_0", &showAnalog[0]); ImGui::SameLine(); + ImGui::Checkbox("analog_1", &showAnalog[1]); + + static float t = 0; + if (!paused) { + t += ImGui::GetIO().DeltaTime; + //digital signal values + if (showDigital[0]) + dataDigital[0].AddPoint(t, sinf(2*t) > 0.45); + if (showDigital[1]) + dataDigital[1].AddPoint(t, sinf(2*t) < 0.45); + //Analog signal values + if (showAnalog[0]) + dataAnalog[0].AddPoint(t, sinf(2*t)); + if (showAnalog[1]) + dataAnalog[1].AddPoint(t, cosf(2*t)); + } + ImPlot::SetNextPlotLimitsY(-1, 1); + ImPlot::SetNextPlotLimitsX(t - 10.0, t, paused ? ImGuiCond_Once : ImGuiCond_Always); + if (ImPlot::BeginPlot("##Digital")) { + for (int i = 0; i < 2; ++i) { + if (showDigital[i] && dataDigital[i].Data.size() > 0) { + sprintf(label, "digital_%d", i); + ImPlot::PlotDigital(label, &dataDigital[i].Data[0].x, &dataDigital[i].Data[0].y, dataDigital[i].Data.size(), dataDigital[i].Offset, 2 * sizeof(float)); + } + } + for (int i = 0; i < 2; ++i) { + if (showAnalog[i]) { + sprintf(label, "analog_%d", i); + if (dataAnalog[i].Data.size() > 0) + ImPlot::PlotLine(label, &dataAnalog[i].Data[0].x, &dataAnalog[i].Data[0].y, dataAnalog[i].Data.size(), dataAnalog[i].Offset, 2 * sizeof(float)); + } + } + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Images")) { + ImGui::BulletText("Below we are displaying the font texture, which is the only texture we have\naccess to in this demo."); + ImGui::BulletText("Use the 'ImTextureID' type as storage to pass pointers or identifiers to your\nown texture data."); + ImGui::BulletText("See ImGui Wiki page 'Image Loading and Displaying Examples'."); + static ImVec2 bmin(0,0); + static ImVec2 bmax(1,1); + static ImVec2 uv0(0,0); + static ImVec2 uv1(1,1); + static ImVec4 tint(1,1,1,1); + ImGui::SliderFloat2("Min", &bmin.x, -2, 2, "%.1f"); + ImGui::SliderFloat2("Max", &bmax.x, -2, 2, "%.1f"); + ImGui::SliderFloat2("UV0", &uv0.x, -2, 2, "%.1f"); + ImGui::SliderFloat2("UV1", &uv1.x, -2, 2, "%.1f"); + ImGui::ColorEdit4("Tint",&tint.x); + if (ImPlot::BeginPlot("##image")) { + ImPlot::PlotImage("my image",ImGui::GetIO().Fonts->TexID, bmin, bmax, uv0, uv1, tint); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Realtime Plots")) { + ImGui::BulletText("Move your mouse to change the data!"); + ImGui::BulletText("This example assumes 60 FPS. Higher FPS requires larger buffer size."); + static ScrollingBuffer sdata1, sdata2; + static RollingBuffer rdata1, rdata2; + ImVec2 mouse = ImGui::GetMousePos(); + static float t = 0; + t += ImGui::GetIO().DeltaTime; + sdata1.AddPoint(t, mouse.x * 0.0005f); + rdata1.AddPoint(t, mouse.x * 0.0005f); + sdata2.AddPoint(t, mouse.y * 0.0005f); + rdata2.AddPoint(t, mouse.y * 0.0005f); + + static float history = 10.0f; + ImGui::SliderFloat("History",&history,1,30,"%.1f s"); + rdata1.Span = history; + rdata2.Span = history; + + static ImPlotAxisFlags rt_axis = ImPlotAxisFlags_NoTickLabels; + ImPlot::SetNextPlotLimitsX(t - history, t, ImGuiCond_Always); + if (ImPlot::BeginPlot("##Scrolling", NULL, NULL, ImVec2(-1,150), 0, rt_axis, rt_axis | ImPlotAxisFlags_LockMin)) { + ImPlot::PlotShaded("Data 1", &sdata1.Data[0].x, &sdata1.Data[0].y, sdata1.Data.size(), 0, sdata1.Offset, 2 * sizeof(float)); + ImPlot::PlotLine("Data 2", &sdata2.Data[0].x, &sdata2.Data[0].y, sdata2.Data.size(), sdata2.Offset, 2*sizeof(float)); + ImPlot::EndPlot(); + } + ImPlot::SetNextPlotLimitsX(0, history, ImGuiCond_Always); + if (ImPlot::BeginPlot("##Rolling", NULL, NULL, ImVec2(-1,150), 0, rt_axis, rt_axis)) { + ImPlot::PlotLine("Data 1", &rdata1.Data[0].x, &rdata1.Data[0].y, rdata1.Data.size(), 0, 2 * sizeof(float)); + ImPlot::PlotLine("Data 2", &rdata2.Data[0].x, &rdata2.Data[0].y, rdata2.Data.size(), 0, 2 * sizeof(float)); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Markers and Text")) { + static float mk_size = ImPlot::GetStyle().MarkerSize; + static float mk_weight = ImPlot::GetStyle().MarkerWeight; + ImGui::DragFloat("Marker Size",&mk_size,0.1f,2.0f,10.0f,"%.2f px"); + ImGui::DragFloat("Marker Weight", &mk_weight,0.05f,0.5f,3.0f,"%.2f px"); + + ImPlot::SetNextPlotLimits(0, 10, 0, 12); + if (ImPlot::BeginPlot("##MarkerStyles", NULL, NULL, ImVec2(-1,0), ImPlotFlags_CanvasOnly, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations)) { + ImS8 xs[2] = {1,4}; + ImS8 ys[2] = {10,11}; + + // filled markers + for (int m = 0; m < ImPlotMarker_COUNT; ++m) { + ImGui::PushID(m); + ImPlot::SetNextMarkerStyle(m, mk_size, IMPLOT_AUTO_COL, mk_weight); + ImPlot::PlotLine("##Filled", xs, ys, 2); + ImGui::PopID(); + ys[0]--; ys[1]--; + } + xs[0] = 6; xs[1] = 9; ys[0] = 10; ys[1] = 11; + // open markers + for (int m = 0; m < ImPlotMarker_COUNT; ++m) { + ImGui::PushID(m); + ImPlot::SetNextMarkerStyle(m, mk_size, ImVec4(0,0,0,0), mk_weight); + ImPlot::PlotLine("##Open", xs, ys, 2); + ImGui::PopID(); + ys[0]--; ys[1]--; + } + + ImPlot::PlotText("Filled Markers", 2.5f, 6.0f); + ImPlot::PlotText("Open Markers", 7.5f, 6.0f); + + ImPlot::PushStyleColor(ImPlotCol_InlayText, ImVec4(1,0,1,1)); + ImPlot::PlotText("Vertical Text", 5.0f, 6.0f, true); + ImPlot::PopStyleColor(); + + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Log Scale")) { + static double xs[1001], ys1[1001], ys2[1001], ys3[1001]; + for (int i = 0; i < 1001; ++i) { + xs[i] = i*0.1f; + ys1[i] = sin(xs[i]) + 1; + ys2[i] = log(xs[i]); + ys3[i] = pow(10.0, xs[i]); + } + ImGui::BulletText("Open the plot context menu (right click) to change scales."); + + ImPlot::SetNextPlotLimits(0.1, 100, 0, 10); + if (ImPlot::BeginPlot("Log Plot", NULL, NULL, ImVec2(-1,0), 0, ImPlotAxisFlags_LogScale )) { + ImPlot::PlotLine("f(x) = x", xs, xs, 1001); + ImPlot::PlotLine("f(x) = sin(x)+1", xs, ys1, 1001); + ImPlot::PlotLine("f(x) = log(x)", xs, ys2, 1001); + ImPlot::PlotLine("f(x) = 10^x", xs, ys3, 21); + ImPlot::EndPlot(); + } + } + if (ImGui::CollapsingHeader("Time Formatted Axes")) { + + static double t_min = 1609459200; // 01/01/2021 @ 12:00:00am (UTC) + static double t_max = 1640995200; // 01/01/2022 @ 12:00:00am (UTC) + + ImGui::BulletText("When ImPlotAxisFlags_Time is enabled on the X-Axis, values are interpreted as\n" + "UNIX timestamps in seconds and axis labels are formated as date/time."); + ImGui::BulletText("By default, labels are in UTC time but can be set to use local time instead."); + + ImGui::Checkbox("Local Time",&ImPlot::GetStyle().UseLocalTime); + ImGui::SameLine(); + ImGui::Checkbox("ISO 8601",&ImPlot::GetStyle().UseISO8601); + ImGui::SameLine(); + ImGui::Checkbox("24 Hour Clock",&ImPlot::GetStyle().Use24HourClock); + + static HugeTimeData* data = NULL; + if (data == NULL) { + ImGui::SameLine(); + if (ImGui::Button("Generate Huge Data (~500MB!)")) { + static HugeTimeData sdata(t_min); + data = &sdata; + } + } + + ImPlot::SetNextPlotLimits(t_min,t_max,0,1); + if (ImPlot::BeginPlot("##Time", NULL, NULL, ImVec2(-1,0), 0, ImPlotAxisFlags_Time)) { + if (data != NULL) { + // downsample our data + int downsample = (int)ImPlot::GetPlotLimits().X.Size() / 1000 + 1; + int start = (int)(ImPlot::GetPlotLimits().X.Min - t_min); + start = start < 0 ? 0 : start > HugeTimeData::Size - 1 ? HugeTimeData::Size - 1 : start; + int end = (int)(ImPlot::GetPlotLimits().X.Max - t_min) + 1000; + end = end < 0 ? 0 : end > HugeTimeData::Size - 1 ? HugeTimeData::Size - 1 : end; + int size = (end - start)/downsample; + // plot it + ImPlot::PlotLine("Time Series", &data->Ts[start], &data->Ys[start], size, 0, sizeof(double)*downsample); + } + // plot time now + double t_now = (double)time(0); + double y_now = HugeTimeData::GetY(t_now); + ImPlot::PlotScatter("Now",&t_now,&y_now,1); + ImPlot::Annotate(t_now,y_now,ImVec2(10,10),ImPlot::GetLastItemColor(),"Now"); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Multiple Y-Axes")) { + static float xs[1001], xs2[1001], ys1[1001], ys2[1001], ys3[1001]; + for (int i = 0; i < 1001; ++i) { + xs[i] = (i*0.1f); + ys1[i] = sinf(xs[i]) * 3 + 1; + ys2[i] = cosf(xs[i]) * 0.2f + 0.5f; + ys3[i] = sinf(xs[i]+0.5f) * 100 + 200; + xs2[i] = xs[i] + 10.0f; + } + static bool y2_axis = true; + static bool y3_axis = true; + ImGui::Checkbox("Y-Axis 2", &y2_axis); + ImGui::SameLine(); + ImGui::Checkbox("Y-Axis 3", &y3_axis); + ImGui::SameLine(); + + // you can fit axes programatically + ImGui::SameLine(); if (ImGui::Button("Fit X")) ImPlot::FitNextPlotAxes(true, false, false, false); + ImGui::SameLine(); if (ImGui::Button("Fit Y")) ImPlot::FitNextPlotAxes(false, true, false, false); + ImGui::SameLine(); if (ImGui::Button("Fit Y2")) ImPlot::FitNextPlotAxes(false, false, true, false); + ImGui::SameLine(); if (ImGui::Button("Fit Y3")) ImPlot::FitNextPlotAxes(false, false, false, true); + + ImPlot::SetNextPlotLimits(0.1, 100, 0, 10); + ImPlot::SetNextPlotLimitsY(0, 1, ImGuiCond_Once, 1); + ImPlot::SetNextPlotLimitsY(0, 300, ImGuiCond_Once, 2); + if (ImPlot::BeginPlot("Multi-Axis Plot", NULL, "Y-Axis 1", ImVec2(-1,0), + (y2_axis ? ImPlotFlags_YAxis2 : 0) | + (y3_axis ? ImPlotFlags_YAxis3 : 0), + ImPlotAxisFlags_None, ImPlotAxisFlags_None, ImPlotAxisFlags_NoGridLines, ImPlotAxisFlags_NoGridLines, + "Y-Axis 2", "Y-Axis 3")) { + ImPlot::PlotLine("f(x) = x", xs, xs, 1001); + ImPlot::PlotLine("f(x) = sin(x)*3+1", xs, ys1, 1001); + if (y2_axis) { + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + ImPlot::PlotLine("f(x) = cos(x)*.2+.5 (Y2)", xs, ys2, 1001); + } + if (y3_axis) { + ImPlot::SetPlotYAxis(ImPlotYAxis_3); + ImPlot::PlotLine("f(x) = sin(x+.5)*100+200 (Y3)", xs2, ys3, 1001); + } + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Linked Axes")) { + static double xmin = 0, xmax = 1, ymin = 0, ymax = 1; + static bool linkx = true, linky = true; + int data[2] = {0,1}; + ImGui::Checkbox("Link X", &linkx); + ImGui::SameLine(); + ImGui::Checkbox("Link Y", &linky); + ImPlot::LinkNextPlotLimits(linkx ? &xmin : NULL , linkx ? &xmax : NULL, linky ? &ymin : NULL, linky ? &ymax : NULL); + if (ImPlot::BeginPlot("Plot A")) { + ImPlot::PlotLine("Line",data,2); + ImPlot::EndPlot(); + } + ImPlot::LinkNextPlotLimits(linkx ? &xmin : NULL , linkx ? &xmax : NULL, linky ? &ymin : NULL, linky ? &ymax : NULL); + if (ImPlot::BeginPlot("Plot B")) { + ImPlot::PlotLine("Line",data,2); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Equal Axes")) { + static double xs[1000], ys[1000]; + for (int i = 0; i < 1000; ++i) { + double angle = i * 2 * PI / 999.0; + xs[i] = cos(angle); ys[i] = sin(angle); + } + ImPlot::SetNextPlotLimits(-1,1,-1,1); + if (ImPlot::BeginPlot("",0,0,ImVec2(-1,0),ImPlotFlags_Equal)) { + ImPlot::PlotLine("Circle",xs,ys,1000); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Querying")) { + static ImVector data; + static ImPlotLimits range, query; + + ImGui::BulletText("Ctrl + click in the plot area to draw points."); + ImGui::BulletText("Middle click (or Ctrl + right click) and drag to create a query rect."); + ImGui::Indent(); + ImGui::BulletText("Hold Alt to expand query horizontally."); + ImGui::BulletText("Hold Shift to expand query vertically."); + ImGui::BulletText("The query rect can be dragged after it's created."); + ImGui::Unindent(); + + if (ImPlot::BeginPlot("##Drawing", NULL, NULL, ImVec2(-1,0), ImPlotFlags_Query, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations)) { + if (ImPlot::IsPlotHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) { + ImPlotPoint pt = ImPlot::GetPlotMousePos(); + data.push_back(pt); + } + if (data.size() > 0) + ImPlot::PlotScatter("Points", &data[0].x, &data[0].y, data.size(), 0, 2 * sizeof(double)); + if (ImPlot::IsPlotQueried() && data.size() > 0) { + ImPlotLimits range2 = ImPlot::GetPlotQuery(); + int cnt = 0; + ImPlotPoint avg; + for (int i = 0; i < data.size(); ++i) { + if (range2.Contains(data[i].x, data[i].y)) { + avg.x += data[i].x; + avg.y += data[i].y; + cnt++; + } + } + if (cnt > 0) { + avg.x = avg.x / cnt; + avg.y = avg.y / cnt; + ImPlot::SetNextMarkerStyle(ImPlotMarker_Square); + ImPlot::PlotScatter("Average", &avg.x, &avg.y, 1); + } + } + range = ImPlot::GetPlotLimits(); + query = ImPlot::GetPlotQuery(); + ImPlot::EndPlot(); + } + ImGui::Text("The current plot limits are: [%g,%g,%g,%g]", range.X.Min, range.X.Max, range.Y.Min, range.Y.Max); + ImGui::Text("The current query limits are: [%g,%g,%g,%g]", query.X.Min, query.X.Max, query.Y.Min, query.Y.Max); + + ImGui::Separator(); + + // mimic's soulthread's imgui_plot demo + static float x_data[512]; + static float y_data1[512]; + static float y_data2[512]; + static float y_data3[512]; + static float sampling_freq = 44100; + static float freq = 500; + for (size_t i = 0; i < 512; ++i) { + const float t = i / sampling_freq; + x_data[i] = t; + const float arg = 2 * 3.14f * freq * t; + y_data1[i] = sinf(arg); + y_data2[i] = y_data1[i] * -0.6f + sinf(2 * arg) * 0.4f; + y_data3[i] = y_data2[i] * -0.6f + sinf(3 * arg) * 0.4f; + } + ImGui::BulletText("Query the first plot to render a subview in the second plot (see above for controls)."); + ImPlot::SetNextPlotLimits(0,0.01,-1,1); + ImPlotAxisFlags flags = ImPlotAxisFlags_NoTickLabels; + ImPlotLimits query2; + if (ImPlot::BeginPlot("##View1",NULL,NULL,ImVec2(-1,150), ImPlotFlags_Query, flags, flags)) { + ImPlot::PlotLine("Signal 1", x_data, y_data1, 512); + ImPlot::PlotLine("Signal 2", x_data, y_data2, 512); + ImPlot::PlotLine("Signal 3", x_data, y_data3, 512); + query2 = ImPlot::GetPlotQuery(); + ImPlot::EndPlot(); + } + ImPlot::SetNextPlotLimits(query2.X.Min, query2.X.Max, query2.Y.Min, query2.Y.Max, ImGuiCond_Always); + if (ImPlot::BeginPlot("##View2",NULL,NULL,ImVec2(-1,150), ImPlotFlags_CanvasOnly, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations)) { + ImPlot::PlotLine("Signal 1", x_data, y_data1, 512); + ImPlot::PlotLine("Signal 2", x_data, y_data2, 512); + ImPlot::PlotLine("Signal 3", x_data, y_data3, 512); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Legend")) { + static ImPlotLocation loc = ImPlotLocation_East; + static bool h = false; static bool o = true; + ImGui::CheckboxFlags("North", (unsigned int*)&loc, ImPlotLocation_North); ImGui::SameLine(); + ImGui::CheckboxFlags("South", (unsigned int*)&loc, ImPlotLocation_South); ImGui::SameLine(); + ImGui::CheckboxFlags("West", (unsigned int*)&loc, ImPlotLocation_West); ImGui::SameLine(); + ImGui::CheckboxFlags("East", (unsigned int*)&loc, ImPlotLocation_East); ImGui::SameLine(); + ImGui::Checkbox("Horizontal##2", &h); ImGui::SameLine(); + ImGui::Checkbox("Outside", &o); + + ImGui::SliderFloat2("LegendPadding", (float*)&GetStyle().LegendPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LegendInnerPadding", (float*)&GetStyle().LegendInnerPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat2("LegendSpacing", (float*)&GetStyle().LegendSpacing, 0.0f, 5.0f, "%.0f"); + + if (ImPlot::BeginPlot("##Legend","x","y",ImVec2(-1,0))) { + ImPlot::SetLegendLocation(loc, h ? ImPlotOrientation_Horizontal : ImPlotOrientation_Vertical, o); + static MyImPlot::WaveData data1(0.001, 0.2, 2, 0.75); + static MyImPlot::WaveData data2(0.001, 0.2, 4, 0.25); + static MyImPlot::WaveData data3(0.001, 0.2, 6, 0.5); + ImPlot::PlotLineG("Item 1", MyImPlot::SineWave, &data1, 1000); // "Item 1" added to legend + ImPlot::PlotLineG("Item 2##IDText", MyImPlot::SawWave, &data2, 1000); // "Item 2" added to legend, text after ## used for ID only + ImPlot::PlotLineG("##NotListed", MyImPlot::SawWave, &data3, 1000); // plotted, but not added to legend + ImPlot::PlotLineG("Item 3", MyImPlot::SineWave, &data1, 1000); // "Item 3" added to legend + ImPlot::PlotLineG("Item 3", MyImPlot::SawWave, &data2, 1000); // combined with previous "Item 3" + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Drag Lines and Points")) { + ImGui::BulletText("Click and drag the horizontal and vertical lines."); + static double x1 = 0.2; + static double x2 = 0.8; + static double y1 = 0.25; + static double y2 = 0.75; + static double f = 0.1; + static bool show_labels = true; + ImGui::Checkbox("Show Labels##1",&show_labels); + if (ImPlot::BeginPlot("##guides",0,0,ImVec2(-1,0),ImPlotFlags_YAxis2)) { + ImPlot::DragLineX("x1",&x1,show_labels); + ImPlot::DragLineX("x2",&x2,show_labels); + ImPlot::DragLineY("y1",&y1,show_labels); + ImPlot::DragLineY("y2",&y2,show_labels); + double xs[1000], ys[1000]; + for (int i = 0; i < 1000; ++i) { + xs[i] = (x2+x1)/2+fabs(x2-x1)*(i/1000.0f - 0.5f); + ys[i] = (y1+y2)/2+fabs(y2-y1)/2*sin(f*i/10); + } + ImPlot::PlotLine("Interactive Data", xs, ys, 1000); + ImPlot::SetPlotYAxis(ImPlotYAxis_2); + ImPlot::DragLineY("f",&f,show_labels,ImVec4(1,0.5f,1,1)); + ImPlot::EndPlot(); + } + ImGui::BulletText("Click and drag any point."); + ImGui::Checkbox("Show Labels##2",&show_labels); + ImPlotAxisFlags flags = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoTickMarks; + if (ImPlot::BeginPlot("##Bezier",0,0,ImVec2(-1,0),ImPlotFlags_CanvasOnly,flags,flags)) { + static ImPlotPoint P[] = {ImPlotPoint(.05f,.05f), ImPlotPoint(0.2,0.4), ImPlotPoint(0.8,0.6), ImPlotPoint(.95f,.95f)}; + static ImPlotPoint B[100]; + for (int i = 0; i < 100; ++i) { + double t = i / 99.0; + double u = 1 - t; + double w1 = u*u*u; + double w2 = 3*u*u*t; + double w3 = 3*u*t*t; + double w4 = t*t*t; + B[i] = ImPlotPoint(w1*P[0].x + w2*P[1].x + w3*P[2].x + w4*P[3].x, w1*P[0].y + w2*P[1].y + w3*P[2].y + w4*P[3].y); + } + ImPlot::SetNextLineStyle(ImVec4(0,0.9f,0,1), 2); + ImPlot::PlotLine("##bez",&B[0].x, &B[0].y, 100, 0, sizeof(ImPlotPoint)); + ImPlot::SetNextLineStyle(ImVec4(1,0.5f,1,1)); + ImPlot::PlotLine("##h1",&P[0].x, &P[0].y, 2, 0, sizeof(ImPlotPoint)); + ImPlot::SetNextLineStyle(ImVec4(0,0.5f,1,1)); + ImPlot::PlotLine("##h2",&P[2].x, &P[2].y, 2, 0, sizeof(ImPlotPoint)); + ImPlot::DragPoint("P0",&P[0].x,&P[0].y, show_labels, ImVec4(0,0.9f,0,1)); + ImPlot::DragPoint("P1",&P[1].x,&P[1].y, show_labels, ImVec4(1,0.5f,1,1)); + ImPlot::DragPoint("P2",&P[2].x,&P[2].y, show_labels, ImVec4(0,0.5f,1,1)); + ImPlot::DragPoint("P3",&P[3].x,&P[3].y, show_labels, ImVec4(0,0.9f,0,1)); + ImPlot::EndPlot(); + } + } + if (ImGui::CollapsingHeader("Annotations")) { + static bool clamp = false; + ImGui::Checkbox("Clamp",&clamp); + ImPlot::SetNextPlotLimits(0,2,0,1); + if (ImPlot::BeginPlot("##Annotations")) { + + static float p[] = {0.25f, 0.25f, 0.75f, 0.75f, 0.25f}; + ImPlot::PlotScatter("##Points",&p[0],&p[1],4); + ImVec4 col = GetLastItemColor(); + clamp ? ImPlot::AnnotateClamped(0.25,0.25,ImVec2(-15,15),col,"BL") : ImPlot::Annotate(0.25,0.25,ImVec2(-15,15),col,"BL"); + clamp ? ImPlot::AnnotateClamped(0.75,0.25,ImVec2(15,15),col,"BR") : ImPlot::Annotate(0.75,0.25,ImVec2(15,15),col,"BR"); + clamp ? ImPlot::AnnotateClamped(0.75,0.75,ImVec2(15,-15),col,"TR") : ImPlot::Annotate(0.75,0.75,ImVec2(15,-15),col,"TR"); + clamp ? ImPlot::AnnotateClamped(0.25,0.75,ImVec2(-15,-15),col,"TL") : ImPlot::Annotate(0.25,0.75,ImVec2(-15,-15),col,"TL"); + clamp ? ImPlot::AnnotateClamped(0.5,0.5,ImVec2(0,0),col,"Center") : ImPlot::Annotate(0.5,0.5,ImVec2(0,0),col,"Center"); + + float bx[] = {1.2f,1.5f,1.8f}; + float by[] = {0.25f, 0.5f, 0.75f}; + ImPlot::PlotBars("##Bars",bx,by,3,0.2); + for (int i = 0; i < 3; ++i) + ImPlot::Annotate(bx[i],by[i],ImVec2(0,-5),"B[%d]=%.2f",i,by[i]); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Drag and Drop")) { + ImGui::BulletText("Drag/drop items from the left column."); + ImGui::BulletText("Drag/drop items between plots."); + ImGui::Indent(); + ImGui::BulletText("Plot 1 Targets: Plot, Y-Axes, Legend"); + ImGui::BulletText("Plot 1 Sources: Legend Items"); + ImGui::BulletText("Plot 2 Targets: Plot, X-Axis, Y-Axis"); + ImGui::BulletText("Plot 2 Sources: Plot, X-Axis, Y-Axis (hold Ctrl)"); + ImGui::Unindent(); + + // convenience struct to manage DND items; do this however you like + struct MyDndItem { + int Idx; + int Plt; + int Yax; + char Label[16]; + ImVector Data; + ImVec4 Color; + MyDndItem() { + static int i = 0; + Idx = i++; + Plt = 0; + Yax = ImPlotYAxis_1; + sprintf(Label, "%02d Hz", Idx+1); + Color = RandomColor(); + Data.reserve(1001); + for (int k = 0; k < 1001; ++k) { + float t = k * 1.0f / 999; + Data.push_back(ImVec2(t, 0.5f + 0.5f * sinf(2*3.14f*t*(Idx+1)))); + } + } + void Reset() { Plt = 0; Yax = ImPlotYAxis_1; } + }; + + const int k_dnd = 20; + static MyDndItem dnd[k_dnd]; + static MyDndItem* dndx = NULL; // for plot 2 + static MyDndItem* dndy = NULL; // for plot 2 + + // child window to serve as initial source for our DND items + ImGui::BeginChild("DND_LEFT",ImVec2(100,400)); + if (ImGui::Button("Reset Data", ImVec2(100, 0))) { + for (int k = 0; k < k_dnd; ++k) + dnd[k].Reset(); + dndx = dndy = NULL; + } + for (int k = 0; k < k_dnd; ++k) { + if (dnd[k].Plt > 0) + continue; + ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine(); + ImGui::Selectable(dnd[k].Label, false, 0, ImVec2(100, 0)); + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { + ImGui::SetDragDropPayload("MY_DND", &k, sizeof(int)); + ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine(); + ImGui::TextUnformatted(dnd[k].Label); + ImGui::EndDragDropSource(); + } + } + ImGui::EndChild(); + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dnd[i].Reset(); + } + ImGui::EndDragDropTarget(); + } + + ImGui::SameLine(); + ImGui::BeginChild("DND_RIGHT",ImVec2(-1,400)); + // plot 1 (time series) + ImPlotAxisFlags flags = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoGridLines; + if (ImPlot::BeginPlot("##DND1", NULL, "[drop here]", ImVec2(-1,195), ImPlotFlags_YAxis2 | ImPlotFlags_YAxis3, flags | ImPlotAxisFlags_Lock, flags, flags, flags, "[drop here]", "[drop here]")) { + for (int k = 0; k < k_dnd; ++k) { + if (dnd[k].Plt == 1 && dnd[k].Data.size() > 0) { + ImPlot::SetPlotYAxis(dnd[k].Yax); + ImPlot::SetNextLineStyle(dnd[k].Color); + static char label[32]; + sprintf(label,"%s (Y%d)", dnd[k].Label, dnd[k].Yax+1); + ImPlot::PlotLine(label, &dnd[k].Data[0].x, &dnd[k].Data[0].y, dnd[k].Data.size(), 0, 2 * sizeof(float)); + // allow legend item labels to be DND sources + if (ImPlot::BeginDragDropSourceItem(label)) { + ImGui::SetDragDropPayload("MY_DND", &k, sizeof(int)); + ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine(); + ImGui::TextUnformatted(dnd[k].Label); + ImPlot::EndDragDropSource(); + } + } + } + // allow the main plot area to be a DND target + if (ImPlot::BeginDragDropTarget()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = 0; + } + ImPlot::EndDragDropTarget(); + } + // allow each y-axis to be a DND target + for (int y = 0; y < 3; ++y) { + if (ImPlot::BeginDragDropTargetY(y)) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = y; + } + ImPlot::EndDragDropTarget(); + } + } + // allow the legend to be a DND target + if (ImPlot::BeginDragDropTargetLegend()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = 0; + } + ImPlot::EndDragDropTarget(); + } + ImPlot::EndPlot(); + } + // plot 2 (Lissajous) + ImPlot::PushStyleColor(ImPlotCol_XAxis, dndx == NULL ? ImPlot::GetStyle().Colors[ImPlotCol_XAxis] : dndx->Color); + ImPlot::PushStyleColor(ImPlotCol_YAxis, dndy == NULL ? ImPlot::GetStyle().Colors[ImPlotCol_YAxis] : dndy->Color); + if (ImPlot::BeginPlot("##DND2", dndx == NULL ? "[drop here]" : dndx->Label, dndy == NULL ? "[drop here]" : dndy->Label, ImVec2(-1,195), 0, flags, flags )) { + if (dndx != NULL && dndy != NULL) { + ImVec4 mixed((dndx->Color.x + dndy->Color.x)/2,(dndx->Color.y + dndy->Color.y)/2,(dndx->Color.z + dndy->Color.z)/2,(dndx->Color.w + dndy->Color.w)/2); + ImPlot::SetNextLineStyle(mixed); + ImPlot::PlotLine("##dndxy", &dndx->Data[0].y, &dndy->Data[0].y, dndx->Data.size(), 0, 2 * sizeof(float)); + } + // allow the x-axis to be a DND target + if (ImPlot::BeginDragDropTargetX()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dndx = &dnd[i]; + } + ImPlot::EndDragDropTarget(); + } + // allow the x-axis to be a DND source + if (dndx != NULL && ImPlot::BeginDragDropSourceX()) { + ImGui::SetDragDropPayload("MY_DND", &dndx->Idx, sizeof(int)); + ImPlot::ItemIcon(dndx->Color); ImGui::SameLine(); + ImGui::TextUnformatted(dndx->Label); + ImPlot::EndDragDropSource(); + } + // allow the y-axis to be a DND target + if (ImPlot::BeginDragDropTargetY()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dndy = &dnd[i]; + } + ImPlot::EndDragDropTarget(); + } + // allow the y-axis to be a DND source + if (dndy != NULL && ImPlot::BeginDragDropSourceY()) { + ImGui::SetDragDropPayload("MY_DND", &dndy->Idx, sizeof(int)); + ImPlot::ItemIcon(dndy->Color); ImGui::SameLine(); + ImGui::TextUnformatted(dndy->Label); + ImPlot::EndDragDropSource(); + } + // allow the plot area to be a DND target + if (ImPlot::BeginDragDropTarget()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("MY_DND")) { + int i = *(int*)payload->Data; dndx = dndy = &dnd[i]; + } + } + // allow the plot area to be a DND source + if (ImPlot::BeginDragDropSource()) { + ImGui::TextUnformatted("Yes, you can\ndrag this!"); + ImPlot::EndDragDropSource(); + } + ImPlot::EndPlot(); + } + ImPlot::PopStyleColor(2); + ImGui::EndChild(); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Tables")) { +#ifdef IMGUI_HAS_TABLE + static ImGuiTableFlags flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_RowBg; + static bool anim = true; + static int offset = 0; + ImGui::BulletText("Plots can be used inside of ImGui tables."); + ImGui::Checkbox("Animate",&anim); + if (anim) + offset = (offset + 1) % 100; + if (ImGui::BeginTable("##table", 3, flags, ImVec2(-1,0))) { + ImGui::TableSetupColumn("Electrode", ImGuiTableColumnFlags_WidthFixed, 75.0f); + ImGui::TableSetupColumn("Voltage", ImGuiTableColumnFlags_WidthFixed, 75.0f); + ImGui::TableSetupColumn("EMG Signal"); + ImGui::TableHeadersRow(); + ImPlot::PushColormap(ImPlotColormap_Cool); + for (int row = 0; row < 10; row++) { + ImGui::TableNextRow(); + static float data[100]; + srand(row); + for (int i = 0; i < 100; ++i) + data[i] = RandomRange(0.0f,10.0f); + ImGui::TableSetColumnIndex(0); + ImGui::Text("EMG %d", row); + ImGui::TableSetColumnIndex(1); + ImGui::Text("%.3f V", data[offset]); + ImGui::TableSetColumnIndex(2); + ImGui::PushID(row); + MyImPlot::Sparkline("##spark",data,100,0,11.0f,offset,ImPlot::GetColormapColor(row),ImVec2(-1, 35)); + ImGui::PopID(); + } + ImPlot::PopColormap(); + ImGui::EndTable(); + } +#else + ImGui::BulletText("You need to merge the ImGui 'tables' branch for this section."); +#endif + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Offset and Stride")) { + static const int k_circles = 11; + static const int k_points_per = 50; + static const int k_size = 2 * k_points_per * k_circles; + static double interleaved_data[k_size]; + for (int p = 0; p < k_points_per; ++p) { + for (int c = 0; c < k_circles; ++c) { + double r = (double)c / (k_circles - 1) * 0.2 + 0.2; + interleaved_data[p*2*k_circles + 2*c + 0] = 0.5 + r * cos((double)p/k_points_per * 6.28); + interleaved_data[p*2*k_circles + 2*c + 1] = 0.5 + r * sin((double)p/k_points_per * 6.28); + } + } + static int offset = 0; + ImGui::BulletText("Offsetting is useful for realtime plots (see above) and circular buffers."); + ImGui::BulletText("Striding is useful for interleaved data (e.g. audio) or plotting structs."); + ImGui::BulletText("Here, all circle data is stored in a single interleaved buffer:"); + ImGui::BulletText("[c0.x0 c0.y0 ... cn.x0 cn.y0 c0.x1 c0.y1 ... cn.x1 cn.y1 ... cn.xm cn.ym]"); + ImGui::BulletText("The offset value indicates which circle point index is considered the first."); + ImGui::BulletText("Offsets can be negative and/or larger than the actual data count."); + ImGui::SliderInt("Offset", &offset, -2*k_points_per, 2*k_points_per); + if (ImPlot::BeginPlot("##strideoffset",0,0,ImVec2(-1,0), ImPlotFlags_Equal)) { + ImPlot::PushColormap(ImPlotColormap_Jet); + char buff[16]; + for (int c = 0; c < k_circles; ++c) { + sprintf(buff, "Circle %d", c); + ImPlot::PlotLine(buff, &interleaved_data[c*2 + 0], &interleaved_data[c*2 + 1], k_points_per, offset, 2*k_circles*sizeof(double)); + } + ImPlot::EndPlot(); + ImPlot::PopColormap(); + } + // offset++; uncomment for animation! + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Data and Getters")) { + ImGui::BulletText("You can plot custom structs using the stride feature."); + ImGui::BulletText("Most plotters can also be passed a function pointer for getting data."); + ImGui::Indent(); + ImGui::BulletText("You can optionally pass user data to be given to your getter function."); + ImGui::BulletText("C++ lambdas can be passed as function pointers as well!"); + ImGui::Unindent(); + + MyImPlot::Vector2f vec2_data[2] = { MyImPlot::Vector2f(0,0), MyImPlot::Vector2f(1,1) }; + + if (ImPlot::BeginPlot("##Custom Data")) { + + // custom structs using stride example: + ImPlot::PlotLine("Vector2f", &vec2_data[0].x, &vec2_data[0].y, 2, 0, sizeof(MyImPlot::Vector2f) /* or sizeof(float) * 2 */); + + // custom getter example 1: + ImPlot::PlotLineG("Spiral", MyImPlot::Spiral, NULL, 1000); + + // custom getter example 2: + static MyImPlot::WaveData data1(0.001, 0.2, 2, 0.75); + static MyImPlot::WaveData data2(0.001, 0.2, 4, 0.25); + ImPlot::PlotLineG("Waves", MyImPlot::SineWave, &data1, 1000); + ImPlot::PlotLineG("Waves", MyImPlot::SawWave, &data2, 1000); + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); + ImPlot::PlotShadedG("Waves", MyImPlot::SineWave, &data1, MyImPlot::SawWave, &data2, 1000); + ImPlot::PopStyleVar(); + + // you can also pass C++ lambdas: + // auto lamda = [](void* data, int idx) { ... return ImPlotPoint(x,y); }; + // ImPlot::PlotLine("My Lambda", lambda, data, 1000); + + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Ticks##")) { + static bool custom_ticks = true; + static bool custom_labels = true; + ImGui::Checkbox("Show Custom Ticks", &custom_ticks); + if (custom_ticks) { + ImGui::SameLine(); + ImGui::Checkbox("Show Custom Labels", &custom_labels); + } + double pi = 3.14; + const char* pi_str[] = {"PI"}; + static double yticks[] = {1,3,7,9}; + static const char* ylabels[] = {"One","Three","Seven","Nine"}; + static double yticks_aux[] = {0.2,0.4,0.6}; + static const char* ylabels_aux[] = {"A","B","C","D","E","F"}; + if (custom_ticks) { + ImPlot::SetNextPlotTicksX(&pi,1,custom_labels ? pi_str : NULL, true); + ImPlot::SetNextPlotTicksY(yticks, 4, custom_labels ? ylabels : NULL); + ImPlot::SetNextPlotTicksY(yticks_aux, 3, custom_labels ? ylabels_aux : NULL, false, 1); + ImPlot::SetNextPlotTicksY(0, 1, 6, custom_labels ? ylabels_aux : NULL, false, 2); + } + ImPlot::SetNextPlotLimits(2.5,5,0,10); + if (ImPlot::BeginPlot("Custom Ticks", NULL, NULL, ImVec2(-1,0), ImPlotFlags_YAxis2 | ImPlotFlags_YAxis3)) { + // nothing to see here, just the ticks + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Styles")) { + ImPlot::PushColormap(ImPlotColormap_Deep); + // normally you wouldn't change the entire style each frame + ImPlotStyle backup = ImPlot::GetStyle(); + MyImPlot::StyleSeaborn(); + ImPlot::SetNextPlotLimits(-0.5f, 9.5f, 0, 10); + if (ImPlot::BeginPlot("seaborn style", "x-axis", "y-axis")) { + unsigned int lin[10] = {8,8,9,7,8,8,8,9,7,8}; + unsigned int bar[10] = {1,2,5,3,4,1,2,5,3,4}; + unsigned int dot[10] = {7,6,6,7,8,5,6,5,8,7}; + ImPlot::PlotBars("Bars", bar, 10, 0.5f); + ImPlot::PlotLine("Line", lin, 10); + ImPlot::NextColormapColor(); // skip green + ImPlot::PlotScatter("Scatter", dot, 10); + ImPlot::EndPlot(); + } + ImPlot::GetStyle() = backup; + ImPlot::PopColormap(); + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Rendering")) { + if (ImPlot::BeginPlot("##CustomRend")) { + ImVec2 cntr = ImPlot::PlotToPixels(ImPlotPoint(0.5f, 0.5f)); + ImVec2 rmin = ImPlot::PlotToPixels(ImPlotPoint(0.25f, 0.75f)); + ImVec2 rmax = ImPlot::PlotToPixels(ImPlotPoint(0.75f, 0.25f)); + ImPlot::PushPlotClipRect(); + ImPlot::GetPlotDrawList()->AddCircleFilled(cntr,20,IM_COL32(255,255,0,255),20); + ImPlot::GetPlotDrawList()->AddRect(rmin, rmax, IM_COL32(128,0,255,255)); + ImPlot::PopPlotClipRect(); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Context Menus")) { + ImGui::BulletText("You can implement legend context menus to inject per-item controls and widgets."); + ImGui::BulletText("Right click the legend label/icon to edit custom item attributes."); + + static float frequency = 0.1f; + static float amplitude = 0.5f; + static ImVec4 color = ImVec4(1,1,0,1); + static float alpha = 1.0f; + static bool line = false; + static float thickness = 1; + static bool markers = false; + static bool shaded = false; + + static float vals[101]; + for (int i = 0; i < 101; ++i) + vals[i] = amplitude * sinf(frequency * i); + + ImPlot::SetNextPlotLimits(0,100,-1,1); + if (ImPlot::BeginPlot("Right Click the Legend")) { + // rendering logic + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, alpha); + if (!line) { + ImPlot::SetNextFillStyle(color); + ImPlot::PlotBars("Right Click Me", vals, 101); + } + else { + if (markers) ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle); + ImPlot::SetNextLineStyle(color, thickness); + ImPlot::PlotLine("Right Click Me", vals, 101); + if (shaded) ImPlot::PlotShaded("Right Click Me",vals,101); + } + ImPlot::PopStyleVar(); + // custom legend context menu + if (ImPlot::BeginLegendPopup("Right Click Me")) { + ImGui::SliderFloat("Frequency",&frequency,0,1,"%0.2f"); + ImGui::SliderFloat("Amplitude",&litude,0,1,"%0.2f"); + ImGui::Separator(); + ImGui::ColorEdit3("Color",&color.x); + ImGui::SliderFloat("Transparency",&alpha,0,1,"%.2f"); + ImGui::Checkbox("Line Plot", &line); + if (line) { + ImGui::SliderFloat("Thickness", &thickness, 0, 5); + ImGui::Checkbox("Markers", &markers); + ImGui::Checkbox("Shaded",&shaded); + } + ImPlot::EndLegendPopup(); + } + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + if (ImGui::CollapsingHeader("Custom Plotters and Tooltips")) { + ImGui::BulletText("You can create custom plotters or extend ImPlot using implot_internal.h."); + double dates[] = {1546300800,1546387200,1546473600,1546560000,1546819200,1546905600,1546992000,1547078400,1547164800,1547424000,1547510400,1547596800,1547683200,1547769600,1547942400,1548028800,1548115200,1548201600,1548288000,1548374400,1548633600,1548720000,1548806400,1548892800,1548979200,1549238400,1549324800,1549411200,1549497600,1549584000,1549843200,1549929600,1550016000,1550102400,1550188800,1550361600,1550448000,1550534400,1550620800,1550707200,1550793600,1551052800,1551139200,1551225600,1551312000,1551398400,1551657600,1551744000,1551830400,1551916800,1552003200,1552262400,1552348800,1552435200,1552521600,1552608000,1552867200,1552953600,1553040000,1553126400,1553212800,1553472000,1553558400,1553644800,1553731200,1553817600,1554076800,1554163200,1554249600,1554336000,1554422400,1554681600,1554768000,1554854400,1554940800,1555027200,1555286400,1555372800,1555459200,1555545600,1555632000,1555891200,1555977600,1556064000,1556150400,1556236800,1556496000,1556582400,1556668800,1556755200,1556841600,1557100800,1557187200,1557273600,1557360000,1557446400,1557705600,1557792000,1557878400,1557964800,1558051200,1558310400,1558396800,1558483200,1558569600,1558656000,1558828800,1558915200,1559001600,1559088000,1559174400,1559260800,1559520000,1559606400,1559692800,1559779200,1559865600,1560124800,1560211200,1560297600,1560384000,1560470400,1560729600,1560816000,1560902400,1560988800,1561075200,1561334400,1561420800,1561507200,1561593600,1561680000,1561939200,1562025600,1562112000,1562198400,1562284800,1562544000,1562630400,1562716800,1562803200,1562889600,1563148800,1563235200,1563321600,1563408000,1563494400,1563753600,1563840000,1563926400,1564012800,1564099200,1564358400,1564444800,1564531200,1564617600,1564704000,1564963200,1565049600,1565136000,1565222400,1565308800,1565568000,1565654400,1565740800,1565827200,1565913600,1566172800,1566259200,1566345600,1566432000,1566518400,1566777600,1566864000,1566950400,1567036800,1567123200,1567296000,1567382400,1567468800,1567555200,1567641600,1567728000,1567987200,1568073600,1568160000,1568246400,1568332800,1568592000,1568678400,1568764800,1568851200,1568937600,1569196800,1569283200,1569369600,1569456000,1569542400,1569801600,1569888000,1569974400,1570060800,1570147200,1570406400,1570492800,1570579200,1570665600,1570752000,1571011200,1571097600,1571184000,1571270400,1571356800,1571616000,1571702400,1571788800,1571875200,1571961600}; + double opens[] = {1284.7,1319.9,1318.7,1328,1317.6,1321.6,1314.3,1325,1319.3,1323.1,1324.7,1321.3,1323.5,1322,1281.3,1281.95,1311.1,1315,1314,1313.1,1331.9,1334.2,1341.3,1350.6,1349.8,1346.4,1343.4,1344.9,1335.6,1337.9,1342.5,1337,1338.6,1337,1340.4,1324.65,1324.35,1349.5,1371.3,1367.9,1351.3,1357.8,1356.1,1356,1347.6,1339.1,1320.6,1311.8,1314,1312.4,1312.3,1323.5,1319.1,1327.2,1332.1,1320.3,1323.1,1328,1330.9,1338,1333,1335.3,1345.2,1341.1,1332.5,1314,1314.4,1310.7,1314,1313.1,1315,1313.7,1320,1326.5,1329.2,1314.2,1312.3,1309.5,1297.4,1293.7,1277.9,1295.8,1295.2,1290.3,1294.2,1298,1306.4,1299.8,1302.3,1297,1289.6,1302,1300.7,1303.5,1300.5,1303.2,1306,1318.7,1315,1314.5,1304.1,1294.7,1293.7,1291.2,1290.2,1300.4,1284.2,1284.25,1301.8,1295.9,1296.2,1304.4,1323.1,1340.9,1341,1348,1351.4,1351.4,1343.5,1342.3,1349,1357.6,1357.1,1354.7,1361.4,1375.2,1403.5,1414.7,1433.2,1438,1423.6,1424.4,1418,1399.5,1435.5,1421.25,1434.1,1412.4,1409.8,1412.2,1433.4,1418.4,1429,1428.8,1420.6,1441,1460.4,1441.7,1438.4,1431,1439.3,1427.4,1431.9,1439.5,1443.7,1425.6,1457.5,1451.2,1481.1,1486.7,1512.1,1515.9,1509.2,1522.3,1513,1526.6,1533.9,1523,1506.3,1518.4,1512.4,1508.8,1545.4,1537.3,1551.8,1549.4,1536.9,1535.25,1537.95,1535.2,1556,1561.4,1525.6,1516.4,1507,1493.9,1504.9,1506.5,1513.1,1506.5,1509.7,1502,1506.8,1521.5,1529.8,1539.8,1510.9,1511.8,1501.7,1478,1485.4,1505.6,1511.6,1518.6,1498.7,1510.9,1510.8,1498.3,1492,1497.7,1484.8,1494.2,1495.6,1495.6,1487.5,1491.1,1495.1,1506.4}; + double highs[] = {1284.75,1320.6,1327,1330.8,1326.8,1321.6,1326,1328,1325.8,1327.1,1326,1326,1323.5,1322.1,1282.7,1282.95,1315.8,1316.3,1314,1333.2,1334.7,1341.7,1353.2,1354.6,1352.2,1346.4,1345.7,1344.9,1340.7,1344.2,1342.7,1342.1,1345.2,1342,1350,1324.95,1330.75,1369.6,1374.3,1368.4,1359.8,1359,1357,1356,1353.4,1340.6,1322.3,1314.1,1316.1,1312.9,1325.7,1323.5,1326.3,1336,1332.1,1330.1,1330.4,1334.7,1341.1,1344.2,1338.8,1348.4,1345.6,1342.8,1334.7,1322.3,1319.3,1314.7,1316.6,1316.4,1315,1325.4,1328.3,1332.2,1329.2,1316.9,1312.3,1309.5,1299.6,1296.9,1277.9,1299.5,1296.2,1298.4,1302.5,1308.7,1306.4,1305.9,1307,1297.2,1301.7,1305,1305.3,1310.2,1307,1308,1319.8,1321.7,1318.7,1316.2,1305.9,1295.8,1293.8,1293.7,1304.2,1302,1285.15,1286.85,1304,1302,1305.2,1323,1344.1,1345.2,1360.1,1355.3,1363.8,1353,1344.7,1353.6,1358,1373.6,1358.2,1369.6,1377.6,1408.9,1425.5,1435.9,1453.7,1438,1426,1439.1,1418,1435,1452.6,1426.65,1437.5,1421.5,1414.1,1433.3,1441.3,1431.4,1433.9,1432.4,1440.8,1462.3,1467,1443.5,1444,1442.9,1447,1437.6,1440.8,1445.7,1447.8,1458.2,1461.9,1481.8,1486.8,1522.7,1521.3,1521.1,1531.5,1546.1,1534.9,1537.7,1538.6,1523.6,1518.8,1518.4,1514.6,1540.3,1565,1554.5,1556.6,1559.8,1541.9,1542.9,1540.05,1558.9,1566.2,1561.9,1536.2,1523.8,1509.1,1506.2,1532.2,1516.6,1519.7,1515,1519.5,1512.1,1524.5,1534.4,1543.3,1543.3,1542.8,1519.5,1507.2,1493.5,1511.4,1525.8,1522.2,1518.8,1515.3,1518,1522.3,1508,1501.5,1503,1495.5,1501.1,1497.9,1498.7,1492.1,1499.4,1506.9,1520.9}; + double lows[] = {1282.85,1315,1318.7,1309.6,1317.6,1312.9,1312.4,1319.1,1319,1321,1318.1,1321.3,1319.9,1312,1280.5,1276.15,1308,1309.9,1308.5,1312.3,1329.3,1333.1,1340.2,1347,1345.9,1338,1340.8,1335,1332,1337.9,1333,1336.8,1333.2,1329.9,1340.4,1323.85,1324.05,1349,1366.3,1351.2,1349.1,1352.4,1350.7,1344.3,1338.9,1316.3,1308.4,1306.9,1309.6,1306.7,1312.3,1315.4,1319,1327.2,1317.2,1320,1323,1328,1323,1327.8,1331.7,1335.3,1336.6,1331.8,1311.4,1310,1309.5,1308,1310.6,1302.8,1306.6,1313.7,1320,1322.8,1311,1312.1,1303.6,1293.9,1293.5,1291,1277.9,1294.1,1286,1289.1,1293.5,1296.9,1298,1299.6,1292.9,1285.1,1288.5,1296.3,1297.2,1298.4,1298.6,1302,1300.3,1312,1310.8,1301.9,1292,1291.1,1286.3,1289.2,1289.9,1297.4,1283.65,1283.25,1292.9,1295.9,1290.8,1304.2,1322.7,1336.1,1341,1343.5,1345.8,1340.3,1335.1,1341.5,1347.6,1352.8,1348.2,1353.7,1356.5,1373.3,1398,1414.7,1427,1416.4,1412.7,1420.1,1396.4,1398.8,1426.6,1412.85,1400.7,1406,1399.8,1404.4,1415.5,1417.2,1421.9,1415,1413.7,1428.1,1434,1435.7,1427.5,1429.4,1423.9,1425.6,1427.5,1434.8,1422.3,1412.1,1442.5,1448.8,1468.2,1484.3,1501.6,1506.2,1498.6,1488.9,1504.5,1518.3,1513.9,1503.3,1503,1506.5,1502.1,1503,1534.8,1535.3,1541.4,1528.6,1525.6,1535.25,1528.15,1528,1542.6,1514.3,1510.7,1505.5,1492.1,1492.9,1496.8,1493.1,1503.4,1500.9,1490.7,1496.3,1505.3,1505.3,1517.9,1507.4,1507.1,1493.3,1470.5,1465,1480.5,1501.7,1501.4,1493.3,1492.1,1505.1,1495.7,1478,1487.1,1480.8,1480.6,1487,1488.3,1484.8,1484,1490.7,1490.4,1503.1}; + double closes[] = {1283.35,1315.3,1326.1,1317.4,1321.5,1317.4,1323.5,1319.2,1321.3,1323.3,1319.7,1325.1,1323.6,1313.8,1282.05,1279.05,1314.2,1315.2,1310.8,1329.1,1334.5,1340.2,1340.5,1350,1347.1,1344.3,1344.6,1339.7,1339.4,1343.7,1337,1338.9,1340.1,1338.7,1346.8,1324.25,1329.55,1369.6,1372.5,1352.4,1357.6,1354.2,1353.4,1346,1341,1323.8,1311.9,1309.1,1312.2,1310.7,1324.3,1315.7,1322.4,1333.8,1319.4,1327.1,1325.8,1330.9,1325.8,1331.6,1336.5,1346.7,1339.2,1334.7,1313.3,1316.5,1312.4,1313.4,1313.3,1312.2,1313.7,1319.9,1326.3,1331.9,1311.3,1313.4,1309.4,1295.2,1294.7,1294.1,1277.9,1295.8,1291.2,1297.4,1297.7,1306.8,1299.4,1303.6,1302.2,1289.9,1299.2,1301.8,1303.6,1299.5,1303.2,1305.3,1319.5,1313.6,1315.1,1303.5,1293,1294.6,1290.4,1291.4,1302.7,1301,1284.15,1284.95,1294.3,1297.9,1304.1,1322.6,1339.3,1340.1,1344.9,1354,1357.4,1340.7,1342.7,1348.2,1355.1,1355.9,1354.2,1362.1,1360.1,1408.3,1411.2,1429.5,1430.1,1426.8,1423.4,1425.1,1400.8,1419.8,1432.9,1423.55,1412.1,1412.2,1412.8,1424.9,1419.3,1424.8,1426.1,1423.6,1435.9,1440.8,1439.4,1439.7,1434.5,1436.5,1427.5,1432.2,1433.3,1441.8,1437.8,1432.4,1457.5,1476.5,1484.2,1519.6,1509.5,1508.5,1517.2,1514.1,1527.8,1531.2,1523.6,1511.6,1515.7,1515.7,1508.5,1537.6,1537.2,1551.8,1549.1,1536.9,1529.4,1538.05,1535.15,1555.9,1560.4,1525.5,1515.5,1511.1,1499.2,1503.2,1507.4,1499.5,1511.5,1513.4,1515.8,1506.2,1515.1,1531.5,1540.2,1512.3,1515.2,1506.4,1472.9,1489,1507.9,1513.8,1512.9,1504.4,1503.9,1512.8,1500.9,1488.7,1497.6,1483.5,1494,1498.3,1494.1,1488.1,1487.5,1495.7,1504.7,1505.3}; + static bool tooltip = true; + ImGui::Checkbox("Show Tooltip", &tooltip); + ImGui::SameLine(); + static ImVec4 bullCol = ImVec4(0.000f, 1.000f, 0.441f, 1.000f); + static ImVec4 bearCol = ImVec4(0.853f, 0.050f, 0.310f, 1.000f); + ImGui::SameLine(); ImGui::ColorEdit4("##Bull", &bullCol.x, ImGuiColorEditFlags_NoInputs); + ImGui::SameLine(); ImGui::ColorEdit4("##Bear", &bearCol.x, ImGuiColorEditFlags_NoInputs); + ImPlot::GetStyle().UseLocalTime = false; + ImPlot::SetNextPlotLimits(1546300800, 1571961600, 1250, 1600); + if (ImPlot::BeginPlot("Candlestick Chart","Day","USD",ImVec2(-1,0),0,ImPlotAxisFlags_Time)) { + MyImPlot::PlotCandlestick("GOOGL",dates, opens, closes, lows, highs, 218, tooltip, 0.25f, bullCol, bearCol); + ImPlot::EndPlot(); + } + } + //------------------------------------------------------------------------- + ImGui::End(); +} + +} // namespace ImPlot + +namespace MyImPlot { + +ImPlotPoint SineWave(void* data , int idx) { + WaveData* wd = (WaveData*)data; + double x = idx * wd->X; + return ImPlotPoint(x, wd->Offset + wd->Amp * sin(2 * 3.14 * wd->Freq * x)); +} + +ImPlotPoint SawWave(void* data, int idx) { + WaveData* wd = (WaveData*)data; + double x = idx * wd->X; + return ImPlotPoint(x, wd->Offset + wd->Amp * (-2 / 3.14 * atan(cos(3.14 * wd->Freq * x) / sin(3.14 * wd->Freq * x)))); +} + +ImPlotPoint Spiral(void*, int idx) { + float r = 0.9f; // outer radius + float a = 0; // inner radius + float b = 0.05f; // increment per rev + float n = (r - a) / b; // number of revolutions + double th = 2 * n * 3.14; // angle + float Th = float(th * idx / (1000 - 1)); + return ImPlotPoint(0.5f+(a + b*Th / (2.0f * (float) 3.14))*cos(Th), + 0.5f + (a + b*Th / (2.0f * (float)3.14))*sin(Th)); +} + +// Example for Tables section. Generates a quick and simple shaded line plot. See implementation at bottom. +void Sparkline(const char* id, const float* values, int count, float min_v, float max_v, int offset, const ImVec4& col, const ImVec2& size) { + ImPlot::PushStyleVar(ImPlotStyleVar_PlotPadding, ImVec2(0,0)); + ImPlot::SetNextPlotLimits(0, count - 1, min_v, max_v, ImGuiCond_Always); + if (ImPlot::BeginPlot(id,0,0,size,ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations)) { + ImPlot::PushStyleColor(ImPlotCol_Line, col); + ImPlot::PlotLine(id, values, count, 1, 0, offset); + ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); + ImPlot::PlotShaded(id, values, count, 0, 1, 0, offset); + ImPlot::PopStyleVar(); + ImPlot::PopStyleColor(); + ImPlot::EndPlot(); + } + ImPlot::PopStyleVar(); +} + +void StyleSeaborn() { + + ImPlotStyle& style = ImPlot::GetStyle(); + + ImVec4* colors = style.Colors; + colors[ImPlotCol_Line] = IMPLOT_AUTO_COL; + colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL; + colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL; + colors[ImPlotCol_ErrorBar] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_PlotBg] = ImVec4(0.92f, 0.92f, 0.95f, 1.00f); + colors[ImPlotCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImPlotCol_LegendBg] = ImVec4(0.92f, 0.92f, 0.95f, 1.00f); + colors[ImPlotCol_LegendBorder] = ImVec4(0.80f, 0.81f, 0.85f, 1.00f); + colors[ImPlotCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_XAxis] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_XAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxis] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxis2] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid2] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_YAxis3] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlotCol_YAxisGrid3] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlotCol_Selection] = ImVec4(1.00f, 0.65f, 0.00f, 1.00f); + colors[ImPlotCol_Query] = ImVec4(0.23f, 0.10f, 0.64f, 1.00f); + colors[ImPlotCol_Crosshairs] = ImVec4(0.23f, 0.10f, 0.64f, 0.50f); + + style.LineWeight = 1.5; + style.Marker = ImPlotMarker_None; + style.MarkerSize = 4; + style.MarkerWeight = 1; + style.FillAlpha = 1.0f; + style.ErrorBarSize = 5; + style.ErrorBarWeight = 1.5f; + style.DigitalBitHeight = 8; + style.DigitalBitGap = 4; + style.PlotBorderSize = 0; + style.MinorAlpha = 1.0f; + style.MajorTickLen = ImVec2(0,0); + style.MinorTickLen = ImVec2(0,0); + style.MajorTickSize = ImVec2(0,0); + style.MinorTickSize = ImVec2(0,0); + style.MajorGridSize = ImVec2(1.2f,1.2f); + style.MinorGridSize = ImVec2(1.2f,1.2f); + style.PlotPadding = ImVec2(12,12); + style.LabelPadding = ImVec2(5,5); + style.LegendPadding = ImVec2(5,5); + style.MousePosPadding = ImVec2(5,5); + style.PlotMinSize = ImVec2(300,225); +} + +} // namespaece MyImPlot + +// WARNING: +// +// You can use "implot_internal.h" to build custom plotting fuctions or extend ImPlot. +// However, note that forward compatibility of this file is not guaranteed and the +// internal API is subject to change. At some point we hope to bring more of this +// into the public API and expose the necessary building blocks to fully support +// custom plotters. For now, proceed at your own risk! + +#include "implot_internal.h" + +namespace MyImPlot { + +template +int BinarySearch(const T* arr, int l, int r, T x) { + if (r >= l) { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return BinarySearch(arr, l, mid - 1, x); + return BinarySearch(arr, mid + 1, r, x); + } + return -1; +} + +void PlotCandlestick(const char* label_id, const double* xs, const double* opens, const double* closes, const double* lows, const double* highs, int count, bool tooltip, float width_percent, ImVec4 bullCol, ImVec4 bearCol) { + + // get ImGui window DrawList + ImDrawList* draw_list = ImPlot::GetPlotDrawList(); + // calc real value width + double half_width = count > 1 ? (xs[1] - xs[0]) * width_percent : width_percent; + + // custom tool + if (ImPlot::IsPlotHovered() && tooltip) { + ImPlotPoint mouse = ImPlot::GetPlotMousePos(); + mouse.x = ImPlot::RoundTime(ImPlotTime::FromDouble(mouse.x), ImPlotTimeUnit_Day).ToDouble(); + float tool_l = ImPlot::PlotToPixels(mouse.x - half_width * 1.5, mouse.y).x; + float tool_r = ImPlot::PlotToPixels(mouse.x + half_width * 1.5, mouse.y).x; + float tool_t = ImPlot::GetPlotPos().y; + float tool_b = tool_t + ImPlot::GetPlotSize().y; + ImPlot::PushPlotClipRect(); + draw_list->AddRectFilled(ImVec2(tool_l, tool_t), ImVec2(tool_r, tool_b), IM_COL32(128,128,128,64)); + ImPlot::PopPlotClipRect(); + // find mouse location index + int idx = BinarySearch(xs, 0, count - 1, mouse.x); + // render tool tip (won't be affected by plot clip rect) + if (idx != -1) { + ImGui::BeginTooltip(); + char buff[32]; + ImPlot::FormatDate(ImPlotTime::FromDouble(xs[idx]),buff,32,ImPlotDateFmt_DayMoYr,ImPlot::GetStyle().UseISO8601); + ImGui::Text("Day: %s", buff); + ImGui::Text("Open: $%.2f", opens[idx]); + ImGui::Text("Close: $%.2f", closes[idx]); + ImGui::Text("Low: $%.2f", lows[idx]); + ImGui::Text("High: $%.2f", highs[idx]); + ImGui::EndTooltip(); + } + } + + // begin plot item + if (ImPlot::BeginItem(label_id)) { + // override legend icon color + ImPlot::GetCurrentItem()->Color = IM_COL32(64,64,64,255); + // fit data if requested + if (ImPlot::FitThisFrame()) { + for (int i = 0; i < count; ++i) { + ImPlot::FitPoint(ImPlotPoint(xs[i], lows[i])); + ImPlot::FitPoint(ImPlotPoint(xs[i], highs[i])); + } + } + // render data + for (int i = 0; i < count; ++i) { + ImVec2 open_pos = ImPlot::PlotToPixels(xs[i] - half_width, opens[i]); + ImVec2 close_pos = ImPlot::PlotToPixels(xs[i] + half_width, closes[i]); + ImVec2 low_pos = ImPlot::PlotToPixels(xs[i], lows[i]); + ImVec2 high_pos = ImPlot::PlotToPixels(xs[i], highs[i]); + ImU32 color = ImGui::GetColorU32(opens[i] > closes[i] ? bearCol : bullCol); + draw_list->AddLine(low_pos, high_pos, color); + draw_list->AddRectFilled(open_pos, close_pos, color); + } + + // end plot item + ImPlot::EndItem(); + } +} + +} // namespace MyImplot + +namespace ImPlot { + +//----------------------------------------------------------------------------- +// BENCHMARK +//----------------------------------------------------------------------------- + +struct BenchData { + BenchData() { + float y = RandomRange(0.0f,1.0f); + Data = new float[1000]; + for (int i = 0; i < 1000; ++i) { + Data[i] = y + RandomRange(-0.01f,0.01f); + } + Col = ImVec4(RandomRange(0.0f,1.0f),RandomRange(0.0f,1.0f),RandomRange(0.0f,1.0f),0.5f); + } + ~BenchData() { delete[] Data; } + float* Data; + ImVec4 Col; +}; + +enum BenchMode { + Line = 0, + Shaded = 1, + Scatter = 2, + Bars = 3 +}; + +struct BenchRecord { + int Mode; + bool AA; + ImVector Data; +}; + +void ShowBenchmarkTool() { + static const int max_items = 500; + static BenchData items[max_items]; + static bool running = false; + static int frames = 60; + static int L = 0; + static int F = 0; + static double t1, t2; + static int mode = BenchMode::Line; + const char* names[] = {"Line","Shaded","Scatter","Bars"}; + + static ImVector records; + + if (running) { + F++; + if (F == frames) { + t2 = ImGui::GetTime(); + records.back().Data.push_back(ImPlotPoint(L, frames / (t2 - t1))); + L += 5; + F = 0; + t1 = ImGui::GetTime(); + } + if (L > max_items) { + running = false; + L = max_items; + } + } + + ImGui::Text("ImDrawIdx: %d-bit", (int)(sizeof(ImDrawIdx) * 8)); + ImGui::Text("ImGuiBackendFlags_RendererHasVtxOffset: %s", (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ? "True" : "False"); + ImGui::Text("%.2f FPS", ImGui::GetIO().Framerate); + + ImGui::Separator(); + + bool was_running = running; + if (was_running) { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.25f); + } + if (ImGui::Button("Benchmark")) { + running = true; + L = F = 0; + records.push_back(BenchRecord()); + records.back().Data.reserve(max_items+1); + records.back().Mode = mode; + records.back().AA = ImPlot::GetStyle().AntiAliasedLines; + t1 = ImGui::GetTime(); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(200); + ImGui::Combo("##Mode",&mode,names,4); + ImGui::SameLine(); + + ImGui::Checkbox("Anti-Aliased Lines", &ImPlot::GetStyle().AntiAliasedLines); + if (was_running) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } + + ImGui::ProgressBar((float)L / (float)(max_items - 1)); + + ImPlot::SetNextPlotLimits(0,1000,0,1,ImGuiCond_Always); + if (ImPlot::BeginPlot("##Bench",NULL,NULL,ImVec2(-1,0),ImPlotFlags_NoChild | ImPlotFlags_CanvasOnly,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations)) { + if (running) { + if (mode == BenchMode::Line) { + for (int i = 0; i < L; ++i) { + ImGui::PushID(i); + ImPlot::SetNextLineStyle(items[i].Col); + ImPlot::PlotLine("##item", items[i].Data, 1000); + ImGui::PopID(); + } + } + else if (mode == BenchMode::Shaded) { + for (int i = 0; i < L; ++i) { + ImGui::PushID(i); + ImPlot::SetNextFillStyle(items[i].Col,0.5f); + ImPlot::PlotShaded("##item", items[i].Data, 1000); + ImGui::PopID(); + } + } + else if (mode == BenchMode::Scatter) { + for (int i = 0; i < L; ++i) { + ImGui::PushID(i); + ImPlot::SetNextLineStyle(items[i].Col); + ImPlot::PlotScatter("##item", items[i].Data, 1000); + ImGui::PopID(); + } + } + else if (mode == BenchMode::Bars) { + for (int i = 0; i < L; ++i) { + ImGui::PushID(i); + ImPlot::SetNextFillStyle(items[i].Col,0.5f); + ImPlot::PlotBars("##item", items[i].Data, 1000); + ImGui::PopID(); + } + } + } + ImPlot::EndPlot(); + } + ImPlot::SetNextPlotLimits(0,500,0,500,ImGuiCond_Always); + static char buffer[64]; + if (ImPlot::BeginPlot("##Stats", "Items (1,000 pts each)", "Framerate (Hz)", ImVec2(-1,0), ImPlotFlags_NoChild)) { + for (int run = 0; run < records.size(); ++run) { + if (records[run].Data.Size > 1) { + sprintf(buffer, "B%d-%s%s", run + 1, names[records[run].Mode], records[run].AA ? "-AA" : ""); + ImVector& d = records[run].Data; + ImPlot::PlotLine(buffer, &d[0].x, &d[0].y, d.Size, 0, 2*sizeof(double)); + } + } + ImPlot::EndPlot(); + } +} + +} diff --git a/DearPyGui/vendor/implot/implot_internal.h b/DearPyGui/vendor/implot/implot_internal.h new file mode 100644 index 000000000..78d0a21f8 --- /dev/null +++ b/DearPyGui/vendor/implot/implot_internal.h @@ -0,0 +1,1184 @@ +// MIT License + +// Copyright (c) 2021 Evan Pezent + +// 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. + +// ImPlot v0.9 WIP + +// You may use this file to debug, understand or extend ImPlot features but we +// don't provide any guarantee of forward compatibility! + +//----------------------------------------------------------------------------- +// [SECTION] Header Mess +//----------------------------------------------------------------------------- + +#pragma once + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include +#include "imgui_internal.h" + +#ifndef IMPLOT_VERSION +#error Must include implot.h before implot_internal.h +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Constants +//----------------------------------------------------------------------------- + +// Constants can be changed unless stated otherwise. We may move some of these +// to ImPlotStyleVar_ over time. + +// The maximum number of supported y-axes (DO NOT CHANGE THIS) +#define IMPLOT_Y_AXES 3 +// The number of times to subdivided grid divisions (best if a multiple of 1, 2, and 5) +#define IMPLOT_SUB_DIV 10 +// Zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click) +#define IMPLOT_ZOOM_RATE 0.1f +// Mimimum allowable timestamp value 01/01/1970 @ 12:00am (UTC) (DO NOT DECREASE THIS) +#define IMPLOT_MIN_TIME 0 +// Maximum allowable timestamp value 01/01/3000 @ 12:00am (UTC) (DO NOT INCREASE THIS) +#define IMPLOT_MAX_TIME 32503680000 + +//----------------------------------------------------------------------------- +// [SECTION] Macros +//----------------------------------------------------------------------------- + +// Split ImU32 color into RGB components [0 255] +#define IM_COL32_SPLIT_RGB(col,r,g,b) \ + ImU32 r = ((col >> IM_COL32_R_SHIFT) & 0xFF); \ + ImU32 g = ((col >> IM_COL32_G_SHIFT) & 0xFF); \ + ImU32 b = ((col >> IM_COL32_B_SHIFT) & 0xFF); + +//----------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//----------------------------------------------------------------------------- + +struct ImPlotTick; +struct ImPlotAxis; +struct ImPlotAxisColor; +struct ImPlotItem; +struct ImPlotLegendData; +struct ImPlotPlot; +struct ImPlotNextPlotData; + +//----------------------------------------------------------------------------- +// [SECTION] Context Pointer +//----------------------------------------------------------------------------- + +extern IMPLOT_API ImPlotContext* GImPlot; // Current implicit context pointer + +//----------------------------------------------------------------------------- +// [SECTION] Generic Helpers +//----------------------------------------------------------------------------- + +// Computes the common (base-10) logarithm +static inline float ImLog10(float x) { return log10f(x); } +static inline double ImLog10(double x) { return log10(x); } +// Returns true if a flag is set +template +inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; } +// Flips a flag in a flagset +template +inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; } +// Linearly remaps x from [x0 x1] to [y0 y1]. +template +inline T ImRemap(T x, T x0, T x1, T y0, T y1) { return y0 + (x - x0) * (y1 - y0) / (x1 - x0); } +// Linear rempas x from [x0 x1] to [0 1] +template +inline T ImRemap01(T x, T x0, T x1) { return (x - x0) / (x1 - x0); } +// Returns always positive modulo (assumes r != 0) +inline int ImPosMod(int l, int r) { return (l % r + r) % r; } +// Returns true if val is NAN or INFINITY +inline bool ImNanOrInf(double val) { return val == HUGE_VAL || val == -HUGE_VAL || isnan(val); } +// Turns NANs to 0s +inline double ImConstrainNan(double val) { return isnan(val) ? 0 : val; } +// Turns infinity to floating point maximums +inline double ImConstrainInf(double val) { return val == HUGE_VAL ? DBL_MAX : val == -HUGE_VAL ? - DBL_MAX : val; } +// Turns numbers less than or equal to 0 to 0.001 (sort of arbitrary, is there a better way?) +inline double ImConstrainLog(double val) { return val <= 0 ? 0.001f : val; } +// Turns numbers less than 0 to zero +inline double ImConstrainTime(double val) { return val < IMPLOT_MIN_TIME ? IMPLOT_MIN_TIME : (val > IMPLOT_MAX_TIME ? IMPLOT_MAX_TIME : val); } +// True if two numbers are approximately equal using units in the last place. +inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { return ImAbs(v1-v2) < DBL_EPSILON * ImAbs(v1+v2) * ulp || ImAbs(v1-v2) < DBL_MIN; } +// Finds min value in an unsorted array +template +inline T ImMinArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] < m) { m = values[i]; } } return m; } +// Finds the max value in an unsorted array +template +inline T ImMaxArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] > m) { m = values[i]; } } return m; } +// Finds the min and max value in an unsorted array +template +inline void ImMinMaxArray(const T* values, int count, T* min_out, T* max_out) { + T Min = values[0]; T Max = values[0]; + for (int i = 1; i < count; ++i) { + if (values[i] < Min) { Min = values[i]; } + if (values[i] > Max) { Max = values[i]; } + } + *min_out = Min; *max_out = Max; +} +// Finds the mean of an array +template +inline double ImMean(const T* values, int count) { + double den = 1.0 / count; + double mu = 0; + for (int i = 0; i < count; ++i) + mu += values[i] * den; + return mu; +} +// Finds the sample standard deviation of an array +template +inline double ImStdDev(const T* values, int count) { + double den = 1.0 / (count - 1.0); + double mu = ImMean(values, count); + double x = 0; + for (int i = 0; i < count; ++i) + x += (values[i] - mu) * (values[i] - mu) * den; + return sqrt(x); +} +// Mix color a and b by factor s in [0 256] +inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) { +#ifdef IMPLOT_MIX64 + const ImU32 af = 256-s; + const ImU32 bf = s; + const ImU64 al = (a & 0x00ff00ff) | (((ImU64)(a & 0xff00ff00)) << 24); + const ImU64 bl = (b & 0x00ff00ff) | (((ImU64)(b & 0xff00ff00)) << 24); + const ImU64 mix = (al * af + bl * bf); + return ((mix >> 32) & 0xff00ff00) | ((mix & 0xff00ff00) >> 8); +#else + const ImU32 af = 256-s; + const ImU32 bf = s; + const ImU32 al = (a & 0x00ff00ff); + const ImU32 ah = (a & 0xff00ff00) >> 8; + const ImU32 bl = (b & 0x00ff00ff); + const ImU32 bh = (b & 0xff00ff00) >> 8; + const ImU32 ml = (al * af + bl * bf); + const ImU32 mh = (ah * af + bh * bf); + return (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8); +#endif +} + +// Lerp across an array of 32-bit collors given t in [0.0 1.0] +inline ImU32 ImLerpU32(const ImU32* colors, int size, float t) { + int i1 = (int)((size - 1 ) * t); + int i2 = i1 + 1; + if (i2 == size || size == 1) + return colors[i1]; + float den = 1.0f / (size - 1); + float t1 = i1 * den; + float t2 = i2 * den; + float tr = ImRemap01(t, t1, t2); + return ImMixU32(colors[i1], colors[i2], (ImU32)(tr*256)); +} + +// Set alpha channel of 32-bit color from float in range [0.0 1.0] +inline ImU32 ImAlphaU32(ImU32 col, float alpha) { + return col & ~((ImU32)((1.0f-alpha)*255)< 0) + Pos += ImMin(written, Size-Pos-1); + } +}; + +// Fixed size point array +template +struct ImPlotPointArray { + inline ImPlotPoint& operator[](int i) { return Data[i]; } + inline const ImPlotPoint& operator[](int i) const { return Data[i]; } + inline int Size() { return N; } + ImPlotPoint Data[N]; +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot Enums +//----------------------------------------------------------------------------- + +typedef int ImPlotScale; // -> enum ImPlotScale_ +typedef int ImPlotTimeUnit; // -> enum ImPlotTimeUnit_ +typedef int ImPlotDateFmt; // -> enum ImPlotDateFmt_ +typedef int ImPlotTimeFmt; // -> enum ImPlotTimeFmt_ + +// XY axes scaling combinations +enum ImPlotScale_ { + ImPlotScale_LinLin, // linear x, linear y + ImPlotScale_LogLin, // log x, linear y + ImPlotScale_LinLog, // linear x, log y + ImPlotScale_LogLog // log x, log y +}; + +enum ImPlotTimeUnit_ { + ImPlotTimeUnit_Us, // microsecond + ImPlotTimeUnit_Ms, // millisecond + ImPlotTimeUnit_S, // second + ImPlotTimeUnit_Min, // minute + ImPlotTimeUnit_Hr, // hour + ImPlotTimeUnit_Day, // day + ImPlotTimeUnit_Mo, // month + ImPlotTimeUnit_Yr, // year + ImPlotTimeUnit_COUNT +}; + +enum ImPlotDateFmt_ { // default [ ISO 8601 ] + ImPlotDateFmt_None = 0, + ImPlotDateFmt_DayMo, // 10/3 [ --10-03 ] + ImPlotDateFmt_DayMoYr, // 10/3/91 [ 1991-10-03 ] + ImPlotDateFmt_MoYr, // Oct 1991 [ 1991-10 ] + ImPlotDateFmt_Mo, // Oct [ --10 ] + ImPlotDateFmt_Yr // 1991 [ 1991 ] +}; + +enum ImPlotTimeFmt_ { // default [ 24 Hour Clock ] + ImPlotTimeFmt_None = 0, + ImPlotTimeFmt_Us, // .428 552 [ .428 552 ] + ImPlotTimeFmt_SUs, // :29.428 552 [ :29.428 552 ] + ImPlotTimeFmt_SMs, // :29.428 [ :29.428 ] + ImPlotTimeFmt_S, // :29 [ :29 ] + ImPlotTimeFmt_HrMinSMs, // 7:21:29.428pm [ 19:21:29.428 ] + ImPlotTimeFmt_HrMinS, // 7:21:29pm [ 19:21:29 ] + ImPlotTimeFmt_HrMin, // 7:21pm [ 19:21 ] + ImPlotTimeFmt_Hr // 7pm [ 19:00 ] +}; + +// Input mapping structure, default values listed in the comments. +struct ImPlotInputMap { + ImGuiMouseButton PanButton; // LMB enables panning when held + ImGuiKeyModFlags PanMod; // none optional modifier that must be held for panning + ImGuiMouseButton FitButton; // LMB fits visible data when double clicked + ImGuiMouseButton ContextMenuButton; // RMB opens plot context menu (if enabled) when clicked + ImGuiMouseButton BoxSelectButton; // RMB begins box selection when pressed and confirms selection when released + ImGuiKeyModFlags BoxSelectMod; // none optional modifier that must be held for box selection + ImGuiMouseButton BoxSelectCancelButton; // LMB cancels active box selection when pressed + ImGuiMouseButton QueryButton; // MMB begins query selection when pressed and end query selection when released + ImGuiKeyModFlags QueryMod; // none optional modifier that must be held for query selection + ImGuiKeyModFlags QueryToggleMod; // Ctrl when held, active box selections turn into queries + ImGuiKeyModFlags HorizontalMod; // Alt expands active box selection/query horizontally to plot edge when held + ImGuiKeyModFlags VerticalMod; // Shift expands active box selection/query vertically to plot edge when held + IMPLOT_API ImPlotInputMap(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot Structs +//----------------------------------------------------------------------------- + +// Combined date/time format spec +struct ImPlotDateTimeFmt { + ImPlotDateTimeFmt(ImPlotDateFmt date_fmt, ImPlotTimeFmt time_fmt, bool use_24_hr_clk = false, bool use_iso_8601 = false) { + Date = date_fmt; + Time = time_fmt; + UseISO8601 = use_iso_8601; + Use24HourClock = use_24_hr_clk; + } + ImPlotDateFmt Date; + ImPlotTimeFmt Time; + bool UseISO8601; + bool Use24HourClock; +}; + +// Two part timestamp struct. +struct ImPlotTime { + time_t S; // second part + int Us; // microsecond part + ImPlotTime() { S = 0; Us = 0; } + ImPlotTime(time_t s, int us = 0) { S = s + us / 1000000; Us = us % 1000000; } + void RollOver() { S = S + Us / 1000000; Us = Us % 1000000; } + double ToDouble() const { return (double)S + (double)Us / 1000000.0; } + static ImPlotTime FromDouble(double t) { return ImPlotTime((time_t)t, (int)(t * 1000000 - floor(t) * 1000000)); } +}; + +static inline ImPlotTime operator+(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return ImPlotTime(lhs.S + rhs.S, lhs.Us + rhs.Us); } +static inline ImPlotTime operator-(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return ImPlotTime(lhs.S - rhs.S, lhs.Us - rhs.Us); } +static inline bool operator==(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return lhs.S == rhs.S && lhs.Us == rhs.Us; } +static inline bool operator<(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return lhs.S == rhs.S ? lhs.Us < rhs.Us : lhs.S < rhs.S; } +static inline bool operator>(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return rhs < lhs; } +static inline bool operator<=(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return lhs < rhs || lhs == rhs; } +static inline bool operator>=(const ImPlotTime& lhs, const ImPlotTime& rhs) +{ return lhs > rhs || lhs == rhs; } + +// Colormap data storage +struct ImPlotColormapData { + ImVector Keys; + ImVector KeyCounts; + ImVector KeyOffsets; + ImVector Tables; + ImVector TableSizes; + ImVector TableOffsets; + ImGuiTextBuffer Text; + ImVector TextOffsets; + ImVector Quals; + ImGuiStorage Map; + int Count; + + ImPlotColormapData() { Count = 0; } + + int Append(const char* name, const ImU32* keys, int count, bool qual) { + if (GetIndex(name) != -1) + return -1; + KeyOffsets.push_back(Keys.size()); + KeyCounts.push_back(count); + Keys.reserve(Keys.size()+count); + for (int i = 0; i < count; ++i) + Keys.push_back(keys[i]); + TextOffsets.push_back(Text.size()); + Text.append(name, name + strlen(name) + 1); + Quals.push_back(qual); + ImGuiID id = ImHashStr(name); + int idx = Count++; + Map.SetInt(id,idx); + _AppendTable(idx); + return idx; + } + + void _AppendTable(ImPlotColormap cmap) { + int key_count = GetKeyCount(cmap); + const ImU32* keys = GetKeys(cmap); + int off = Tables.size(); + TableOffsets.push_back(off); + if (IsQual(cmap)) { + Tables.reserve(key_count); + for (int i = 0; i < key_count; ++i) + Tables.push_back(keys[i]); + TableSizes.push_back(key_count); + } + else { + int max_size = 255 * (key_count-1) + 1; + Tables.reserve(off + max_size); + // ImU32 last = keys[0]; + // Tables.push_back(last); + // int n = 1; + for (int i = 0; i < key_count-1; ++i) { + for (int s = 0; s < 255; ++s) { + ImU32 a = keys[i]; + ImU32 b = keys[i+1]; + ImU32 c = ImMixU32(a,b,s); + // if (c != last) { + Tables.push_back(c); + // last = c; + // n++; + // } + } + } + ImU32 c = keys[key_count-1]; + // if (c != last) { + Tables.push_back(c); + // n++; + // } + // TableSizes.push_back(n); + TableSizes.push_back(max_size); + } + } + + void RebuildTables() { + Tables.resize(0); + TableSizes.resize(0); + TableOffsets.resize(0); + for (int i = 0; i < Count; ++i) + _AppendTable(i); + } + + inline bool IsQual(ImPlotColormap cmap) const { return Quals[cmap]; } + inline const char* GetName(ImPlotColormap cmap) const { return cmap < Count ? Text.Buf.Data + TextOffsets[cmap] : NULL; } + inline ImPlotColormap GetIndex(const char* name) const { ImGuiID key = ImHashStr(name); return Map.GetInt(key,-1); } + + inline const ImU32* GetKeys(ImPlotColormap cmap) const { return &Keys[KeyOffsets[cmap]]; } + inline int GetKeyCount(ImPlotColormap cmap) const { return KeyCounts[cmap]; } + inline ImU32 GetKeyColor(ImPlotColormap cmap, int idx) const { return Keys[KeyOffsets[cmap]+idx]; } + inline void SetKeyColor(ImPlotColormap cmap, int idx, ImU32 value) { Keys[KeyOffsets[cmap]+idx] = value; RebuildTables(); } + + inline const ImU32* GetTable(ImPlotColormap cmap) const { return &Tables[TableOffsets[cmap]]; } + inline int GetTableSize(ImPlotColormap cmap) const { return TableSizes[cmap]; } + inline ImU32 GetTableColor(ImPlotColormap cmap, int idx) const { return Tables[TableOffsets[cmap]+idx]; } + + inline ImU32 LerpTable(ImPlotColormap cmap, float t) const { + int off = TableOffsets[cmap]; + int siz = TableSizes[cmap]; + int idx = Quals[cmap] ? ImClamp((int)(siz*t),0,siz-1) : (int)((siz - 1) * t + 0.5f); + return Tables[off + idx]; + } + +}; + +// ImPlotPoint with positive/negative error values +struct ImPlotPointError { + double X, Y, Neg, Pos; + ImPlotPointError(double x, double y, double neg, double pos) { + X = x; Y = y; Neg = neg; Pos = pos; + } +}; + +// Interior plot label/annotation +struct ImPlotAnnotation { + ImVec2 Pos; + ImVec2 Offset; + ImU32 ColorBg; + ImU32 ColorFg; + int TextOffset; + bool Clamp; +}; + +// Collection of plot labels +struct ImPlotAnnotationCollection { + + ImVector Annotations; + ImGuiTextBuffer TextBuffer; + int Size; + + ImPlotAnnotationCollection() { Reset(); } + + void AppendV(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt, va_list args) IM_FMTLIST(7) { + ImPlotAnnotation an; + an.Pos = pos; an.Offset = off; + an.ColorBg = bg; an.ColorFg = fg; + an.TextOffset = TextBuffer.size(); + an.Clamp = clamp; + Annotations.push_back(an); + TextBuffer.appendfv(fmt, args); + const char nul[] = ""; + TextBuffer.append(nul,nul+1); + Size++; + } + + void Append(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt, ...) IM_FMTARGS(7) { + va_list args; + va_start(args, fmt); + AppendV(pos, off, bg, fg, clamp, fmt, args); + va_end(args); + } + + const char* GetText(int idx) { + return TextBuffer.Buf.Data + Annotations[idx].TextOffset; + } + + void Reset() { + Annotations.shrink(0); + TextBuffer.Buf.shrink(0); + Size = 0; + } +}; + +// Tick mark info +struct ImPlotTick +{ + double PlotPos; + float PixelPos; + ImVec2 LabelSize; + int TextOffset; + bool Major; + bool ShowLabel; + int Level; + + ImPlotTick(double value, bool major, bool show_label) { + PlotPos = value; + Major = major; + ShowLabel = show_label; + TextOffset = -1; + Level = 0; + } +}; + +// Collection of ticks +struct ImPlotTickCollection { + ImVector Ticks; + ImGuiTextBuffer TextBuffer; + float TotalWidth; + float TotalHeight; + float MaxWidth; + float MaxHeight; + int Size; + + ImPlotTickCollection() { Reset(); } + + void Append(const ImPlotTick& tick) { + if (tick.ShowLabel) { + TotalWidth += tick.ShowLabel ? tick.LabelSize.x : 0; + TotalHeight += tick.ShowLabel ? tick.LabelSize.y : 0; + MaxWidth = tick.LabelSize.x > MaxWidth ? tick.LabelSize.x : MaxWidth; + MaxHeight = tick.LabelSize.y > MaxHeight ? tick.LabelSize.y : MaxHeight; + } + Ticks.push_back(tick); + Size++; + } + + void Append(double value, bool major, bool show_label, void (*labeler)(ImPlotTick& tick, ImGuiTextBuffer& buf)) { + ImPlotTick tick(value, major, show_label); + if (labeler) + labeler(tick, TextBuffer); + Append(tick); + } + + const char* GetText(int idx) const { + return TextBuffer.Buf.Data + Ticks[idx].TextOffset; + } + + void Reset() { + Ticks.shrink(0); + TextBuffer.Buf.shrink(0); + TotalWidth = TotalHeight = MaxWidth = MaxHeight = 0; + Size = 0; + } +}; + +// Axis state information that must persist after EndPlot +struct ImPlotAxis +{ + ImPlotAxisFlags Flags; + ImPlotAxisFlags PreviousFlags; + ImPlotRange Range; + float Pixels; + ImPlotOrientation Orientation; + bool Dragging; + bool ExtHovered; + bool AllHovered; + bool Present; + bool HasRange; + double* LinkedMin; + double* LinkedMax; + ImPlotTime PickerTimeMin, PickerTimeMax; + int PickerLevel; + ImU32 ColorMaj, ColorMin, ColorTxt; + ImGuiCond RangeCond; + ImRect HoverRect; + + ImPlotAxis() { + Flags = PreviousFlags = ImPlotAxisFlags_None; + Range.Min = 0; + Range.Max = 1; + Dragging = false; + ExtHovered = false; + AllHovered = false; + LinkedMin = LinkedMax = NULL; + PickerLevel = 0; + ColorMaj = ColorMin = ColorTxt = 0; + } + + bool SetMin(double _min) { + _min = ImConstrainNan(ImConstrainInf(_min)); + if (ImHasFlag(Flags, ImPlotAxisFlags_LogScale)) + _min = ImConstrainLog(_min); + if (ImHasFlag(Flags, ImPlotAxisFlags_Time)) + _min = ImConstrainTime(_min); + if (_min >= Range.Max) + return false; + Range.Min = _min; + PickerTimeMin = ImPlotTime::FromDouble(Range.Min); + return true; + }; + + bool SetMax(double _max) { + _max = ImConstrainNan(ImConstrainInf(_max)); + if (ImHasFlag(Flags, ImPlotAxisFlags_LogScale)) + _max = ImConstrainLog(_max); + if (ImHasFlag(Flags, ImPlotAxisFlags_Time)) + _max = ImConstrainTime(_max); + if (_max <= Range.Min) + return false; + Range.Max = _max; + PickerTimeMax = ImPlotTime::FromDouble(Range.Max); + return true; + }; + + void SetRange(double _min, double _max) { + Range.Min = _min; + Range.Max = _max; + Constrain(); + PickerTimeMin = ImPlotTime::FromDouble(Range.Min); + PickerTimeMax = ImPlotTime::FromDouble(Range.Max); + } + + void SetRange(const ImPlotRange& range) { + SetRange(range.Min, range.Max); + } + + void SetAspect(double unit_per_pix) { + double new_size = unit_per_pix * Pixels; + double delta = (new_size - Range.Size()) * 0.5f; + if (IsLocked()) + return; + else if (IsLockedMin() && !IsLockedMax()) + SetRange(Range.Min, Range.Max + 2*delta); + else if (!IsLockedMin() && IsLockedMax()) + SetRange(Range.Min - 2*delta, Range.Max); + else + SetRange(Range.Min - delta, Range.Max + delta); + } + + double GetAspect() const { return Range.Size() / Pixels; } + + void Constrain() { + Range.Min = ImConstrainNan(ImConstrainInf(Range.Min)); + Range.Max = ImConstrainNan(ImConstrainInf(Range.Max)); + if (ImHasFlag(Flags, ImPlotAxisFlags_LogScale)) { + Range.Min = ImConstrainLog(Range.Min); + Range.Max = ImConstrainLog(Range.Max); + } + if (ImHasFlag(Flags, ImPlotAxisFlags_Time)) { + Range.Min = ImConstrainTime(Range.Min); + Range.Max = ImConstrainTime(Range.Max); + } + if (Range.Max <= Range.Min) + Range.Max = Range.Min + DBL_EPSILON; + } + + inline bool IsLabeled() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoTickLabels); } + inline bool IsInverted() const { return ImHasFlag(Flags, ImPlotAxisFlags_Invert); } + inline bool IsAutoFitting() const { return ImHasFlag(Flags, ImPlotAxisFlags_AutoFit); } + inline bool IsRangeLocked() const { return HasRange && RangeCond == ImGuiCond_Always; } + inline bool IsLockedMin() const { return ImHasFlag(Flags, ImPlotAxisFlags_LockMin) || IsRangeLocked(); } + inline bool IsLockedMax() const { return ImHasFlag(Flags, ImPlotAxisFlags_LockMax) || IsRangeLocked(); } + inline bool IsLocked() const { return !Present || ((IsLockedMin() && IsLockedMax()) || IsRangeLocked()); } + inline bool IsInputLocked() const { return IsLocked() || IsAutoFitting(); } + inline bool IsTime() const { return ImHasFlag(Flags, ImPlotAxisFlags_Time); } + inline bool IsLog() const { return ImHasFlag(Flags, ImPlotAxisFlags_LogScale); } +}; + +// State information for Plot items +struct ImPlotItem +{ + ImGuiID ID; + ImU32 Color; + int NameOffset; + bool Show; + bool LegendHovered; + bool SeenThisFrame; + + ImPlotItem() { + ID = 0; + // Color = ImPlot::NextColormapColor(); + NameOffset = -1; + Show = true; + SeenThisFrame = false; + LegendHovered = false; + } + + ~ImPlotItem() { ID = 0; } +}; + +// Holds Legend state labels and item references +struct ImPlotLegendData +{ + ImVector Indices; + ImGuiTextBuffer Labels; + void Reset() { Indices.shrink(0); Labels.Buf.shrink(0); } +}; + +// Holds Plot state information that must persist after EndPlot +struct ImPlotPlot +{ + ImGuiID ID; + ImPlotFlags Flags; + ImPlotFlags PreviousFlags; + ImPlotAxis XAxis; + ImPlotAxis YAxis[IMPLOT_Y_AXES]; + ImPlotLegendData LegendData; + ImPool Items; + ImVec2 SelectStart; + ImVec2 QueryStart; + ImRect QueryRect; + bool Selecting; + bool ContextLocked; + bool Querying; + bool Queried; + bool DraggingQuery; + bool LegendHovered; + bool LegendOutside; + bool LegendFlipSideNextFrame; + bool FrameHovered; + bool PlotHovered; + int ColormapIdx; + int CurrentYAxis; + ImPlotLocation MousePosLocation; + ImPlotLocation LegendLocation; + ImPlotOrientation LegendOrientation; + ImRect FrameRect; + ImRect CanvasRect; + ImRect PlotRect; + ImRect AxesRect; + ImRect LegendRect; + + ImPlotPlot() { + Flags = PreviousFlags = ImPlotFlags_None; + XAxis.Orientation = ImPlotOrientation_Horizontal; + for (int i = 0; i < IMPLOT_Y_AXES; ++i) + YAxis[i].Orientation = ImPlotOrientation_Vertical; + SelectStart = QueryStart = ImVec2(0,0); + Selecting = ContextLocked = Querying = Queried = DraggingQuery = LegendHovered = LegendOutside = LegendFlipSideNextFrame = false; + ColormapIdx = CurrentYAxis = 0; + LegendLocation = ImPlotLocation_North | ImPlotLocation_West; + LegendOrientation = ImPlotOrientation_Vertical; + MousePosLocation = ImPlotLocation_South | ImPlotLocation_East; + } + + int GetLegendCount() const { return LegendData.Indices.size(); } + ImPlotItem* GetLegendItem(int i); + const char* GetLegendLabel(int i); + + inline bool IsInputLocked() const { return XAxis.IsInputLocked() && YAxis[0].IsInputLocked() && YAxis[1].IsInputLocked() && YAxis[2].IsInputLocked(); } +}; + +// Temporary data storage for upcoming plot +struct ImPlotNextPlotData +{ + ImGuiCond XRangeCond; + ImGuiCond YRangeCond[IMPLOT_Y_AXES]; + ImPlotRange X; + ImPlotRange Y[IMPLOT_Y_AXES]; + bool HasXRange; + bool HasYRange[IMPLOT_Y_AXES]; + bool ShowDefaultTicksX; + bool ShowDefaultTicksY[IMPLOT_Y_AXES]; + bool FitX; + bool FitY[IMPLOT_Y_AXES]; + double* LinkedXmin; + double* LinkedXmax; + double* LinkedYmin[IMPLOT_Y_AXES]; + double* LinkedYmax[IMPLOT_Y_AXES]; + + ImPlotNextPlotData() { Reset(); } + + void Reset() { + HasXRange = false; + ShowDefaultTicksX = true; + FitX = false; + LinkedXmin = LinkedXmax = NULL; + for (int i = 0; i < IMPLOT_Y_AXES; ++i) { + HasYRange[i] = false; + ShowDefaultTicksY[i] = true; + FitY[i] = false; + LinkedYmin[i] = LinkedYmax[i] = NULL; + } + } + +}; + +// Temporary data storage for upcoming item +struct ImPlotNextItemData { + ImVec4 Colors[5]; // ImPlotCol_Line, ImPlotCol_Fill, ImPlotCol_MarkerOutline, ImPlotCol_MarkerFill, ImPlotCol_ErrorBar + float LineWeight; + ImPlotMarker Marker; + float MarkerSize; + float MarkerWeight; + float FillAlpha; + float ErrorBarSize; + float ErrorBarWeight; + float DigitalBitHeight; + float DigitalBitGap; + bool RenderLine; + bool RenderFill; + bool RenderMarkerLine; + bool RenderMarkerFill; + bool HasHidden; + bool Hidden; + ImGuiCond HiddenCond; + ImPlotNextItemData() { Reset(); } + void Reset() { + for (int i = 0; i < 5; ++i) + Colors[i] = IMPLOT_AUTO_COL; + LineWeight = MarkerSize = MarkerWeight = FillAlpha = ErrorBarSize = ErrorBarWeight = DigitalBitHeight = DigitalBitGap = IMPLOT_AUTO; + Marker = IMPLOT_AUTO; + HasHidden = Hidden = false; + } +}; + +// Holds state information that must persist between calls to BeginPlot()/EndPlot() +struct ImPlotContext { + // Plot States + ImPool Plots; + ImPlotPlot* CurrentPlot; + ImPlotItem* CurrentItem; + ImPlotItem* PreviousItem; + + // Tick Marks and Labels + ImPlotTickCollection CTicks; + ImPlotTickCollection XTicks; + ImPlotTickCollection YTicks[IMPLOT_Y_AXES]; + float YAxisReference[IMPLOT_Y_AXES]; + + // Annotation and User Labels + ImPlotAnnotationCollection Annotations; + + // Transformations and Data Extents + ImPlotScale Scales[IMPLOT_Y_AXES]; + ImRect PixelRange[IMPLOT_Y_AXES]; + double Mx; + double My[IMPLOT_Y_AXES]; + double LogDenX; + double LogDenY[IMPLOT_Y_AXES]; + ImPlotRange ExtentsX; + ImPlotRange ExtentsY[IMPLOT_Y_AXES]; + + // Data Fitting Flags + bool FitThisFrame; + bool FitX; + bool FitY[IMPLOT_Y_AXES]; + + // Axis Rendering Flags + bool RenderX; + bool RenderY[IMPLOT_Y_AXES]; + + // Axis Locking Flags + bool ChildWindowMade; + + // Style and Colormaps + ImPlotStyle Style; + ImVector ColorModifiers; + ImVector StyleModifiers; + ImPlotColormapData ColormapData; + ImVector ColormapModifiers; + + // Time + tm Tm; + + // Temp data for general use + ImVector Temp1, Temp2; + + // Misc + int VisibleItemCount; + int DigitalPlotItemCnt; + int DigitalPlotOffset; + ImPlotNextPlotData NextPlotData; + ImPlotNextItemData NextItemData; + ImPlotInputMap InputMap; + ImPlotPoint MousePos[IMPLOT_Y_AXES]; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Internal API +// No guarantee of forward compatibility here! +//----------------------------------------------------------------------------- + +namespace ImPlot { + +//----------------------------------------------------------------------------- +// [SECTION] Context Utils +//----------------------------------------------------------------------------- + +// Initializes an ImPlotContext +IMPLOT_API void Initialize(ImPlotContext* ctx); +// Resets an ImPlot context for the next call to BeginPlot +IMPLOT_API void Reset(ImPlotContext* ctx); + +//----------------------------------------------------------------------------- +// [SECTION] Input Utils +//----------------------------------------------------------------------------- + +// Allows changing how keyboard/mouse interaction works. +IMPLOT_API ImPlotInputMap& GetInputMap(); + +//----------------------------------------------------------------------------- +// [SECTION] Plot Utils +//----------------------------------------------------------------------------- + +// Gets a plot from the current ImPlotContext +IMPLOT_API ImPlotPlot* GetPlot(const char* title); +// Gets the current plot from the current ImPlotContext +IMPLOT_API ImPlotPlot* GetCurrentPlot(); +// Busts the cache for every plot in the current context +IMPLOT_API void BustPlotCache(); + +// Shows a plot's context menu. +IMPLOT_API void ShowPlotContextMenu(ImPlotPlot& plot); + +//----------------------------------------------------------------------------- +// [SECTION] Item Utils +//----------------------------------------------------------------------------- + +// Begins a new item. Returns false if the item should not be plotted. Pushes PlotClipRect. +IMPLOT_API bool BeginItem(const char* label_id, ImPlotCol recolor_from = -1); +// Ends an item (call only if BeginItem returns true). Pops PlotClipRect. +IMPLOT_API void EndItem(); + +// Register or get an existing item from the current plot. +IMPLOT_API ImPlotItem* RegisterOrGetItem(const char* label_id, bool* just_created = NULL); +// Get a plot item from the current plot. +IMPLOT_API ImPlotItem* GetItem(const char* label_id); +// Gets the current item. +IMPLOT_API ImPlotItem* GetCurrentItem(); +// Busts the cache for every item for every plot in the current context. +IMPLOT_API void BustItemCache(); + +//----------------------------------------------------------------------------- +// [SECTION] Axis Utils +//----------------------------------------------------------------------------- + +// Gets the current y-axis for the current plot +inline int GetCurrentYAxis() { return GImPlot->CurrentPlot->CurrentYAxis; } +// Updates axis ticks, lins, and label colors +IMPLOT_API void UpdateAxisColors(int axis_flag, ImPlotAxis* axis); + +// Updates plot-to-pixel space transformation variables for the current plot. +IMPLOT_API void UpdateTransformCache(); +// Gets the XY scale for the current plot and y-axis +inline ImPlotScale GetCurrentScale() { return GImPlot->Scales[GetCurrentYAxis()]; } + +// Returns true if the user has requested data to be fit. +inline bool FitThisFrame() { return GImPlot->FitThisFrame; } +// Extends the current plot's axes so that it encompasses point p +IMPLOT_API void FitPoint(const ImPlotPoint& p); +// Extends the current plot's axes so that it encompasses a vertical line at x +IMPLOT_API void FitPointX(double x); +// Extends the current plot's axes so that it encompasses a horizontal line at y +IMPLOT_API void FitPointY(double y); + +// Returns true if two ranges overlap +inline bool RangesOverlap(const ImPlotRange& r1, const ImPlotRange& r2) +{ return r1.Min <= r2.Max && r2.Min <= r1.Max; } + +// Updates pointers for linked axes from axis internal range. +IMPLOT_API void PushLinkedAxis(ImPlotAxis& axis); +// Updates axis internal range from points for linked axes. +IMPLOT_API void PullLinkedAxis(ImPlotAxis& axis); + +// Shows an axis's context menu. +IMPLOT_API void ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool time_allowed = false); + +//----------------------------------------------------------------------------- +// [SECTION] Legend Utils +//----------------------------------------------------------------------------- + +// Gets the position of an inner rect that is located inside of an outer rect according to an ImPlotLocation and padding amount. +IMPLOT_API ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation location, const ImVec2& pad = ImVec2(0,0)); +// Calculates the bounding box size of a legend +IMPLOT_API ImVec2 CalcLegendSize(ImPlotPlot& plot, const ImVec2& pad, const ImVec2& spacing, ImPlotOrientation orientation); +// Renders legend entries into a bounding box +IMPLOT_API void ShowLegendEntries(ImPlotPlot& plot, const ImRect& legend_bb, bool interactable, const ImVec2& pad, const ImVec2& spacing, ImPlotOrientation orientation, ImDrawList& DrawList); +// Shows an alternate legend for the plot identified by #title_id, outside of the plot frame (can be called before or after of Begin/EndPlot but must occur in the same ImGui window!). +IMPLOT_API void ShowAltLegend(const char* title_id, ImPlotOrientation orientation = ImPlotOrientation_Vertical, const ImVec2 size = ImVec2(0,0), bool interactable = true); + +//----------------------------------------------------------------------------- +// [SECTION] Tick Utils +//----------------------------------------------------------------------------- + +// Label a tick with default formatting. +IMPLOT_API void LabelTickDefault(ImPlotTick& tick, ImGuiTextBuffer& buffer); +// Label a tick with scientific formating. +IMPLOT_API void LabelTickScientific(ImPlotTick& tick, ImGuiTextBuffer& buffer); +// Label a tick with time formatting. +IMPLOT_API void LabelTickTime(ImPlotTick& tick, ImGuiTextBuffer& buffer, const ImPlotTime& t, ImPlotDateTimeFmt fmt); + +// Populates a list of ImPlotTicks with normal spaced and formatted ticks +IMPLOT_API void AddTicksDefault(const ImPlotRange& range, int nMajor, int nMinor, ImPlotTickCollection& ticks); +// Populates a list of ImPlotTicks with logarithmic space and formatted ticks +IMPLOT_API void AddTicksLogarithmic(const ImPlotRange& range, int nMajor, ImPlotTickCollection& ticks); +// Populates a list of ImPlotTicks with time formatted ticks. +IMPLOT_API void AddTicksTime(const ImPlotRange& range, float plot_width, ImPlotTickCollection& ticks); +// Populates a list of ImPlotTicks with custom spaced and labeled ticks +IMPLOT_API void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlotTickCollection& ticks); + +// Create a a string label for a an axis value +IMPLOT_API int LabelAxisValue(const ImPlotAxis& axis, const ImPlotTickCollection& ticks, double value, char* buff, int size); + +//----------------------------------------------------------------------------- +// [SECTION] Styling Utils +//----------------------------------------------------------------------------- + +// Get styling data for next item (call between Begin/EndItem) +inline const ImPlotNextItemData& GetItemData() { return GImPlot->NextItemData; } + +// Returns true if a color is set to be automatically determined +inline bool IsColorAuto(const ImVec4& col) { return col.w == -1; } +// Returns true if a style color is set to be automaticaly determined +inline bool IsColorAuto(ImPlotCol idx) { return IsColorAuto(GImPlot->Style.Colors[idx]); } +// Returns the automatically deduced style color +IMPLOT_API ImVec4 GetAutoColor(ImPlotCol idx); + +// Returns the style color whether it is automatic or custom set +inline ImVec4 GetStyleColorVec4(ImPlotCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot->Style.Colors[idx]; } +inline ImU32 GetStyleColorU32(ImPlotCol idx) { return ImGui::ColorConvertFloat4ToU32(GetStyleColorVec4(idx)); } + +// Draws vertical text. The position is the bottom left of the text rect. +IMPLOT_API void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char* text_begin, const char* text_end = NULL); +// Calculates the size of vertical text +inline ImVec2 CalcTextSizeVertical(const char *text) { + ImVec2 sz = ImGui::CalcTextSize(text); + return ImVec2(sz.y, sz.x); +} +// Returns white or black text given background color +inline ImU32 CalcTextColor(const ImVec4& bg) { return (bg.x * 0.299 + bg.y * 0.587 + bg.z * 0.114) > 0.5 ? IM_COL32_BLACK : IM_COL32_WHITE; } +inline ImU32 CalcTextColor(ImU32 bg) { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); } + +// Clamps a label position so that it fits a rect defined by Min/Max +inline ImVec2 ClampLabelPos(ImVec2 pos, const ImVec2& size, const ImVec2& Min, const ImVec2& Max) { + if (pos.x < Min.x) pos.x = Min.x; + if (pos.y < Min.y) pos.y = Min.y; + if ((pos.x + size.x) > Max.x) pos.x = Max.x - size.x; + if ((pos.y + size.y) > Max.y) pos.y = Max.y - size.y; + return pos; +} + +// Returns a color from the Color map given an index >= 0 (modulo will be performed). +IMPLOT_API ImU32 GetColormapColorU32(int idx, ImPlotColormap cmap); +// Returns the next unused colormap color and advances the colormap. Can be used to skip colors if desired. +IMPLOT_API ImU32 NextColormapColorU32(); +// Linearly interpolates a color from the current colormap given t between 0 and 1. +IMPLOT_API ImU32 SampleColormapU32(float t, ImPlotColormap cmap); + +// Render a colormap bar +IMPLOT_API void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous); + +//----------------------------------------------------------------------------- +// [SECTION] Math and Misc Utils +//----------------------------------------------------------------------------- + +// Rounds x to powers of 2,5 and 10 for generating axis labels (from Graphics Gems 1 Chapter 11.2) +IMPLOT_API double NiceNum(double x, bool round); +// Computes order of magnitude of double. +inline int OrderOfMagnitude(double val) { return val == 0 ? 0 : (int)(floor(log10(fabs(val)))); } +// Returns the precision required for a order of magnitude. +inline int OrderToPrecision(int order) { return order > 0 ? 0 : 1 - order; } +// Returns a floating point precision to use given a value +inline int Precision(double val) { return OrderToPrecision(OrderOfMagnitude(val)); } + +// Returns the intersection point of two lines A and B (assumes they are not parallel!) +inline ImVec2 Intersection(const ImVec2& a1, const ImVec2& a2, const ImVec2& b1, const ImVec2& b2) { + float v1 = (a1.x * a2.y - a1.y * a2.x); float v2 = (b1.x * b2.y - b1.y * b2.x); + float v3 = ((a1.x - a2.x) * (b1.y - b2.y) - (a1.y - a2.y) * (b1.x - b2.x)); + return ImVec2((v1 * (b1.x - b2.x) - v2 * (a1.x - a2.x)) / v3, (v1 * (b1.y - b2.y) - v2 * (a1.y - a2.y)) / v3); +} + +// Fills a buffer with n samples linear interpolated from vmin to vmax +template +void FillRange(ImVector& buffer, int n, T vmin, T vmax) { + buffer.resize(n); + T step = (vmax - vmin) / (n - 1); + for (int i = 0; i < n; ++i) { + buffer[i] = vmin + i * step; + } +} + +// Offsets and strides a data buffer +template +inline T OffsetAndStride(const T* data, int idx, int count, int offset, int stride) { + idx = ImPosMod(offset + idx, count); + return *(const T*)(const void*)((const unsigned char*)data + (size_t)idx * stride); +} + +// Calculate histogram bin counts and widths +template +void CalculateBins(const T* values, int count, ImPlotBin meth, const ImPlotRange& range, int& bins_out, double& width_out) { + switch (meth) { + case ImPlotBin_Sqrt: + bins_out = (int)ceil(sqrt(count)); + break; + case ImPlotBin_Sturges: + bins_out = (int)ceil(1.0 + log2(count)); + break; + case ImPlotBin_Rice: + bins_out = (int)ceil(2 * cbrt(count)); + break; + case ImPlotBin_Scott: + width_out = 3.49 * ImStdDev(values, count) / cbrt(count); + bins_out = (int)round(range.Size() / width_out); + break; + } + width_out = range.Size() / bins_out; +} + +//----------------------------------------------------------------------------- +// Time Utils +//----------------------------------------------------------------------------- + +// Returns true if year is leap year (366 days long) +inline bool IsLeapYear(int year) { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); +} +// Returns the number of days in a month, accounting for Feb. leap years. #month is zero indexed. +inline int GetDaysInMonth(int year, int month) { + static const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + return days[month] + (int)(month == 1 && IsLeapYear(year)); +} + +// Make a UNIX timestamp from a tm struct expressed in UTC time (i.e. GMT timezone). +IMPLOT_API ImPlotTime MkGmtTime(struct tm *ptm); +// Make a tm struct expressed in UTC time (i.e. GMT timezone) from a UNIX timestamp. +IMPLOT_API tm* GetGmtTime(const ImPlotTime& t, tm* ptm); + +// Make a UNIX timestamp from a tm struct expressed in local time. +IMPLOT_API ImPlotTime MkLocTime(struct tm *ptm); +// Make a tm struct expressed in local time from a UNIX timestamp. +IMPLOT_API tm* GetLocTime(const ImPlotTime& t, tm* ptm); + +// NB: The following functions only work if there is a current ImPlotContext because the +// internal tm struct is owned by the context! They are aware of ImPlotStyle.UseLocalTime. + +// Make a timestamp from time components. +// year[1970-3000], month[0-11], day[1-31], hour[0-23], min[0-59], sec[0-59], us[0,999999] +IMPLOT_API ImPlotTime MakeTime(int year, int month = 0, int day = 1, int hour = 0, int min = 0, int sec = 0, int us = 0); +// Get year component from timestamp [1970-3000] +IMPLOT_API int GetYear(const ImPlotTime& t); + +// Adds or subtracts time from a timestamp. #count > 0 to add, < 0 to subtract. +IMPLOT_API ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count); +// Rounds a timestamp down to nearest unit. +IMPLOT_API ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit); +// Rounds a timestamp up to the nearest unit. +IMPLOT_API ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit); +// Rounds a timestamp up or down to the nearest unit. +IMPLOT_API ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit); +// Combines the date of one timestamp with the time-of-day of another timestamp. +IMPLOT_API ImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& time_part); + +// Formats the time part of timestamp t into a buffer according to #fmt +IMPLOT_API int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk); +// Formats the date part of timestamp t into a buffer according to #fmt +IMPLOT_API int FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601); +// Formats the time and/or date parts of a timestamp t into a buffer according to #fmt +IMPLOT_API int FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeFmt fmt); + +// Shows a date picker widget block (year/month/day). +// #level = 0 for day, 1 for month, 2 for year. Modified by user interaction. +// #t will be set when a day is clicked and the function will return true. +// #t1 and #t2 are optional dates to highlight. +IMPLOT_API bool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1 = NULL, const ImPlotTime* t2 = NULL); +// Shows a time picker widget block (hour/min/sec). +// #t will be set when a new hour, minute, or sec is selected or am/pm is toggled, and the function will return true. +IMPLOT_API bool ShowTimePicker(const char* id, ImPlotTime* t); + +} // namespace ImPlot diff --git a/DearPyGui/vendor/implot/implot_items.cpp b/DearPyGui/vendor/implot/implot_items.cpp new file mode 100644 index 000000000..99cd6b0b4 --- /dev/null +++ b/DearPyGui/vendor/implot/implot_items.cpp @@ -0,0 +1,2233 @@ +// MIT License + +// Copyright (c) 2020 Evan Pezent + +// 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. + +// ImPlot v0.9 WIP + +#include "implot.h" +#include "implot_internal.h" + +#ifdef _MSC_VER +#define sprintf sprintf_s +#endif + +#define SQRT_1_2 0.70710678118f +#define SQRT_3_2 0.86602540378f + +#define IMPLOT_NORMALIZE2F_OVER_ZERO(VX, VY) \ + { \ + float d2 = VX * VX + VY * VY; \ + if (d2 > 0.0f) { \ + float inv_len = 1.0f / ImSqrt(d2); \ + VX *= inv_len; \ + VY *= inv_len; \ + } \ + } + +// Support for pre-1.82 version. Users on 1.82+ can use 0 (default) flags to mean "all corners" but in order to support older versions we are more explicit. +#if (IMGUI_VERSION_NUM < 18102) && !defined(ImDrawFlags_RoundCornersAll) +#define ImDrawFlags_RoundCornersAll ImDrawCornerFlags_All +#endif + +namespace ImPlot { + +//----------------------------------------------------------------------------- +// Item Utils +//----------------------------------------------------------------------------- + +ImPlotItem* RegisterOrGetItem(const char* label_id, bool* just_created) { + ImPlotContext& gp = *GImPlot; + ImGuiID id = ImGui::GetID(label_id); + if (just_created != NULL) + *just_created = gp.CurrentPlot->Items.GetByKey(id) == NULL; + ImPlotItem* item = gp.CurrentPlot->Items.GetOrAddByKey(id); + if (item->SeenThisFrame) + return item; + item->SeenThisFrame = true; + int idx = gp.CurrentPlot->Items.GetIndex(item); + item->ID = id; + if (ImGui::FindRenderedTextEnd(label_id, NULL) != label_id) { + gp.CurrentPlot->LegendData.Indices.push_back(idx); + item->NameOffset = gp.CurrentPlot->LegendData.Labels.size(); + gp.CurrentPlot->LegendData.Labels.append(label_id, label_id + strlen(label_id) + 1); + } + else { + item->Show = true; + } + if (item->Show) + gp.VisibleItemCount++; + return item; +} + +ImPlotItem* GetItem(const char* label_id) { + ImPlotContext& gp = *GImPlot; + ImGuiID id = ImGui::GetID(label_id); + return gp.CurrentPlot->Items.GetByKey(id); +} + +ImPlotItem* GetCurrentItem() { + ImPlotContext& gp = *GImPlot; + return gp.CurrentItem; +} + +void SetNextLineStyle(const ImVec4& col, float weight) { + ImPlotContext& gp = *GImPlot; + gp.NextItemData.Colors[ImPlotCol_Line] = col; + gp.NextItemData.LineWeight = weight; +} + +void SetNextFillStyle(const ImVec4& col, float alpha) { + ImPlotContext& gp = *GImPlot; + gp.NextItemData.Colors[ImPlotCol_Fill] = col; + gp.NextItemData.FillAlpha = alpha; +} + +void SetNextMarkerStyle(ImPlotMarker marker, float size, const ImVec4& fill, float weight, const ImVec4& outline) { + ImPlotContext& gp = *GImPlot; + gp.NextItemData.Marker = marker; + gp.NextItemData.Colors[ImPlotCol_MarkerFill] = fill; + gp.NextItemData.MarkerSize = size; + gp.NextItemData.Colors[ImPlotCol_MarkerOutline] = outline; + gp.NextItemData.MarkerWeight = weight; +} + +void SetNextErrorBarStyle(const ImVec4& col, float size, float weight) { + ImPlotContext& gp = *GImPlot; + gp.NextItemData.Colors[ImPlotCol_ErrorBar] = col; + gp.NextItemData.ErrorBarSize = size; + gp.NextItemData.ErrorBarWeight = weight; +} + +ImVec4 GetLastItemColor() { + ImPlotContext& gp = *GImPlot; + if (gp.PreviousItem) + return ImGui::ColorConvertU32ToFloat4(gp.PreviousItem->Color); + return ImVec4(); +} + +void HideNextItem(bool hidden, ImGuiCond cond) { + ImPlotContext& gp = *GImPlot; + gp.NextItemData.HasHidden = true; + gp.NextItemData.Hidden = hidden; + gp.NextItemData.HiddenCond = cond; +} + +void BustItemCache() { + ImPlotContext& gp = *GImPlot; + for (int p = 0; p < gp.Plots.GetSize(); ++p) { + ImPlotPlot& plot = *gp.Plots.GetByIndex(p); + plot.ColormapIdx = 0; + plot.Items.Clear(); + plot.LegendData.Reset(); + } +} + +void BustColorCache(const char* plot_title_id) { + ImPlotContext& gp = *GImPlot; + if (plot_title_id == NULL) { + BustItemCache(); + } + else { + ImPlotPlot* plot = gp.Plots.GetByKey(ImGui::GetCurrentWindow()->GetID(plot_title_id)); + if (plot == NULL) + return; + plot->ColormapIdx = 0; + plot->Items.Clear(); + plot->LegendData.Reset(); + } +} + +//----------------------------------------------------------------------------- +// Begin/EndItem +//----------------------------------------------------------------------------- + +// Begins a new item. Returns false if the item should not be plotted. +bool BeginItem(const char* label_id, ImPlotCol recolor_from) { + ImPlotContext& gp = *GImPlot; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PlotX() needs to be called between BeginPlot() and EndPlot()!"); + bool just_created; + ImPlotItem* item = RegisterOrGetItem(label_id, &just_created); + // set current item + gp.CurrentItem = item; + ImPlotNextItemData& s = gp.NextItemData; + // set/override item color + if (recolor_from != -1) { + if (!IsColorAuto(s.Colors[recolor_from])) + item->Color = ImGui::ColorConvertFloat4ToU32(s.Colors[recolor_from]); + else if (!IsColorAuto(gp.Style.Colors[recolor_from])) + item->Color = ImGui::ColorConvertFloat4ToU32(gp.Style.Colors[recolor_from]); + else if (just_created) + item->Color = NextColormapColorU32(); + } + else if (just_created) { + item->Color = NextColormapColorU32(); + } + // hide/show item + if (gp.NextItemData.HasHidden) { + if (just_created || gp.NextItemData.HiddenCond == ImGuiCond_Always) + item->Show = !gp.NextItemData.Hidden; + } + if (!item->Show) { + // reset next item data + gp.NextItemData.Reset(); + gp.PreviousItem = item; + gp.CurrentItem = NULL; + return false; + } + else { + ImVec4 item_color = ImGui::ColorConvertU32ToFloat4(item->Color); + // stage next item colors + s.Colors[ImPlotCol_Line] = IsColorAuto(s.Colors[ImPlotCol_Line]) ? ( IsColorAuto(ImPlotCol_Line) ? item_color : gp.Style.Colors[ImPlotCol_Line] ) : s.Colors[ImPlotCol_Line]; + s.Colors[ImPlotCol_Fill] = IsColorAuto(s.Colors[ImPlotCol_Fill]) ? ( IsColorAuto(ImPlotCol_Fill) ? item_color : gp.Style.Colors[ImPlotCol_Fill] ) : s.Colors[ImPlotCol_Fill]; + s.Colors[ImPlotCol_MarkerOutline] = IsColorAuto(s.Colors[ImPlotCol_MarkerOutline]) ? ( IsColorAuto(ImPlotCol_MarkerOutline) ? s.Colors[ImPlotCol_Line] : gp.Style.Colors[ImPlotCol_MarkerOutline] ) : s.Colors[ImPlotCol_MarkerOutline]; + s.Colors[ImPlotCol_MarkerFill] = IsColorAuto(s.Colors[ImPlotCol_MarkerFill]) ? ( IsColorAuto(ImPlotCol_MarkerFill) ? s.Colors[ImPlotCol_Line] : gp.Style.Colors[ImPlotCol_MarkerFill] ) : s.Colors[ImPlotCol_MarkerFill]; + s.Colors[ImPlotCol_ErrorBar] = IsColorAuto(s.Colors[ImPlotCol_ErrorBar]) ? ( GetStyleColorVec4(ImPlotCol_ErrorBar) ) : s.Colors[ImPlotCol_ErrorBar]; + // stage next item style vars + s.LineWeight = s.LineWeight < 0 ? gp.Style.LineWeight : s.LineWeight; + s.Marker = s.Marker < 0 ? gp.Style.Marker : s.Marker; + s.MarkerSize = s.MarkerSize < 0 ? gp.Style.MarkerSize : s.MarkerSize; + s.MarkerWeight = s.MarkerWeight < 0 ? gp.Style.MarkerWeight : s.MarkerWeight; + s.FillAlpha = s.FillAlpha < 0 ? gp.Style.FillAlpha : s.FillAlpha; + s.ErrorBarSize = s.ErrorBarSize < 0 ? gp.Style.ErrorBarSize : s.ErrorBarSize; + s.ErrorBarWeight = s.ErrorBarWeight < 0 ? gp.Style.ErrorBarWeight : s.ErrorBarWeight; + s.DigitalBitHeight = s.DigitalBitHeight < 0 ? gp.Style.DigitalBitHeight : s.DigitalBitHeight; + s.DigitalBitGap = s.DigitalBitGap < 0 ? gp.Style.DigitalBitGap : s.DigitalBitGap; + // apply alpha modifier(s) + s.Colors[ImPlotCol_Fill].w *= s.FillAlpha; + // s.Colors[ImPlotCol_MarkerFill].w *= s.FillAlpha; // TODO: this should be separate, if it at all + // apply highlight mods + if (item->LegendHovered && !ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_NoHighlight)) { + s.LineWeight *= 2; + s.MarkerWeight *= 2; + // TODO: highlight fills? + } + // set render flags + s.RenderLine = s.Colors[ImPlotCol_Line].w > 0 && s.LineWeight > 0; + s.RenderFill = s.Colors[ImPlotCol_Fill].w > 0; + s.RenderMarkerLine = s.Colors[ImPlotCol_MarkerOutline].w > 0 && s.MarkerWeight > 0; + s.RenderMarkerFill = s.Colors[ImPlotCol_MarkerFill].w > 0; + // push rendering clip rect + PushPlotClipRect(); + return true; + } +} + +// Ends an item (call only if BeginItem returns true) +void EndItem() { + ImPlotContext& gp = *GImPlot; + // pop rendering clip rect + PopPlotClipRect(); + // reset next item data + gp.NextItemData.Reset(); + // set current item + gp.PreviousItem = gp.CurrentItem; + gp.CurrentItem = NULL; +} + +//----------------------------------------------------------------------------- +// GETTERS +//----------------------------------------------------------------------------- + +// Getters can be thought of as iterators that convert user data (e.g. raw arrays) +// to ImPlotPoints + +// Interprets an array of Y points as ImPlotPoints where the X value is the index +template +struct GetterYs { + GetterYs(const T* ys, int count, double xscale, double x0, int offset, int stride) : + Ys(ys), + Count(count), + XScale(xscale), + X0(x0), + Offset(count ? ImPosMod(offset, count) : 0), + Stride(stride) + { } + inline ImPlotPoint operator()(int idx) const { + return ImPlotPoint(X0 + XScale * idx, (double)OffsetAndStride(Ys, idx, Count, Offset, Stride)); + } + const T* const Ys; + const int Count; + const double XScale; + const double X0; + const int Offset; + const int Stride; +}; + +// Interprets separate arrays for X and Y points as ImPlotPoints +template +struct GetterXsYs { + GetterXsYs(const T* xs, const T* ys, int count, int offset, int stride) : + Xs(xs), + Ys(ys), + Count(count), + Offset(count ? ImPosMod(offset, count) : 0), + Stride(stride) + { } + inline ImPlotPoint operator()(int idx) const { + return ImPlotPoint((double)OffsetAndStride(Xs, idx, Count, Offset, Stride), (double)OffsetAndStride(Ys, idx, Count, Offset, Stride)); + } + const T* const Xs; + const T* const Ys; + const int Count; + const int Offset; + const int Stride; +}; + +// Always returns a constant Y reference value where the X value is the index +struct GetterYRef { + GetterYRef(double y_ref, int count, double xscale, double x0) : + YRef(y_ref), + Count(count), + XScale(xscale), + X0(x0) + { } + inline ImPlotPoint operator()(int idx) const { + return ImPlotPoint(X0 + XScale*idx, YRef); + } + const double YRef; + const int Count; + const double XScale; + const double X0; +}; + +// Interprets an array of X points as ImPlotPoints where the Y value is a constant reference value +template +struct GetterXsYRef { + GetterXsYRef(const T* xs, double y_ref, int count, int offset, int stride) : + Xs(xs), + YRef(y_ref), + Count(count), + Offset(count ? ImPosMod(offset, count) : 0), + Stride(stride) + { } + inline ImPlotPoint operator()(int idx) const { + return ImPlotPoint((double)OffsetAndStride(Xs, idx, Count, Offset, Stride), YRef); + } + const T* const Xs; + const double YRef; + const int Count; + const int Offset; + const int Stride; +}; + +// Interprets an array of Y points as ImPlotPoints where the X value is a constant reference value +template +struct GetterXRefYs { + GetterXRefYs(double x_ref, const T* ys, int count, int offset, int stride) : + XRef(x_ref), + Ys(ys), + Count(count), + Offset(count ? ImPosMod(offset, count) : 0), + Stride(stride) + { } + inline ImPlotPoint operator()(int idx) const { + return ImPlotPoint(XRef, (double)OffsetAndStride(Ys, idx, Count, Offset, Stride)); + } + const double XRef; + const T* const Ys; + const int Count; + const int Offset; + const int Stride; +}; + +/// Interprets a user's function pointer as ImPlotPoints +struct GetterFuncPtr { + GetterFuncPtr(ImPlotPoint (*getter)(void* data, int idx), void* data, int count, int offset) : + Getter(getter), + Data(data), + Count(count), + Offset(count ? ImPosMod(offset, count) : 0) + { } + inline ImPlotPoint operator()(int idx) const { + idx = ImPosMod(Offset + idx, Count); + return Getter(Data, idx); + } + ImPlotPoint (* const Getter)(void* data, int idx); + void* const Data; + const int Count; + const int Offset; +}; + +template +struct GetterBarV { + const T* Ys; double XShift; int Count; int Offset; int Stride; + GetterBarV(const T* ys, double xshift, int count, int offset, int stride) { Ys = ys; XShift = xshift; Count = count; Offset = offset; Stride = stride; } + inline ImPlotPoint operator()(int idx) const { return ImPlotPoint((double)idx + (double)XShift, (double)OffsetAndStride(Ys, idx, Count, Offset, Stride)); } +}; + +template +struct GetterBarH { + const T* Xs; double YShift; int Count; int Offset; int Stride; + GetterBarH(const T* xs, double yshift, int count, int offset, int stride) { Xs = xs; YShift = yshift; Count = count; Offset = offset; Stride = stride; } + inline ImPlotPoint operator()(int idx) const { return ImPlotPoint((double)OffsetAndStride(Xs, idx, Count, Offset, Stride), (double)idx + (double)YShift); } +}; + +template +struct GetterError { + GetterError(const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) : + Xs(xs), + Ys(ys), + Neg(neg), + Pos(pos), + Count(count), + Offset(count ? ImPosMod(offset, count) : 0), + Stride(stride) + { } + inline ImPlotPointError operator()(int idx) const { + return ImPlotPointError((double)OffsetAndStride(Xs, idx, Count, Offset, Stride), + (double)OffsetAndStride(Ys, idx, Count, Offset, Stride), + (double)OffsetAndStride(Neg, idx, Count, Offset, Stride), + (double)OffsetAndStride(Pos, idx, Count, Offset, Stride)); + } + const T* const Xs; + const T* const Ys; + const T* const Neg; + const T* const Pos; + const int Count; + const int Offset; + const int Stride; +}; + +//----------------------------------------------------------------------------- +// TRANSFORMERS +//----------------------------------------------------------------------------- + +// Transforms convert points in plot space (i.e. ImPlotPoint) to pixel space (i.e. ImVec2) + +// Transforms points for linear x and linear y space +struct TransformerLinLin { + TransformerLinLin() : YAxis(GetCurrentYAxis()) {} + // inline ImVec2 operator()(const ImPlotPoint& plt) const { return (*this)(plt.x, plt.y); } + inline ImVec2 operator()(const ImPlotPoint& plt) const { + ImPlotContext& gp = *GImPlot; + return ImVec2( (float)(gp.PixelRange[YAxis].Min.x + gp.Mx * (plt.x - gp.CurrentPlot->XAxis.Range.Min)), + (float)(gp.PixelRange[YAxis].Min.y + gp.My[YAxis] * (plt.y - gp.CurrentPlot->YAxis[YAxis].Range.Min)) ); + } + const int YAxis; +}; + +// Transforms points for log x and linear y space +struct TransformerLogLin { + TransformerLogLin() : YAxis(GetCurrentYAxis()) {} + inline ImVec2 operator()(const ImPlotPoint& plt) const { + ImPlotContext& gp = *GImPlot; + double t = ImLog10(plt.x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX; + double x = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, (float)t); + return ImVec2( (float)(gp.PixelRange[YAxis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min)), + (float)(gp.PixelRange[YAxis].Min.y + gp.My[YAxis] * (plt.y - gp.CurrentPlot->YAxis[YAxis].Range.Min)) ); + } + const int YAxis; +}; + +// Transforms points for linear x and log y space +struct TransformerLinLog { + TransformerLinLog() : YAxis(GetCurrentYAxis()) {} + inline ImVec2 operator()(const ImPlotPoint& plt) const { + ImPlotContext& gp = *GImPlot; + double t = ImLog10(plt.y / gp.CurrentPlot->YAxis[YAxis].Range.Min) / gp.LogDenY[YAxis]; + double y = ImLerp(gp.CurrentPlot->YAxis[YAxis].Range.Min, gp.CurrentPlot->YAxis[YAxis].Range.Max, (float)t); + return ImVec2( (float)(gp.PixelRange[YAxis].Min.x + gp.Mx * (plt.x - gp.CurrentPlot->XAxis.Range.Min)), + (float)(gp.PixelRange[YAxis].Min.y + gp.My[YAxis] * (y - gp.CurrentPlot->YAxis[YAxis].Range.Min)) ); + } + const int YAxis; +}; + +// Transforms points for log x and log y space +struct TransformerLogLog { + TransformerLogLog() : YAxis(GetCurrentYAxis()) {} + inline ImVec2 operator()(const ImPlotPoint& plt) const { + ImPlotContext& gp = *GImPlot; + double t = ImLog10(plt.x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX; + double x = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, (float)t); + t = ImLog10(plt.y / gp.CurrentPlot->YAxis[YAxis].Range.Min) / gp.LogDenY[YAxis]; + double y = ImLerp(gp.CurrentPlot->YAxis[YAxis].Range.Min, gp.CurrentPlot->YAxis[YAxis].Range.Max, (float)t); + return ImVec2( (float)(gp.PixelRange[YAxis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min)), + (float)(gp.PixelRange[YAxis].Min.y + gp.My[YAxis] * (y - gp.CurrentPlot->YAxis[YAxis].Range.Min)) ); + } + const int YAxis; +}; + +//----------------------------------------------------------------------------- +// PRIMITIVE RENDERERS +//----------------------------------------------------------------------------- + +inline void AddLine(const ImVec2& P1, const ImVec2& P2, float weight, ImU32 col, ImDrawList& DrawList, ImVec2 uv) { + float dx = P2.x - P1.x; + float dy = P2.y - P1.y; + IMPLOT_NORMALIZE2F_OVER_ZERO(dx, dy); + dx *= (weight * 0.5f); + dy *= (weight * 0.5f); + DrawList._VtxWritePtr[0].pos.x = P1.x + dy; + DrawList._VtxWritePtr[0].pos.y = P1.y - dx; + DrawList._VtxWritePtr[0].uv = uv; + DrawList._VtxWritePtr[0].col = col; + DrawList._VtxWritePtr[1].pos.x = P2.x + dy; + DrawList._VtxWritePtr[1].pos.y = P2.y - dx; + DrawList._VtxWritePtr[1].uv = uv; + DrawList._VtxWritePtr[1].col = col; + DrawList._VtxWritePtr[2].pos.x = P2.x - dy; + DrawList._VtxWritePtr[2].pos.y = P2.y + dx; + DrawList._VtxWritePtr[2].uv = uv; + DrawList._VtxWritePtr[2].col = col; + DrawList._VtxWritePtr[3].pos.x = P1.x - dy; + DrawList._VtxWritePtr[3].pos.y = P1.y + dx; + DrawList._VtxWritePtr[3].uv = uv; + DrawList._VtxWritePtr[3].col = col; + DrawList._VtxWritePtr += 4; + DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2); + DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2); + DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3); + DrawList._IdxWritePtr += 6; + DrawList._VtxCurrentIdx += 4; +} + +inline void AddRectFilled(const ImVec2& Pmin, const ImVec2& Pmax, ImU32 col, ImDrawList& DrawList, ImVec2 uv) { + DrawList._VtxWritePtr[0].pos = Pmin; + DrawList._VtxWritePtr[0].uv = uv; + DrawList._VtxWritePtr[0].col = col; + DrawList._VtxWritePtr[1].pos = Pmax; + DrawList._VtxWritePtr[1].uv = uv; + DrawList._VtxWritePtr[1].col = col; + DrawList._VtxWritePtr[2].pos.x = Pmin.x; + DrawList._VtxWritePtr[2].pos.y = Pmax.y; + DrawList._VtxWritePtr[2].uv = uv; + DrawList._VtxWritePtr[2].col = col; + DrawList._VtxWritePtr[3].pos.x = Pmax.x; + DrawList._VtxWritePtr[3].pos.y = Pmin.y; + DrawList._VtxWritePtr[3].uv = uv; + DrawList._VtxWritePtr[3].col = col; + DrawList._VtxWritePtr += 4; + DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2); + DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3); + DrawList._IdxWritePtr += 6; + DrawList._VtxCurrentIdx += 4; +} + +template +struct LineStripRenderer { + inline LineStripRenderer(const TGetter& getter, const TTransformer& transformer, ImU32 col, float weight) : + Getter(getter), + Transformer(transformer), + Prims(Getter.Count - 1), + Col(col), + Weight(weight) + { + P1 = Transformer(Getter(0)); + } + inline bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const { + ImVec2 P2 = Transformer(Getter(prim + 1)); + if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) { + P1 = P2; + return false; + } + AddLine(P1,P2,Weight,Col,DrawList,uv); + P1 = P2; + return true; + } + const TGetter& Getter; + const TTransformer& Transformer; + const int Prims; + const ImU32 Col; + const float Weight; + mutable ImVec2 P1; + static const int IdxConsumed = 6; + static const int VtxConsumed = 4; +}; + +template +struct StairsRenderer { + inline StairsRenderer(const TGetter& getter, const TTransformer& transformer, ImU32 col, float weight) : + Getter(getter), + Transformer(transformer), + Prims(Getter.Count - 1), + Col(col), + HalfWeight(weight * 0.5f) + { + P1 = Transformer(Getter(0)); + } + inline bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const { + ImVec2 P2 = Transformer(Getter(prim + 1)); + if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) { + P1 = P2; + return false; + } + AddRectFilled(ImVec2(P1.x, P1.y + HalfWeight), ImVec2(P2.x, P1.y - HalfWeight), Col, DrawList, uv); + AddRectFilled(ImVec2(P2.x - HalfWeight, P2.y), ImVec2(P2.x + HalfWeight, P1.y), Col, DrawList, uv); + + // AddLine(P1, P12, Weight, Col, DrawList, uv); + // AddLine(P12, P2, Weight, Col, DrawList, uv); + P1 = P2; + return true; + } + const TGetter& Getter; + const TTransformer& Transformer; + const int Prims; + const ImU32 Col; + const float HalfWeight; + mutable ImVec2 P1; + static const int IdxConsumed = 12; + static const int VtxConsumed = 8; +}; + +template +struct LineSegmentsRenderer { + inline LineSegmentsRenderer(const TGetter1& getter1, const TGetter2& getter2, const TTransformer& transformer, ImU32 col, float weight) : + Getter1(getter1), + Getter2(getter2), + Transformer(transformer), + Prims(ImMin(Getter1.Count, Getter2.Count)), + Col(col), + Weight(weight) + {} + inline bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const { + ImVec2 P1 = Transformer(Getter1(prim)); + ImVec2 P2 = Transformer(Getter2(prim)); + if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) + return false; + AddLine(P1,P2,Weight,Col,DrawList,uv); + return true; + } + const TGetter1& Getter1; + const TGetter2& Getter2; + const TTransformer& Transformer; + const int Prims; + const ImU32 Col; + const float Weight; + static const int IdxConsumed = 6; + static const int VtxConsumed = 4; +}; + +template +struct ShadedRenderer { + ShadedRenderer(const TGetter1& getter1, const TGetter2& getter2, const TTransformer& transformer, ImU32 col) : + Getter1(getter1), + Getter2(getter2), + Transformer(transformer), + Prims(ImMin(Getter1.Count, Getter2.Count) - 1), + Col(col) + { + P11 = Transformer(Getter1(0)); + P12 = Transformer(Getter2(0)); + } + + inline bool operator()(ImDrawList& DrawList, const ImRect& /*cull_rect*/, const ImVec2& uv, int prim) const { + // TODO: Culling + ImVec2 P21 = Transformer(Getter1(prim+1)); + ImVec2 P22 = Transformer(Getter2(prim+1)); + const int intersect = (P11.y > P12.y && P22.y > P21.y) || (P12.y > P11.y && P21.y > P22.y); + ImVec2 intersection = Intersection(P11,P21,P12,P22); + DrawList._VtxWritePtr[0].pos = P11; + DrawList._VtxWritePtr[0].uv = uv; + DrawList._VtxWritePtr[0].col = Col; + DrawList._VtxWritePtr[1].pos = P21; + DrawList._VtxWritePtr[1].uv = uv; + DrawList._VtxWritePtr[1].col = Col; + DrawList._VtxWritePtr[2].pos = intersection; + DrawList._VtxWritePtr[2].uv = uv; + DrawList._VtxWritePtr[2].col = Col; + DrawList._VtxWritePtr[3].pos = P12; + DrawList._VtxWritePtr[3].uv = uv; + DrawList._VtxWritePtr[3].col = Col; + DrawList._VtxWritePtr[4].pos = P22; + DrawList._VtxWritePtr[4].uv = uv; + DrawList._VtxWritePtr[4].col = Col; + DrawList._VtxWritePtr += 5; + DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1 + intersect); + DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3); + DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3 - intersect); + DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 4); + DrawList._IdxWritePtr += 6; + DrawList._VtxCurrentIdx += 5; + P11 = P21; + P12 = P22; + return true; + } + const TGetter1& Getter1; + const TGetter2& Getter2; + const TTransformer& Transformer; + const int Prims; + const ImU32 Col; + mutable ImVec2 P11; + mutable ImVec2 P12; + static const int IdxConsumed = 6; + static const int VtxConsumed = 5; +}; + +// Stupid way of calculating maximum index size of ImDrawIdx without integer overflow issues +template +struct MaxIdx { static const unsigned int Value; }; +template <> const unsigned int MaxIdx::Value = 65535; +template <> const unsigned int MaxIdx::Value = 4294967295; + +/// Renders primitive shapes in bulk as efficiently as possible. +template +inline void RenderPrimitives(const Renderer& renderer, ImDrawList& DrawList, const ImRect& cull_rect) { + unsigned int prims = renderer.Prims; + unsigned int prims_culled = 0; + unsigned int idx = 0; + const ImVec2 uv = DrawList._Data->TexUvWhitePixel; + while (prims) { + // find how many can be reserved up to end of current draw command's limit + unsigned int cnt = ImMin(prims, (MaxIdx::Value - DrawList._VtxCurrentIdx) / Renderer::VtxConsumed); + // make sure at least this many elements can be rendered to avoid situations where at the end of buffer this slow path is not taken all the time + if (cnt >= ImMin(64u, prims)) { + if (prims_culled >= cnt) + prims_culled -= cnt; // reuse previous reservation + else { + DrawList.PrimReserve((cnt - prims_culled) * Renderer::IdxConsumed, (cnt - prims_culled) * Renderer::VtxConsumed); // add more elements to previous reservation + prims_culled = 0; + } + } + else + { + if (prims_culled > 0) { + DrawList.PrimUnreserve(prims_culled * Renderer::IdxConsumed, prims_culled * Renderer::VtxConsumed); + prims_culled = 0; + } + cnt = ImMin(prims, (MaxIdx::Value - 0/*DrawList._VtxCurrentIdx*/) / Renderer::VtxConsumed); + DrawList.PrimReserve(cnt * Renderer::IdxConsumed, cnt * Renderer::VtxConsumed); // reserve new draw command + } + prims -= cnt; + for (unsigned int ie = idx + cnt; idx != ie; ++idx) { + if (!renderer(DrawList, cull_rect, uv, idx)) + prims_culled++; + } + } + if (prims_culled > 0) + DrawList.PrimUnreserve(prims_culled * Renderer::IdxConsumed, prims_culled * Renderer::VtxConsumed); +} + +template +inline void RenderLineStrip(const Getter& getter, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) { + ImPlotContext& gp = *GImPlot; + if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) { + ImVec2 p1 = transformer(getter(0)); + for (int i = 1; i < getter.Count; ++i) { + ImVec2 p2 = transformer(getter(i)); + if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2)))) + DrawList.AddLine(p1, p2, col, line_weight); + p1 = p2; + } + } + else { + RenderPrimitives(LineStripRenderer(getter, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect); + } +} + +template +inline void RenderLineSegments(const Getter1& getter1, const Getter2& getter2, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) { + ImPlotContext& gp = *GImPlot; + if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) { + int I = ImMin(getter1.Count, getter2.Count); + for (int i = 0; i < I; ++i) { + ImVec2 p1 = transformer(getter1(i)); + ImVec2 p2 = transformer(getter2(i)); + if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2)))) + DrawList.AddLine(p1, p2, col, line_weight); + } + } + else { + RenderPrimitives(LineSegmentsRenderer(getter1, getter2, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect); + } +} + +template +inline void RenderStairs(const Getter& getter, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) { + ImPlotContext& gp = *GImPlot; + if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) { + ImVec2 p1 = transformer(getter(0)); + for (int i = 1; i < getter.Count; ++i) { + ImVec2 p2 = transformer(getter(i)); + if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2)))) { + ImVec2 p12(p2.x, p1.y); + DrawList.AddLine(p1, p12, col, line_weight); + DrawList.AddLine(p12, p2, col, line_weight); + } + p1 = p2; + } + } + else { + RenderPrimitives(StairsRenderer(getter, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect); + } +} + +//----------------------------------------------------------------------------- +// MARKER RENDERERS +//----------------------------------------------------------------------------- + +inline void TransformMarker(ImVec2* points, int n, const ImVec2& c, float s) { + for (int i = 0; i < n; ++i) { + points[i].x = c.x + points[i].x * s; + points[i].y = c.y + points[i].y * s; + } +} + +inline void RenderMarkerGeneral(ImDrawList& DrawList, ImVec2* points, int n, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + TransformMarker(points, n, c, s); + if (fill) + DrawList.AddConvexPolyFilled(points, n, col_fill); + if (outline && !(fill && col_outline == col_fill)) { + for (int i = 0; i < n; ++i) + DrawList.AddLine(points[i], points[(i+1)%n], col_outline, weight); + } +} + +inline void RenderMarkerCircle(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[10] = {ImVec2(1.0f, 0.0f), + ImVec2(0.809017f, 0.58778524f), + ImVec2(0.30901697f, 0.95105654f), + ImVec2(-0.30901703f, 0.9510565f), + ImVec2(-0.80901706f, 0.5877852f), + ImVec2(-1.0f, 0.0f), + ImVec2(-0.80901694f, -0.58778536f), + ImVec2(-0.3090171f, -0.9510565f), + ImVec2(0.30901712f, -0.9510565f), + ImVec2(0.80901694f, -0.5877853f)}; + RenderMarkerGeneral(DrawList, marker, 10, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerDiamond(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[4] = {ImVec2(1, 0), ImVec2(0, -1), ImVec2(-1, 0), ImVec2(0, 1)}; + RenderMarkerGeneral(DrawList, marker, 4, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerSquare(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[4] = {ImVec2(SQRT_1_2,SQRT_1_2),ImVec2(SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,SQRT_1_2)}; + RenderMarkerGeneral(DrawList, marker, 4, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerUp(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[3] = {ImVec2(SQRT_3_2,0.5f),ImVec2(0,-1),ImVec2(-SQRT_3_2,0.5f)}; + RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerDown(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[3] = {ImVec2(SQRT_3_2,-0.5f),ImVec2(0,1),ImVec2(-SQRT_3_2,-0.5f)}; + RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerLeft(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[3] = {ImVec2(-1,0), ImVec2(0.5, SQRT_3_2), ImVec2(0.5, -SQRT_3_2)}; + RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerRight(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) { + ImVec2 marker[3] = {ImVec2(1,0), ImVec2(-0.5, SQRT_3_2), ImVec2(-0.5, -SQRT_3_2)}; + RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight); +} + +inline void RenderMarkerAsterisk(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) { + ImVec2 marker[6] = {ImVec2(SQRT_3_2, 0.5f), ImVec2(0, -1), ImVec2(-SQRT_3_2, 0.5f), ImVec2(SQRT_3_2, -0.5f), ImVec2(0, 1), ImVec2(-SQRT_3_2, -0.5f)}; + TransformMarker(marker, 6, c, s); + DrawList.AddLine(marker[0], marker[5], col_outline, weight); + DrawList.AddLine(marker[1], marker[4], col_outline, weight); + DrawList.AddLine(marker[2], marker[3], col_outline, weight); +} + +inline void RenderMarkerPlus(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) { + ImVec2 marker[4] = {ImVec2(1, 0), ImVec2(0, -1), ImVec2(-1, 0), ImVec2(0, 1)}; + TransformMarker(marker, 4, c, s); + DrawList.AddLine(marker[0], marker[2], col_outline, weight); + DrawList.AddLine(marker[1], marker[3], col_outline, weight); +} + +inline void RenderMarkerCross(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) { + ImVec2 marker[4] = {ImVec2(SQRT_1_2,SQRT_1_2),ImVec2(SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,SQRT_1_2)}; + TransformMarker(marker, 4, c, s); + DrawList.AddLine(marker[0], marker[2], col_outline, weight); + DrawList.AddLine(marker[1], marker[3], col_outline, weight); +} + +template +inline void RenderMarkers(Getter getter, Transformer transformer, ImDrawList& DrawList, ImPlotMarker marker, float size, bool rend_mk_line, ImU32 col_mk_line, float weight, bool rend_mk_fill, ImU32 col_mk_fill) { + static void (*marker_table[ImPlotMarker_COUNT])(ImDrawList&, const ImVec2&, float s, bool, ImU32, bool, ImU32, float) = { + RenderMarkerCircle, + RenderMarkerSquare, + RenderMarkerDiamond , + RenderMarkerUp , + RenderMarkerDown , + RenderMarkerLeft, + RenderMarkerRight, + RenderMarkerCross, + RenderMarkerPlus, + RenderMarkerAsterisk + }; + ImPlotContext& gp = *GImPlot; + for (int i = 0; i < getter.Count; ++i) { + ImVec2 c = transformer(getter(i)); + if (gp.CurrentPlot->PlotRect.Contains(c)) + marker_table[marker](DrawList, c, size, rend_mk_line, col_mk_line, rend_mk_fill, col_mk_fill, weight); + } +} + +//----------------------------------------------------------------------------- +// PLOT LINE +//----------------------------------------------------------------------------- + +template +inline void PlotLineEx(const char* label_id, const Getter& getter) { + if (BeginItem(label_id, ImPlotCol_Line)) { + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + FitPoint(p); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + if (getter.Count > 1 && s.RenderLine) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderLineStrip(getter, TransformerLinLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLin: RenderLineStrip(getter, TransformerLogLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LinLog: RenderLineStrip(getter, TransformerLinLog(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLog: RenderLineStrip(getter, TransformerLogLog(), DrawList, s.LineWeight, col_line); break; + } + } + // render markers + if (s.Marker != ImPlotMarker_None) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]); + const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + } + } + EndItem(); + } +} + +template +void PlotLine(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) { + GetterYs getter(values,count,xscale,x0,offset,stride); + PlotLineEx(label_id, getter); +} + +template IMPLOT_API void PlotLine (const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine (const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride); + +template +void PlotLine(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + return PlotLineEx(label_id, getter); +} + +template IMPLOT_API void PlotLine(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride); +template IMPLOT_API void PlotLine(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride); + +// custom +void PlotLineG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, int offset) { + GetterFuncPtr getter(getter_func,data, count, offset); + return PlotLineEx(label_id, getter); +} + +//----------------------------------------------------------------------------- +// PLOT SCATTER +//----------------------------------------------------------------------------- + +template +inline void PlotScatterEx(const char* label_id, const Getter& getter) { + if (BeginItem(label_id, ImPlotCol_MarkerOutline)) { + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + FitPoint(p); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + // render markers + ImPlotMarker marker = s.Marker == ImPlotMarker_None ? ImPlotMarker_Circle : s.Marker; + if (marker != ImPlotMarker_None) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]); + const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + } + } + EndItem(); + } +} + +template +void PlotScatter(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) { + GetterYs getter(values,count,xscale,x0,offset,stride); + PlotScatterEx(label_id, getter); +} + +template IMPLOT_API void PlotScatter(const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride); + +template +void PlotScatter(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + return PlotScatterEx(label_id, getter); +} + +template IMPLOT_API void PlotScatter(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride); +template IMPLOT_API void PlotScatter(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride); + +// custom +void PlotScatterG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, int offset) { + GetterFuncPtr getter(getter_func,data, count, offset); + return PlotScatterEx(label_id, getter); +} + +//----------------------------------------------------------------------------- +// PLOT STAIRS +//----------------------------------------------------------------------------- + +template +inline void PlotStairsEx(const char* label_id, const Getter& getter) { + if (BeginItem(label_id, ImPlotCol_Line)) { + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + FitPoint(p); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + if (getter.Count > 1 && s.RenderLine) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderStairs(getter, TransformerLinLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLin: RenderStairs(getter, TransformerLogLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LinLog: RenderStairs(getter, TransformerLinLog(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLog: RenderStairs(getter, TransformerLogLog(), DrawList, s.LineWeight, col_line); break; + } + } + // render markers + if (s.Marker != ImPlotMarker_None) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]); + const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + } + } + EndItem(); + } +} + +template +void PlotStairs(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) { + GetterYs getter(values,count,xscale,x0,offset,stride); + PlotStairsEx(label_id, getter); +} + +template IMPLOT_API void PlotStairs (const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs (const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride); + +template +void PlotStairs(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + return PlotStairsEx(label_id, getter); +} + +template IMPLOT_API void PlotStairs(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride); +template IMPLOT_API void PlotStairs(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride); + +// custom +void PlotStairsG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, int offset) { + GetterFuncPtr getter(getter_func,data, count, offset); + return PlotStairsEx(label_id, getter); +} + +//----------------------------------------------------------------------------- +// PLOT SHADED +//----------------------------------------------------------------------------- + +template +inline void PlotShadedEx(const char* label_id, const Getter1& getter1, const Getter2& getter2, bool fit2) { + if (BeginItem(label_id, ImPlotCol_Fill)) { + if (FitThisFrame()) { + for (int i = 0; i < getter1.Count; ++i) + FitPoint(getter1(i)); + if (fit2) { + for (int i = 0; i < getter2.Count; ++i) + FitPoint(getter2(i)); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList & DrawList = *GetPlotDrawList(); + if (s.RenderFill) { + ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderPrimitives(ShadedRenderer(getter1,getter2,TransformerLinLin(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break; + case ImPlotScale_LogLin: RenderPrimitives(ShadedRenderer(getter1,getter2,TransformerLogLin(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break; + case ImPlotScale_LinLog: RenderPrimitives(ShadedRenderer(getter1,getter2,TransformerLinLog(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break; + case ImPlotScale_LogLog: RenderPrimitives(ShadedRenderer(getter1,getter2,TransformerLogLog(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break; + } + } + EndItem(); + } +} + +template +void PlotShaded(const char* label_id, const T* values, int count, double y_ref, double xscale, double x0, int offset, int stride) { + bool fit2 = true; + if (y_ref == -HUGE_VAL) { + fit2 = false; + y_ref = GetPlotLimits().Y.Min; + } + if (y_ref == HUGE_VAL) { + fit2 = false; + y_ref = GetPlotLimits().Y.Max; + } + GetterYs getter1(values,count,xscale,x0,offset,stride); + GetterYRef getter2(y_ref,count,xscale,x0); + PlotShadedEx(label_id, getter1, getter2, fit2); +} + +template IMPLOT_API void PlotShaded(const char* label_id, const ImS8* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU8* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS16* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU16* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS32* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU32* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS64* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU64* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const float* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const double* values, int count, double y_ref, double xscale, double x0, int offset, int stride); + +template +void PlotShaded(const char* label_id, const T* xs, const T* ys, int count, double y_ref, int offset, int stride) { + bool fit2 = true; + if (y_ref == -HUGE_VAL) { + fit2 = false; + y_ref = GetPlotLimits().Y.Min; + } + if (y_ref == HUGE_VAL) { + fit2 = false; + y_ref = GetPlotLimits().Y.Max; + } + GetterXsYs getter1(xs, ys, count, offset, stride); + GetterXsYRef getter2(xs, y_ref, count, offset, stride); + PlotShadedEx(label_id, getter1, getter2, fit2); +} + +template IMPLOT_API void PlotShaded(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const float* xs, const float* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const double* xs, const double* ys, int count, double y_ref, int offset, int stride); + +template +void PlotShaded(const char* label_id, const T* xs, const T* ys1, const T* ys2, int count, int offset, int stride) { + GetterXsYs getter1(xs, ys1, count, offset, stride); + GetterXsYs getter2(xs, ys2, count, offset, stride); + PlotShadedEx(label_id, getter1, getter2, true); +} + +template IMPLOT_API void PlotShaded(const char* label_id, const ImS8* xs, const ImS8* ys1, const ImS8* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU8* xs, const ImU8* ys1, const ImU8* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS16* xs, const ImS16* ys1, const ImS16* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU16* xs, const ImU16* ys1, const ImU16* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS32* xs, const ImS32* ys1, const ImS32* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU32* xs, const ImU32* ys1, const ImU32* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImS64* xs, const ImS64* ys1, const ImS64* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const ImU64* xs, const ImU64* ys1, const ImU64* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const float* xs, const float* ys1, const float* ys2, int count, int offset, int stride); +template IMPLOT_API void PlotShaded(const char* label_id, const double* xs, const double* ys1, const double* ys2, int count, int offset, int stride); + +// custom +void PlotShadedG(const char* label_id, ImPlotPoint (*g1)(void* data, int idx), void* data1, ImPlotPoint (*g2)(void* data, int idx), void* data2, int count, int offset) { + GetterFuncPtr getter1(g1, data1, count, offset); + GetterFuncPtr getter2(g2, data2, count, offset); + PlotShadedEx(label_id, getter1, getter2, true); +} + +//----------------------------------------------------------------------------- +// PLOT BAR +//----------------------------------------------------------------------------- + +// TODO: Migrate to RenderPrimitives + +template +void PlotBarsEx(const char* label_id, const Getter& getter, double width) { + if (BeginItem(label_id, ImPlotCol_Fill)) { + const double half_width = width / 2; + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + FitPoint(ImPlotPoint(p.x - half_width, p.y)); + FitPoint(ImPlotPoint(p.x + half_width, 0)); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]); + bool rend_line = s.RenderLine; + if (s.RenderFill && col_line == col_fill) + rend_line = false; + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + if (p.y == 0) + continue; + ImVec2 a = PlotToPixels(p.x - half_width, p.y); + ImVec2 b = PlotToPixels(p.x + half_width, 0); + if (s.RenderFill) + DrawList.AddRectFilled(a, b, col_fill); + if (rend_line) + DrawList.AddRect(a, b, col_line, 0, ImDrawFlags_RoundCornersAll, s.LineWeight); + } + EndItem(); + } +} + +template +void PlotBars(const char* label_id, const T* values, int count, double width, double shift, int offset, int stride) { + GetterBarV getter(values,shift,count,offset,stride); + PlotBarsEx(label_id, getter, width); +} + +template IMPLOT_API void PlotBars(const char* label_id, const ImS8* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU8* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS16* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU16* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS32* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU32* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS64* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU64* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const float* values, int count, double width, double shift, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const double* values, int count, double width, double shift, int offset, int stride); + +template +void PlotBars(const char* label_id, const T* xs, const T* ys, int count, double width, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + PlotBarsEx(label_id, getter, width); +} + +template IMPLOT_API void PlotBars(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const float* xs, const float* ys, int count, double width, int offset, int stride); +template IMPLOT_API void PlotBars(const char* label_id, const double* xs, const double* ys, int count, double width, int offset, int stride); + +// custom +void PlotBarsG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, double width, int offset) { + GetterFuncPtr getter(getter_func, data, count, offset); + PlotBarsEx(label_id, getter, width); +} + +//----------------------------------------------------------------------------- +// PLOT BAR H +//----------------------------------------------------------------------------- + +// TODO: Migrate to RenderPrimitives + +template +void PlotBarsHEx(const char* label_id, const Getter& getter, THeight height) { + if (BeginItem(label_id, ImPlotCol_Fill)) { + const THeight half_height = height / 2; + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + FitPoint(ImPlotPoint(0, p.y - half_height)); + FitPoint(ImPlotPoint(p.x, p.y + half_height)); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]); + bool rend_line = s.RenderLine; + if (s.RenderFill && col_line == col_fill) + rend_line = false; + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint p = getter(i); + if (p.x == 0) + continue; + ImVec2 a = PlotToPixels(0, p.y - half_height); + ImVec2 b = PlotToPixels(p.x, p.y + half_height); + if (s.RenderFill) + DrawList.AddRectFilled(a, b, col_fill); + if (rend_line) + DrawList.AddRect(a, b, col_line, 0, ImDrawFlags_RoundCornersAll, s.LineWeight); + } + EndItem(); + } +} + +template +void PlotBarsH(const char* label_id, const T* values, int count, double height, double shift, int offset, int stride) { + GetterBarH getter(values,shift,count,offset,stride); + PlotBarsHEx(label_id, getter, height); +} + +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS8* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU8* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS16* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU16* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS32* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU32* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS64* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU64* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const float* values, int count, double height, double shift, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const double* values, int count, double height, double shift, int offset, int stride); + +template +void PlotBarsH(const char* label_id, const T* xs, const T* ys, int count, double height, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + PlotBarsHEx(label_id, getter, height); +} + +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const float* xs, const float* ys, int count, double height, int offset, int stride); +template IMPLOT_API void PlotBarsH(const char* label_id, const double* xs, const double* ys, int count, double height, int offset, int stride); + +// custom +void PlotBarsHG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, double height, int offset) { + GetterFuncPtr getter(getter_func, data, count, offset); + PlotBarsHEx(label_id, getter, height); +} + +//----------------------------------------------------------------------------- +// PLOT ERROR BARS +//----------------------------------------------------------------------------- + +template +void PlotErrorBarsEx(const char* label_id, const Getter& getter) { + if (BeginItem(label_id)) { + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPointError e = getter(i); + FitPoint(ImPlotPoint(e.X , e.Y - e.Neg)); + FitPoint(ImPlotPoint(e.X , e.Y + e.Pos )); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + const ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_ErrorBar]); + const bool rend_whisker = s.ErrorBarSize > 0; + const float half_whisker = s.ErrorBarSize * 0.5f; + for (int i = 0; i < getter.Count; ++i) { + ImPlotPointError e = getter(i); + ImVec2 p1 = PlotToPixels(e.X, e.Y - e.Neg); + ImVec2 p2 = PlotToPixels(e.X, e.Y + e.Pos); + DrawList.AddLine(p1,p2,col, s.ErrorBarWeight); + if (rend_whisker) { + DrawList.AddLine(p1 - ImVec2(half_whisker, 0), p1 + ImVec2(half_whisker, 0), col, s.ErrorBarWeight); + DrawList.AddLine(p2 - ImVec2(half_whisker, 0), p2 + ImVec2(half_whisker, 0), col, s.ErrorBarWeight); + } + } + EndItem(); + } +} + +template +void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset, int stride) { + GetterError getter(xs, ys, err, err, count, offset, stride); + PlotErrorBarsEx(label_id, getter); +} + +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const float* xs, const float* ys, const float* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const double* xs, const double* ys, const double* err, int count, int offset, int stride); + +template +void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) { + GetterError getter(xs, ys, neg, pos, count, offset, stride); + PlotErrorBarsEx(label_id, getter); +} + +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* neg, const ImS8* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* neg, const ImU8* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* neg, const ImS16* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* neg, const ImU16* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* neg, const ImS32* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* neg, const ImU32* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* neg, const ImS64* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* neg, const ImU64* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const float* xs, const float* ys, const float* neg, const float* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBars(const char* label_id, const double* xs, const double* ys, const double* neg, const double* pos, int count, int offset, int stride); + +//----------------------------------------------------------------------------- +// PLOT ERROR BARS H +//----------------------------------------------------------------------------- + +template +void PlotErrorBarsHEx(const char* label_id, const Getter& getter) { + if (BeginItem(label_id)) { + if (FitThisFrame()) { + for (int i = 0; i < getter.Count; ++i) { + ImPlotPointError e = getter(i); + FitPoint(ImPlotPoint(e.X - e.Neg, e.Y)); + FitPoint(ImPlotPoint(e.X + e.Pos, e.Y)); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + const ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_ErrorBar]); + const bool rend_whisker = s.ErrorBarSize > 0; + const float half_whisker = s.ErrorBarSize * 0.5f; + for (int i = 0; i < getter.Count; ++i) { + ImPlotPointError e = getter(i); + ImVec2 p1 = PlotToPixels(e.X - e.Neg, e.Y); + ImVec2 p2 = PlotToPixels(e.X + e.Pos, e.Y); + DrawList.AddLine(p1, p2, col, s.ErrorBarWeight); + if (rend_whisker) { + DrawList.AddLine(p1 - ImVec2(0, half_whisker), p1 + ImVec2(0, half_whisker), col, s.ErrorBarWeight); + DrawList.AddLine(p2 - ImVec2(0, half_whisker), p2 + ImVec2(0, half_whisker), col, s.ErrorBarWeight); + } + } + EndItem(); + } +} + +template +void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset, int stride) { + GetterError getter(xs, ys, err, err, count, offset, stride); + PlotErrorBarsHEx(label_id, getter); +} + +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const float* xs, const float* ys, const float* err, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const double* xs, const double* ys, const double* err, int count, int offset, int stride); + +template +void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) { + GetterError getter(xs, ys, neg, pos, count, offset, stride); + PlotErrorBarsHEx(label_id, getter); +} + +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* neg, const ImS8* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* neg, const ImU8* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* neg, const ImS16* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* neg, const ImU16* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* neg, const ImS32* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* neg, const ImU32* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* neg, const ImS64* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* neg, const ImU64* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const float* xs, const float* ys, const float* neg, const float* pos, int count, int offset, int stride); +template IMPLOT_API void PlotErrorBarsH(const char* label_id, const double* xs, const double* ys, const double* neg, const double* pos, int count, int offset, int stride); + +//----------------------------------------------------------------------------- +// PLOT STEMS +//----------------------------------------------------------------------------- + +template +inline void PlotStemsEx(const char* label_id, const GetterM& get_mark, const GetterB& get_base) { + if (BeginItem(label_id, ImPlotCol_Line)) { + if (FitThisFrame()) { + for (int i = 0; i < get_base.Count; ++i) { + FitPoint(get_mark(i)); + FitPoint(get_base(i)); + } + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + // render stems + if (s.RenderLine) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderLineSegments(get_mark, get_base, TransformerLinLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLin: RenderLineSegments(get_mark, get_base, TransformerLogLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LinLog: RenderLineSegments(get_mark, get_base, TransformerLinLog(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLog: RenderLineSegments(get_mark, get_base, TransformerLogLog(), DrawList, s.LineWeight, col_line); break; + } + } + // render markers + ImPlotMarker marker = s.Marker == ImPlotMarker_None ? ImPlotMarker_Circle : s.Marker; + if (marker != ImPlotMarker_None) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]); + const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderMarkers(get_mark, TransformerLinLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLin: RenderMarkers(get_mark, TransformerLogLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LinLog: RenderMarkers(get_mark, TransformerLinLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + case ImPlotScale_LogLog: RenderMarkers(get_mark, TransformerLogLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break; + } + } + EndItem(); + } +} + +template +void PlotStems(const char* label_id, const T* values, int count, double y_ref, double xscale, double x0, int offset, int stride) { + GetterYs get_mark(values,count,xscale,x0,offset,stride); + GetterYRef get_base(y_ref,count,xscale,x0); + PlotStemsEx(label_id, get_mark, get_base); +} + +template IMPLOT_API void PlotStems(const char* label_id, const ImS8* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU8* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS16* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU16* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS32* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU32* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS64* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU64* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const float* values, int count, double y_ref, double xscale, double x0, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const double* values, int count, double y_ref, double xscale, double x0, int offset, int stride); + +template +void PlotStems(const char* label_id, const T* xs, const T* ys, int count, double y_ref, int offset, int stride) { + GetterXsYs get_mark(xs,ys,count,offset,stride); + GetterXsYRef get_base(xs,y_ref,count,offset,stride); + PlotStemsEx(label_id, get_mark, get_base); +} + +template IMPLOT_API void PlotStems(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const float* xs, const float* ys, int count, double y_ref, int offset, int stride); +template IMPLOT_API void PlotStems(const char* label_id, const double* xs, const double* ys, int count, double y_ref, int offset, int stride); + +//----------------------------------------------------------------------------- +// INFINITE LINES +//----------------------------------------------------------------------------- + +template +void PlotVLines(const char* label_id, const T* xs, int count, int offset, int stride) { + if (BeginItem(label_id, ImPlotCol_Line)) { + const ImPlotLimits lims = GetPlotLimits(); + GetterXsYRef get_min(xs,lims.Y.Min,count,offset,stride); + GetterXsYRef get_max(xs,lims.Y.Max,count,offset,stride); + if (FitThisFrame()) { + for (int i = 0; i < get_min.Count; ++i) + FitPointX(get_min(i).x); + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + // render stems + if (s.RenderLine) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderLineSegments(get_min, get_max, TransformerLinLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLin: RenderLineSegments(get_min, get_max, TransformerLogLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LinLog: RenderLineSegments(get_min, get_max, TransformerLinLog(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLog: RenderLineSegments(get_min, get_max, TransformerLogLog(), DrawList, s.LineWeight, col_line); break; + } + } + EndItem(); + } +} + +template IMPLOT_API void PlotVLines(const char* label_id, const ImS8* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImU8* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImS16* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImU16* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImS32* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImU32* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImS64* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const ImU64* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const float* xs, int count, int offset, int stride); +template IMPLOT_API void PlotVLines(const char* label_id, const double* xs, int count, int offset, int stride); + + +template +void PlotHLines(const char* label_id, const T* ys, int count, int offset, int stride) { + if (BeginItem(label_id, ImPlotCol_Line)) { + const ImPlotLimits lims = GetPlotLimits(); + GetterXRefYs get_min(lims.X.Min,ys,count,offset,stride); + GetterXRefYs get_max(lims.X.Max,ys,count,offset,stride); + if (FitThisFrame()) { + for (int i = 0; i < get_min.Count; ++i) + FitPointY(get_min(i).y); + } + const ImPlotNextItemData& s = GetItemData(); + ImDrawList& DrawList = *GetPlotDrawList(); + // render stems + if (s.RenderLine) { + const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderLineSegments(get_min, get_max, TransformerLinLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLin: RenderLineSegments(get_min, get_max, TransformerLogLin(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LinLog: RenderLineSegments(get_min, get_max, TransformerLinLog(), DrawList, s.LineWeight, col_line); break; + case ImPlotScale_LogLog: RenderLineSegments(get_min, get_max, TransformerLogLog(), DrawList, s.LineWeight, col_line); break; + } + } + EndItem(); + } +} + +template IMPLOT_API void PlotHLines(const char* label_id, const ImS8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImU8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImS16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImU16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImS32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImU32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImS64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const ImU64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const float* ys, int count, int offset, int stride); +template IMPLOT_API void PlotHLines(const char* label_id, const double* ys, int count, int offset, int stride); + +//----------------------------------------------------------------------------- +// PLOT PIE CHART +//----------------------------------------------------------------------------- + +inline void RenderPieSlice(ImDrawList& DrawList, const ImPlotPoint& center, double radius, double a0, double a1, ImU32 col) { + static const float resolution = 50 / (2 * IM_PI); + static ImVec2 buffer[50]; + buffer[0] = PlotToPixels(center); + int n = ImMax(3, (int)((a1 - a0) * resolution)); + double da = (a1 - a0) / (n - 1); + for (int i = 0; i < n; ++i) { + double a = a0 + i * da; + buffer[i + 1] = PlotToPixels(center.x + radius * cos(a), center.y + radius * sin(a)); + } + DrawList.AddConvexPolyFilled(buffer, n + 1, col); +} + +template +void PlotPieChart(const char* const label_ids[], const T* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0) { + IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, "PlotPieChart() needs to be called between BeginPlot() and EndPlot()!"); + ImDrawList & DrawList = *GetPlotDrawList(); + double sum = 0; + for (int i = 0; i < count; ++i) + sum += (double)values[i]; + normalize = normalize || sum > 1.0; + ImPlotPoint center(x,y); + PushPlotClipRect(); + double a0 = angle0 * 2 * IM_PI / 360.0; + double a1 = angle0 * 2 * IM_PI / 360.0; + for (int i = 0; i < count; ++i) { + double percent = normalize ? (double)values[i] / sum : (double)values[i]; + a1 = a0 + 2 * IM_PI * percent; + if (BeginItem(label_ids[i])) { + ImU32 col = GetCurrentItem()->Color; + if (percent < 0.5) { + RenderPieSlice(DrawList, center, radius, a0, a1, col); + } + else { + RenderPieSlice(DrawList, center, radius, a0, a0 + (a1 - a0) * 0.5, col); + RenderPieSlice(DrawList, center, radius, a0 + (a1 - a0) * 0.5, a1, col); + } + EndItem(); + } + a0 = a1; + } + if (fmt != NULL) { + a0 = angle0 * 2 * IM_PI / 360.0; + a1 = angle0 * 2 * IM_PI / 360.0; + char buffer[32]; + for (int i = 0; i < count; ++i) { + ImPlotItem* item = GetItem(label_ids[i]); + double percent = normalize ? (double)values[i] / sum : (double)values[i]; + a1 = a0 + 2 * IM_PI * percent; + if (item->Show) { + sprintf(buffer, fmt, (double)values[i]); + ImVec2 size = ImGui::CalcTextSize(buffer); + double angle = a0 + (a1 - a0) * 0.5; + ImVec2 pos = PlotToPixels(center.x + 0.5 * radius * cos(angle), center.y + 0.5 * radius * sin(angle)); + ImU32 col = CalcTextColor(ImGui::ColorConvertU32ToFloat4(item->Color)); + DrawList.AddText(pos - size * 0.5f, col, buffer); + } + a0 = a1; + } + } + PopPlotClipRect(); +} + +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImS8* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImU8* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImS16* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImU16* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImS32* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImU32* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImS64* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const ImU64* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const float* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); +template IMPLOT_API void PlotPieChart(const char* const label_ids[], const double* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0); + +//----------------------------------------------------------------------------- +// PLOT HEATMAP +//----------------------------------------------------------------------------- + +struct RectInfo { + ImPlotPoint Min, Max; + ImU32 Color; +}; + +template +struct RectRenderer { + inline RectRenderer(const TGetter& getter, const TTransformer& transformer) : + Getter(getter), + Transformer(transformer), + Prims(Getter.Count) + {} + inline bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const { + RectInfo rect = Getter(prim); + ImVec2 P1 = Transformer(rect.Min); + ImVec2 P2 = Transformer(rect.Max); + + if ((rect.Color & IM_COL32_A_MASK) == 0 || !cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) + return false; + + DrawList._VtxWritePtr[0].pos = P1; + DrawList._VtxWritePtr[0].uv = uv; + DrawList._VtxWritePtr[0].col = rect.Color; + DrawList._VtxWritePtr[1].pos.x = P1.x; + DrawList._VtxWritePtr[1].pos.y = P2.y; + DrawList._VtxWritePtr[1].uv = uv; + DrawList._VtxWritePtr[1].col = rect.Color; + DrawList._VtxWritePtr[2].pos = P2; + DrawList._VtxWritePtr[2].uv = uv; + DrawList._VtxWritePtr[2].col = rect.Color; + DrawList._VtxWritePtr[3].pos.x = P2.x; + DrawList._VtxWritePtr[3].pos.y = P1.y; + DrawList._VtxWritePtr[3].uv = uv; + DrawList._VtxWritePtr[3].col = rect.Color; + DrawList._VtxWritePtr += 4; + DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx); + DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3); + DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1); + DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2); + DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3); + DrawList._IdxWritePtr += 6; + DrawList._VtxCurrentIdx += 4; + return true; + } + const TGetter& Getter; + const TTransformer& Transformer; + const int Prims; + static const int IdxConsumed = 6; + static const int VtxConsumed = 4; +}; + +template +struct GetterHeatmap { + GetterHeatmap(const T* values, int rows, int cols, double scale_min, double scale_max, double width, double height, double xref, double yref, double ydir) : + Values(values), + Count(rows*cols), + Rows(rows), + Cols(cols), + ScaleMin(scale_min), + ScaleMax(scale_max), + Width(width), + Height(height), + XRef(xref), + YRef(yref), + YDir(ydir), + HalfSize(Width*0.5, Height*0.5) + { } + + inline RectInfo operator()(int idx) const { + double val = (double)Values[idx]; + const int r = idx / Cols; + const int c = idx % Cols; + const ImPlotPoint p(XRef + HalfSize.x + c*Width, YRef + YDir * (HalfSize.y + r*Height)); + RectInfo rect; + rect.Min.x = p.x - HalfSize.x; + rect.Min.y = p.y - HalfSize.y; + rect.Max.x = p.x + HalfSize.x; + rect.Max.y = p.y + HalfSize.y; + const float t = ImClamp((float)ImRemap01(val, ScaleMin, ScaleMax),0.0f,1.0f); + rect.Color = GImPlot->ColormapData.LerpTable(GImPlot->Style.Colormap, t); + return rect; + } + const T* const Values; + const int Count, Rows, Cols; + const double ScaleMin, ScaleMax, Width, Height, XRef, YRef, YDir; + const ImPlotPoint HalfSize; +}; + +template +void RenderHeatmap(Transformer transformer, ImDrawList& DrawList, const T* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, bool reverse_y) { + ImPlotContext& gp = *GImPlot; + if (scale_min == scale_max) { + ImVec2 a = transformer(bounds_min); + ImVec2 b = transformer(bounds_max); + ImU32 col = GetColormapColorU32(0,gp.Style.Colormap); + DrawList.AddRectFilled(a, b, col); + return; + } + const double yref = reverse_y ? bounds_max.y : bounds_min.y; + const double ydir = reverse_y ? -1 : 1; + GetterHeatmap getter(values, rows, cols, scale_min, scale_max, (bounds_max.x - bounds_min.x) / cols, (bounds_max.y - bounds_min.y) / rows, bounds_min.x, yref, ydir); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderPrimitives(RectRenderer, TransformerLinLin>(getter, TransformerLinLin()), DrawList, gp.CurrentPlot->PlotRect); break; + case ImPlotScale_LogLin: RenderPrimitives(RectRenderer, TransformerLogLin>(getter, TransformerLogLin()), DrawList, gp.CurrentPlot->PlotRect); break;; + case ImPlotScale_LinLog: RenderPrimitives(RectRenderer, TransformerLinLog>(getter, TransformerLinLog()), DrawList, gp.CurrentPlot->PlotRect); break;; + case ImPlotScale_LogLog: RenderPrimitives(RectRenderer, TransformerLogLog>(getter, TransformerLogLog()), DrawList, gp.CurrentPlot->PlotRect); break;; + } + if (fmt != NULL) { + const double w = (bounds_max.x - bounds_min.x) / cols; + const double h = (bounds_max.y - bounds_min.y) / rows; + const ImPlotPoint half_size(w*0.5,h*0.5); + int i = 0; + for (int r = 0; r < rows; ++r) { + for (int c = 0; c < cols; ++c) { + ImPlotPoint p; + p.x = bounds_min.x + 0.5*w + c*w; + p.y = yref + ydir * (0.5*h + r*h); + ImVec2 px = transformer(p); + char buff[32]; + sprintf(buff, fmt, values[i]); + ImVec2 size = ImGui::CalcTextSize(buff); + double t = ImClamp(ImRemap01((double)values[i], scale_min, scale_max),0.0,1.0); + ImVec4 color = SampleColormap((float)t); + ImU32 col = CalcTextColor(color); + DrawList.AddText(px - size * 0.5f, col, buff); + i++; + } + } + } +} + +template +void PlotHeatmap(const char* label_id, const T* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max) { + if (BeginItem(label_id)) { + if (FitThisFrame()) { + FitPoint(bounds_min); + FitPoint(bounds_max); + } + ImDrawList& DrawList = *GetPlotDrawList(); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderHeatmap(TransformerLinLin(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break; + case ImPlotScale_LogLin: RenderHeatmap(TransformerLogLin(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break; + case ImPlotScale_LinLog: RenderHeatmap(TransformerLinLog(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break; + case ImPlotScale_LogLog: RenderHeatmap(TransformerLogLog(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break; + } + EndItem(); + } +} + +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImS8* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImU8* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImS16* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImU16* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImS32* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImU32* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImS64* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const ImU64* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const float* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); +template IMPLOT_API void PlotHeatmap(const char* label_id, const double* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max); + +//----------------------------------------------------------------------------- +// PLOT HISTOGRAM +//----------------------------------------------------------------------------- + +template +double PlotHistogram(const char* label_id, const T* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale) { + + if (count <= 0 || bins == 0) + return 0; + + if (range.Min == 0 && range.Max == 0) { + T Min, Max; + ImMinMaxArray(values, count, &Min, &Max); + range.Min = (double)Min; + range.Max = (double)Max; + } + + double width; + if (bins < 0) + CalculateBins(values, count, bins, range, bins, width); + else + width = range.Size() / bins; + + ImVector& bin_centers = GImPlot->Temp1; + ImVector& bin_counts = GImPlot->Temp2; + bin_centers.resize(bins); + bin_counts.resize(bins); + int below = 0; + + for (int b = 0; b < bins; ++b) { + bin_centers[b] = range.Min + b * width + width * 0.5; + bin_counts[b] = 0; + } + int counted = 0; + double max_count = 0; + for (int i = 0; i < count; ++i) { + double val = (double)values[i]; + if (range.Contains(val)) { + const int b = ImClamp((int)((val - range.Min) / width), 0, bins - 1); + bin_counts[b] += 1.0; + if (bin_counts[b] > max_count) + max_count = bin_counts[b]; + counted++; + } + else if (val < range.Min) { + below++; + } + } + if (cumulative && density) { + if (outliers) + bin_counts[0] += below; + for (int b = 1; b < bins; ++b) + bin_counts[b] += bin_counts[b-1]; + double scale = 1.0 / (outliers ? count : counted); + for (int b = 0; b < bins; ++b) + bin_counts[b] *= scale; + max_count = bin_counts[bins-1]; + } + else if (cumulative) { + if (outliers) + bin_counts[0] += below; + for (int b = 1; b < bins; ++b) + bin_counts[b] += bin_counts[b-1]; + max_count = bin_counts[bins-1]; + } + else if (density) { + double scale = 1.0 / ((outliers ? count : counted) * width); + for (int b = 0; b < bins; ++b) + bin_counts[b] *= scale; + max_count *= scale; + } + PlotBars(label_id, &bin_centers.Data[0], &bin_counts.Data[0], bins, bar_scale*width); + return max_count; +} + +template IMPLOT_API double PlotHistogram(const char* label_id, const ImS8* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImU8* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImS16* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImU16* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImS32* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImU32* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImS64* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const ImU64* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const float* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); +template IMPLOT_API double PlotHistogram(const char* label_id, const double* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale); + +//----------------------------------------------------------------------------- +// PLOT HISTOGRAM 2D +//----------------------------------------------------------------------------- + +template +double PlotHistogram2D(const char* label_id, const T* xs, const T* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers) { + + if (count <= 0 || x_bins == 0 || y_bins == 0) + return 0; + + if (range.X.Min == 0 && range.X.Max == 0) { + T Min, Max; + ImMinMaxArray(xs, count, &Min, &Max); + range.X.Min = (double)Min; + range.X.Max = (double)Max; + } + if (range.Y.Min == 0 && range.Y.Max == 0) { + T Min, Max; + ImMinMaxArray(ys, count, &Min, &Max); + range.Y.Min = (double)Min; + range.Y.Max = (double)Max; + } + + double width, height; + if (x_bins < 0) + CalculateBins(xs, count, x_bins, range.X, x_bins, width); + else + width = range.X.Size() / x_bins; + if (y_bins < 0) + CalculateBins(ys, count, y_bins, range.Y, y_bins, height); + else + height = range.Y.Size() / y_bins; + + const int bins = x_bins * y_bins; + + ImVector& bin_counts = GImPlot->Temp1; + bin_counts.resize(bins); + + for (int b = 0; b < bins; ++b) + bin_counts[b] = 0; + + int counted = 0; + double max_count = 0; + for (int i = 0; i < count; ++i) { + if (range.Contains((double)xs[i], (double)ys[i])) { + const int xb = ImClamp( (int)((double)(xs[i] - range.X.Min) / width) , 0, x_bins - 1); + const int yb = ImClamp( (int)((double)(ys[i] - range.Y.Min) / height) , 0, y_bins - 1); + const int b = yb * x_bins + xb; + bin_counts[b] += 1.0; + if (bin_counts[b] > max_count) + max_count = bin_counts[b]; + counted++; + } + } + if (density) { + double scale = 1.0 / ((outliers ? count : counted) * width * height); + for (int b = 0; b < bins; ++b) + bin_counts[b] *= scale; + max_count *= scale; + } + + if (BeginItem(label_id)) { + if (FitThisFrame()) { + FitPoint(range.Min()); + FitPoint(range.Max()); + } + ImDrawList& DrawList = *GetPlotDrawList(); + switch (GetCurrentScale()) { + case ImPlotScale_LinLin: RenderHeatmap(TransformerLinLin(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break; + case ImPlotScale_LogLin: RenderHeatmap(TransformerLogLin(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break; + case ImPlotScale_LinLog: RenderHeatmap(TransformerLinLog(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break; + case ImPlotScale_LogLog: RenderHeatmap(TransformerLogLog(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break; + } + EndItem(); + } + return max_count; +} + +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const float* xs, const float* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); +template IMPLOT_API double PlotHistogram2D(const char* label_id, const double* xs, const double* ys, int count, int x_bins, int y_bins, bool density, ImPlotLimits range, bool outliers); + +//----------------------------------------------------------------------------- +// PLOT DIGITAL +//----------------------------------------------------------------------------- + +// TODO: Make this behave like all the other plot types (.e. not fixed in y axis) + +template +inline void PlotDigitalEx(const char* label_id, Getter getter) { + if (BeginItem(label_id, ImPlotCol_Fill)) { + ImPlotContext& gp = *GImPlot; + ImDrawList& DrawList = *GetPlotDrawList(); + const ImPlotNextItemData& s = GetItemData(); + if (getter.Count > 1 && s.RenderFill) { + const int y_axis = GetCurrentYAxis(); + int pixYMax = 0; + ImPlotPoint itemData1 = getter(0); + for (int i = 0; i < getter.Count; ++i) { + ImPlotPoint itemData2 = getter(i); + if (ImNanOrInf(itemData1.y)) { + itemData1 = itemData2; + continue; + } + if (ImNanOrInf(itemData2.y)) itemData2.y = ImConstrainNan(ImConstrainInf(itemData2.y)); + int pixY_0 = (int)(s.LineWeight); + itemData1.y = ImMax(0.0, itemData1.y); + float pixY_1_float = s.DigitalBitHeight * (float)itemData1.y; + int pixY_1 = (int)(pixY_1_float); //allow only positive values + int pixY_chPosOffset = (int)(ImMax(s.DigitalBitHeight, pixY_1_float) + s.DigitalBitGap); + pixYMax = ImMax(pixYMax, pixY_chPosOffset); + ImVec2 pMin = PlotToPixels(itemData1); + ImVec2 pMax = PlotToPixels(itemData2); + int pixY_Offset = 20; //20 pixel from bottom due to mouse cursor label + pMin.y = (gp.PixelRange[y_axis].Min.y) + ((-gp.DigitalPlotOffset) - pixY_Offset); + pMax.y = (gp.PixelRange[y_axis].Min.y) + ((-gp.DigitalPlotOffset) - pixY_0 - pixY_1 - pixY_Offset); + //plot only one rectangle for same digital state + while (((i+2) < getter.Count) && (itemData1.y == itemData2.y)) { + const int in = (i + 1); + itemData2 = getter(in); + if (ImNanOrInf(itemData2.y)) break; + pMax.x = PlotToPixels(itemData2).x; + i++; + } + //do not extend plot outside plot range + if (pMin.x < gp.PixelRange[y_axis].Min.x) pMin.x = gp.PixelRange[y_axis].Min.x; + if (pMax.x < gp.PixelRange[y_axis].Min.x) pMax.x = gp.PixelRange[y_axis].Min.x; + if (pMin.x > gp.PixelRange[y_axis].Max.x) pMin.x = gp.PixelRange[y_axis].Max.x; + if (pMax.x > gp.PixelRange[y_axis].Max.x) pMax.x = gp.PixelRange[y_axis].Max.x; + //plot a rectangle that extends up to x2 with y1 height + if ((pMax.x > pMin.x) && (gp.CurrentPlot->PlotRect.Contains(pMin) || gp.CurrentPlot->PlotRect.Contains(pMax))) { + // ImVec4 colAlpha = item->Color; + // colAlpha.w = item->Highlight ? 1.0f : 0.9f; + DrawList.AddRectFilled(pMin, pMax, ImGui::GetColorU32(s.Colors[ImPlotCol_Fill])); + } + itemData1 = itemData2; + } + gp.DigitalPlotItemCnt++; + gp.DigitalPlotOffset += pixYMax; + } + EndItem(); + } +} + + +template +void PlotDigital(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) { + GetterXsYs getter(xs,ys,count,offset,stride); + return PlotDigitalEx(label_id, getter); +} + +template IMPLOT_API void PlotDigital(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride); +template IMPLOT_API void PlotDigital(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride); + +// custom +void PlotDigitalG(const char* label_id, ImPlotPoint (*getter_func)(void* data, int idx), void* data, int count, int offset) { + GetterFuncPtr getter(getter_func,data,count,offset); + return PlotDigitalEx(label_id, getter); +} + +//----------------------------------------------------------------------------- +// PLOT IMAGE +//----------------------------------------------------------------------------- + +void PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bmin, const ImPlotPoint& bmax, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col) { + if (BeginItem(label_id)) { + if (FitThisFrame()) { + FitPoint(bmin); + FitPoint(bmax); + } + ImU32 tint_col32 = ImGui::ColorConvertFloat4ToU32(tint_col); + GetCurrentItem()->Color = tint_col32; + ImDrawList& DrawList = *GetPlotDrawList(); + ImVec2 p1 = PlotToPixels(bmin.x, bmax.y); + ImVec2 p2 = PlotToPixels(bmax.x, bmin.y); + PushPlotClipRect(); + DrawList.AddImage(user_texture_id, p1, p2, uv0, uv1, tint_col32); + PopPlotClipRect(); + EndItem(); + } +} + +//----------------------------------------------------------------------------- +// PLOT TEXT +//----------------------------------------------------------------------------- + +// double +void PlotText(const char* text, double x, double y, bool vertical, const ImVec2& pixel_offset) { + IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, "PlotText() needs to be called between BeginPlot() and EndPlot()!"); + ImDrawList & DrawList = *GetPlotDrawList(); + PushPlotClipRect(); + ImU32 colTxt = GetStyleColorU32(ImPlotCol_InlayText); + if (vertical) { + ImVec2 ctr = CalcTextSizeVertical(text) * 0.5f; + ImVec2 pos = PlotToPixels(ImPlotPoint(x,y)) + ImVec2(-ctr.x, ctr.y) + pixel_offset; + AddTextVertical(&DrawList, pos, colTxt, text); + } + else { + ImVec2 pos = PlotToPixels(ImPlotPoint(x,y)) - ImGui::CalcTextSize(text) * 0.5f + pixel_offset; + DrawList.AddText(pos, colTxt, text); + } + PopPlotClipRect(); +} + +//----------------------------------------------------------------------------- +// PLOT DUMMY +//----------------------------------------------------------------------------- + +void PlotDummy(const char* label_id) { + if (BeginItem(label_id, ImPlotCol_Line)) + EndItem(); +} + +} // namespace ImPlot \ No newline at end of file diff --git a/thirdparty/stb/stb_image.h b/DearPyGui/vendor/stb/stb_image.h similarity index 100% rename from thirdparty/stb/stb_image.h rename to DearPyGui/vendor/stb/stb_image.h diff --git a/thirdparty/DearPyGui_Ext/dearpygui_ext/.gitignore b/DearSandbox/.gitignore similarity index 100% rename from thirdparty/DearPyGui_Ext/dearpygui_ext/.gitignore rename to DearSandbox/.gitignore diff --git a/DearSandbox/CMakeLists.txt b/DearSandbox/CMakeLists.txt new file mode 100644 index 000000000..b32955e52 --- /dev/null +++ b/DearSandbox/CMakeLists.txt @@ -0,0 +1,97 @@ +cmake_minimum_required (VERSION 3.13) + +add_executable (DearSandbox) + +set_property(TARGET DearSandbox PROPERTY CXX_STANDARD 17) + +if(APPLE) + find_package(Python3 COMPONENTS Interpreter Development) +endif() + +target_sources(DearSandbox + + PRIVATE + + "$<$:main.cpp>" + "$<$:../DearPyGui/src/core/cpp.hint>" + "$<$:main_linux.cpp>" + "$<$:main_linux.cpp>" +) + +target_include_directories(DearSandbox + + PRIVATE + + "$<$:${CMAKE_SOURCE_DIR}/Dependencies/cpython/debug/include/python3.9d/>" + "$<$:${CMAKE_SOURCE_DIR}/Dependencies/cpython/PC/>" + "../Dependencies/spdlog/include" + "../Dependencies/imgui/" + "../DearPyGui/vendor/implot/" + "../DearPyGui/src/" + "../DearPyGui/src/core/" + "../DearPyGui/src/core/Modules" + "../DearPyGui/src/core/AppItems" + "../DearPyGui/src/core/DrawCommands" + "../DearPyGui/src/core/PythonCommands" + "../DearPyGui/src/core/PythonUtilities" + "../DearPyGui/src/core/Registries" + "../DearPyGui/src/core/Theming" + "../Dependencies/cpython/" + "../Dependencies/cpython/debug/" + "../Dependencies/cpython/Include/" +) + +target_compile_definitions(DearSandbox + + PUBLIC + + $<$:MV_DEBUG> + $<$:MV_RELEASE> +) + +if (WIN32) + + + set_target_properties(DearSandbox + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}$<$:/DearSandbox/>$<$:/DearSandbox/>" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}$<$:/DearSandbox/>$<$:/DearSandbox/>" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}$<$:/DearSandbox/>$<$:/DearSandbox/>" + ) + + target_link_directories(DearSandbox PRIVATE "../Dependencies/cpython/PCbuild/amd64/") + target_link_libraries(DearSandbox PUBLIC coreemb $<$:python39_d> $<$:python39>) + + add_custom_command(TARGET DearSandbox PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_SOURCE_DIR}/Dependencies/cpython/PCbuild/amd64/python3$<$:_d>.dll $) + + + add_custom_command(TARGET DearSandbox PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_SOURCE_DIR}/Dependencies/cpython/PCbuild/amd64/python39$<$:_d>.dll $) + +elseif(APPLE) + + set_property(TARGET DearSandbox APPEND_STRING PROPERTY COMPILE_FLAGS "-Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g") + + target_link_directories(DearSandbox PRIVATE ../Dependencies/cpython/debug/lib) + + target_link_libraries(DearSandbox PUBLIC coreemb -ldl "-framework CoreFoundation" "python3.9d") + + file(GLOB PYTHON_LIBS_PATH "../Dependencies/cpython/debug/lib/python*") + + add_compile_definitions(PYTHON_LIBS_PATH="${PYTHON_LIBS_PATH}") + +else() # Linux + + target_link_directories(DearSandbox PRIVATE ../Dependencies/cpython/debug) + + target_link_libraries(DearSandbox + + PUBLIC + "-lcrypt -lpthread -ldl -lutil -lm" + coreemb + python3.9d + ) +endif() \ No newline at end of file diff --git a/DearSandbox/main.cpp b/DearSandbox/main.cpp new file mode 100644 index 000000000..d9c5d9a3c --- /dev/null +++ b/DearSandbox/main.cpp @@ -0,0 +1,76 @@ +#include "mvPython.h" +#include "mvStdOutput.h" +#include "mvModule_Core.h" +#include "mvApp.h" +#include +#include +#include +#include +#include "mvViewport.h" +#include "mvLog.h" + +namespace fs = std::filesystem; +using namespace Marvel; + +int main(int argc, char* argv[]) +{ + +#ifdef MV_RELEASE + HWND hWnd = GetConsoleWindow(); + ShowWindow(hWnd, SW_HIDE); + GenerateStubFile("../../DearPyGui/dearpygui/core.pyi"); +#else + HWND hWnd = GetConsoleWindow(); + ShowWindow(hWnd, SW_SHOW); +#endif + + // add our custom module + PyImport_AppendInittab("sandboxout", &PyInit_embOut); + PyImport_AppendInittab("core", &PyInit_core); + + // set path and start the interpreter + wchar_t* path = Py_DecodeLocale("../../DearSandbox/;../../Dependencies/cpython/Lib;../../Dependencies/cpython/PCbuild/amd64;../../DearPyGui/", nullptr); + + Py_SetPath(path); + Py_NoSiteFlag = 1; // this must be set to 1 + Py_DontWriteBytecodeFlag = 1; + + // initialize python + Py_Initialize(); + if (!Py_IsInitialized()) + { + printf("Error initializing Python interpreter\n"); + return 1; + } + + PyObject* mmarvel = PyImport_ImportModule("core"); + + // import our custom module to capture stdout/stderr + PyObject* m = PyImport_ImportModule("sandboxout"); + PySys_SetObject("stdout", m); + PySys_SetObject("stderr", m); + + PyObject* pModule = PyImport_ImportModule("sandbox"); // new reference + + // check if error occurred + if (!PyErr_Occurred() && pModule != nullptr) + { + Py_XDECREF(pModule); + Py_XDECREF(mmarvel); + } + + else + { + PyErr_Print(); + + // create window + auto window = mvViewport::CreateViewport(1080, + 800, true); + window->show(false, false); + while (window->running()) + window->renderFrame(); + delete window; + delete mvApp::GetApp(); + } + +} \ No newline at end of file diff --git a/DearSandbox/main_linux.cpp b/DearSandbox/main_linux.cpp new file mode 100644 index 000000000..3439664cb --- /dev/null +++ b/DearSandbox/main_linux.cpp @@ -0,0 +1,74 @@ +#include "mvPython.h" +#include "mvStdOutput.h" +#include "mvModule_Core.h" +#include "mvViewport.h" +#include + +using namespace Marvel; + +int main(int argc, char* argv[]) +{ + + PyObject* m = nullptr; + + // initialize python + // add our custom module + PyImport_AppendInittab("sandboxout", &PyInit_embOut); + PyImport_AppendInittab("core", &PyInit_core); + + // set path and start the interpreter +#if defined(__APPLE__) + wchar_t *deco = Py_DecodeLocale( + PYTHON_LIBS_PATH":" + PYTHON_LIBS_PATH"/lib-dynload:" + PYTHON_LIBS_PATH"/site-packages:" + "../../DearPyGui:" + "../../DearSandbox", + nullptr); +#else + wchar_t *deco = Py_DecodeLocale( + "../../Dependencies/cpython/debug/build/lib.linux-x86_64-3.8-pydebug/:../" + "../Dependencies/cpython/Lib/:../../DearPyGui:../../DearSandbox", + nullptr); +#endif + + Py_SetPath(deco); + Py_NoSiteFlag = 1; // this must be set to 1 + Py_DontWriteBytecodeFlag = 1; + //_PyEval_SetSwitchInterval() + + Py_Initialize(); + if (!Py_IsInitialized()) + { + printf("Error initializing Python interpreter\n"); + return 1; + } + + PyObject* mmarvel = PyImport_ImportModule("core"); + + // import our custom module to capture stdout/stderr + m = PyImport_ImportModule("sandboxout"); + PySys_SetObject("stdout", m); + PySys_SetObject("stderr", m); + + PyObject* pModule = PyImport_ImportModule("sandbox"); // new reference + + // check if error occurred + if (!PyErr_Occurred() && pModule != nullptr) + { + Py_XDECREF(pModule); + Py_XDECREF(mmarvel); + return 0; + } + + PyErr_Print(); + + // create window + auto viewport = mvViewport::CreateViewport(1080, 800, true); + viewport->show(false, false); + viewport->run(); + delete viewport; + delete mvApp::GetApp(); + + return 0; +} \ No newline at end of file diff --git a/DearSandbox/mvStdOutput.h b/DearSandbox/mvStdOutput.h new file mode 100644 index 000000000..8bec09e47 --- /dev/null +++ b/DearSandbox/mvStdOutput.h @@ -0,0 +1,53 @@ +#pragma once +//----------------------------------------------------------------------------- +// mvStdOutput +// +// - This file defines a python module to intercept console output and +// reroute it to the marvel logger +// +//----------------------------------------------------------------------------- + +#include "mvPython.h" +#include "mvAppLog.h" +#include +#include + +namespace Marvel { + + static PyObject* writeToLogger(PyObject* self, PyObject* args) + { + PyGILState_STATE gstate = PyGILState_Ensure(); + const char* what; + if (!PyArg_ParseTuple(args, "s", &what)) + { + PyGILState_Release(gstate); + Py_RETURN_NONE; + } + + Marvel::mvAppLog::AddLog("%0s", what); + PyGILState_Release(gstate); + Py_RETURN_NONE; + } + + PyObject* flush(PyObject* self, PyObject* args) + { + // no-op + return Py_BuildValue(""); + } + + static PyMethodDef outmethods[] = { + {"write", writeToLogger, METH_VARARGS, "Write something."}, + {"flush", flush, METH_VARARGS, "Flush."}, + {NULL, NULL, 0, NULL} + }; + + PyModuleDef OutModule = { + PyModuleDef_HEAD_INIT, "sandboxout", NULL, -1, outmethods, + NULL, NULL, NULL, NULL + }; + + PyObject* PyInit_embOut(void) + { + return PyModule_Create(&OutModule); + } +} \ No newline at end of file diff --git a/DearSandbox/sandbox.py b/DearSandbox/sandbox.py new file mode 100644 index 000000000..0bbb9a6f6 --- /dev/null +++ b/DearSandbox/sandbox.py @@ -0,0 +1,18 @@ +from dearpygui.core import * +from dearpygui.simple import * +from dearpygui.demo import * + +add_font("google", "../../Resources/NotoSerifCJKjp-Medium.otf", 20) +set_font("google", 20) + + +set_log_level(0) +show_logger() +show_demo() + +create_viewport() +setup_dearpygui() +show_viewport() +while(is_dearpygui_running()): + render_dearpygui_frame() +cleanup_dearpygui() \ No newline at end of file diff --git a/thirdparty/.gitignore b/Dependencies/.gitignore similarity index 100% rename from thirdparty/.gitignore rename to Dependencies/.gitignore diff --git a/Dependencies/ImGuiFileDialog b/Dependencies/ImGuiFileDialog new file mode 160000 index 000000000..e39e6d5ca --- /dev/null +++ b/Dependencies/ImGuiFileDialog @@ -0,0 +1 @@ +Subproject commit e39e6d5ca8fb69914392452848015f0a3c6d7a6d diff --git a/Dependencies/cpython b/Dependencies/cpython new file mode 160000 index 000000000..1e5d33e9b --- /dev/null +++ b/Dependencies/cpython @@ -0,0 +1 @@ +Subproject commit 1e5d33e9b9b8631b36f061103a30208b206fd03a diff --git a/thirdparty/freetype b/Dependencies/freetype similarity index 100% rename from thirdparty/freetype rename to Dependencies/freetype diff --git a/Dependencies/glfw b/Dependencies/glfw new file mode 160000 index 000000000..0a49ef0a0 --- /dev/null +++ b/Dependencies/glfw @@ -0,0 +1 @@ +Subproject commit 0a49ef0a00baa3ab520ddc452f0e3b1e099c5589 diff --git a/Dependencies/imgui b/Dependencies/imgui new file mode 160000 index 000000000..81e0b18e3 --- /dev/null +++ b/Dependencies/imgui @@ -0,0 +1 @@ +Subproject commit 81e0b18e38cceafa18a24fae0f2357412f0586c4 diff --git a/Dependencies/spdlog b/Dependencies/spdlog new file mode 160000 index 000000000..de0dbfa35 --- /dev/null +++ b/Dependencies/spdlog @@ -0,0 +1 @@ +Subproject commit de0dbfa3596a18cd70a4619b6a9766847a941276 diff --git a/Distribution/.gitignore b/Distribution/.gitignore new file mode 100644 index 000000000..8fe780624 --- /dev/null +++ b/Distribution/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +build/ +dearpygui.egg-info/ +dist/ +dearpygui/ +*.txt diff --git a/Distribution/BuildPythonWheel.py b/Distribution/BuildPythonWheel.py new file mode 100644 index 000000000..6281f57e6 --- /dev/null +++ b/Distribution/BuildPythonWheel.py @@ -0,0 +1,30 @@ +import shutil +import os +from os import path +import sys + +# arg 1 - Location (i.e. /../../cmake-build-release/DearPyGui/Release/dearpygui.pyd) +# arg 2 - File (i.e. dearpygui.pyd, dearpygui.so) +# arg 3 - Version Number + +script_dir = os.getcwd() +location = sys.argv[1] +vnum = sys.argv[2] + +# create the necessary directories if they do not exist +if not os.path.isdir(script_dir + "/dearpygui/"): + os.mkdir(script_dir + "/dearpygui/") + +# copy add items to temporary location +shutil.copy(location, script_dir +"/dearpygui") +shutil.copy(script_dir + "/../DearPyGui/dearpygui/core.pyi", script_dir + "/dearpygui") +shutil.copy(script_dir + "/../DearPyGui/dearpygui/simple.py", script_dir + "/dearpygui") +shutil.copy(script_dir + "/../DearPyGui/dearpygui/demo.py", script_dir + "/dearpygui") +shutil.copy(script_dir + "/../Distribution/vcruntime140_1.dll", script_dir + "/dearpygui") + +with open(script_dir + "/dearpygui/__init__.py", 'w') as file: + file.write("pass\n") + +# create information file used by setup.py +with open(script_dir + "/distinfo.txt", 'w') as file: + file.write(vnum + '\n') diff --git a/Distribution/MANIFEST.IN b/Distribution/MANIFEST.IN new file mode 100644 index 000000000..bad50dfe9 --- /dev/null +++ b/Distribution/MANIFEST.IN @@ -0,0 +1,4 @@ +# Include the README +include ../docs/*.md +# Include the license file +include ../LICENSE \ No newline at end of file diff --git a/Distribution/setup.cfg b/Distribution/setup.cfg new file mode 100644 index 000000000..31df949d0 --- /dev/null +++ b/Distribution/setup.cfg @@ -0,0 +1,5 @@ +[metadata] +license_file = ../LICENSE +[bdist_wheel] +universal = 0 +python-tag = cp38 \ No newline at end of file diff --git a/Distribution/setup.py b/Distribution/setup.py new file mode 100644 index 000000000..a9f5accea --- /dev/null +++ b/Distribution/setup.py @@ -0,0 +1,51 @@ +from setuptools import setup, find_packages, Distribution +from codecs import open +from os import path + +# import readme content +with open("../docs/README.md", encoding='utf-8') as f: + long_description = f.read() + +# use info file created by BuildPythonWheel.py +with open("distinfo.txt", encoding='utf-8') as file: + lines = file.readlines() + DEARPYGUI_VERSION = lines[0].rstrip("\n") + +class BinaryDistribution(Distribution): + """Distribution which always forces a binary package with platform name""" + def has_ext_modules(foo): + return True + +setup( + name='dearpygui', # Required + version=DEARPYGUI_VERSION, # Required + author="Jonathan Hoffstadt and Preston Cothren", # Optional + author_email="jonathanhoffstadt@yahoo.com", # Optional + description='DearPyGui: A simple Python GUI Toolkit', # Required + long_description=long_description, # Optional + long_description_content_type='text/markdown', # Optional + url='https://github.com/hoffstadt/DearPyGui', # Optional + license = 'MIT', + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Education', + 'Intended Audience :: Developers', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: MIT License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: Microsoft :: Windows :: Windows 10', + 'Operating System :: POSIX :: Linux', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Software Development :: User Interfaces', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required + package_data={ # Optional + 'dearpygui': ["core.so", "core.pyd", "core.pyi", "simple.py", "demo.py", "vcruntime140_1.dll"], + }, + distclass=BinaryDistribution +) diff --git a/thirdparty/Microsoft/vcruntime140_1.dll b/Distribution/vcruntime140_1.dll similarity index 100% rename from thirdparty/Microsoft/vcruntime140_1.dll rename to Distribution/vcruntime140_1.dll diff --git a/ImguiTesting/CMakeLists.txt b/ImguiTesting/CMakeLists.txt new file mode 100644 index 000000000..f2c131877 --- /dev/null +++ b/ImguiTesting/CMakeLists.txt @@ -0,0 +1,88 @@ +cmake_minimum_required (VERSION 3.13) + +add_executable (PureImgui) + +target_sources(PureImgui + + PRIVATE + + "$<$:main.cpp>" + "$<$:main.cpp>" + "$<$:main.mm>" + "$<$:src/mvAppleWindow.mm>" + "$<$:src/mvWindowsWindow.cpp>" + "$<$:src/mvLinuxWindow.cpp>" + + # imnodes + "../DearPyGui/vendor/imnodes/imnodes.cpp" + + # implot + "../DearPyGui/vendor/implot/implot.cpp" + "../DearPyGui/vendor/implot/implot_items.cpp" + "../DearPyGui/vendor/implot/implot_demo.cpp" + + # imgui + "../Dependencies/imgui/misc/freetype/imgui_freetype.cpp" + "../Dependencies/imgui/imgui.cpp" + "../Dependencies/imgui/imgui_demo.cpp" + "../Dependencies/imgui/imgui_draw.cpp" + "../Dependencies/imgui/imgui_widgets.cpp" + "../Dependencies/imgui/imgui_tables.cpp" + "$<$:../Dependencies/imgui/backends/imgui_impl_win32.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_dx11.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_metal.mm>" + "$<$:../Dependencies/imgui/backends/imgui_impl_glfw.cpp>" + + "$<$:../Dependencies/imgui/examples/libs/gl3w/GL/gl3w.c>" + "$<$:../Dependencies/imgui/backends/imgui_impl_glfw.cpp>" + "$<$:../Dependencies/imgui/backends/imgui_impl_opengl3.cpp>" +) + + + +if(APPLE) + + SET_PROPERTY(TARGET PureImgui APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc") + + set(CMAKE_EXE_LINKER_FLAGS "\ + -framework Metal \ + -framework MetalKit \ + -framework Cocoa \ + -framework IOKit \ + -framework CoreVideo \ + -framework QuartzCore") + +elseif(UNIX) + + SET_PROPERTY(TARGET PureImgui APPEND_STRING PROPERTY COMPILE_FLAGS "-g -Wall -Wformat") + add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GL3W) + +endif() + +target_include_directories(PureImgui + + PRIVATE + + "src/" + "../Dependencies/glfw/include/" + "../Dependencies/glfw/deps/" + "../Dependencies/imgui/" + "../Dependencies/imgui/misc/freetype/" + "../Dependencies/ImGuiFileDialog/ImGuiFileDialog/" + "../Dependencies/imgui/backends/" + "../Dependencies/imgui/examples/libs/gl3w" + "../DearPyGui/vendor/implot/" + "../DearPyGui/vendor/stb/" + "../DearPyGui/vendor/imnodes/" +) + +target_link_libraries(PureImgui + + PRIVATE + + freetype + $<$:GL> + $<$:glfw> + $<$:glfw> + $<$:d3d11> +) diff --git a/ImguiTesting/main.cpp b/ImguiTesting/main.cpp new file mode 100644 index 000000000..f2470536d --- /dev/null +++ b/ImguiTesting/main.cpp @@ -0,0 +1,41 @@ +#if defined (_WIN32) +#include "mvWindowsWindow.h" +#define mvWindowClass mvWindowsWindow +#elif defined(__APPLE__) +#include "mvAppleWindow.h" +#define mvWindowClass mvAppleWindow +#else +#include "mvLinuxWindow.h" +#define mvWindowClass mvLinuxWindow +#endif + +#include + +int main() +{ + auto window = new mvWindowClass(); + + window->show(); + + window->setup(); + while (window->m_running) + { + window->prerender(); + + // place test code here + +#if defined (_WIN32) + ImGui::ShowDemoWindow(); + ImPlot::ShowDemoWindow(); + window->postrender(); +#elif defined(__APPLE__) +#else + ImGui::ShowDemoWindow(); + ImPlot::ShowDemoWindow(); + window->postrender(); +#endif + + + } + +} \ No newline at end of file diff --git a/ImguiTesting/main.mm b/ImguiTesting/main.mm new file mode 100644 index 000000000..3eca89a02 --- /dev/null +++ b/ImguiTesting/main.mm @@ -0,0 +1 @@ +#include "main.cpp" \ No newline at end of file diff --git a/ImguiTesting/src/mvAppleWindow.h b/ImguiTesting/src/mvAppleWindow.h new file mode 100644 index 000000000..5afb8118a --- /dev/null +++ b/ImguiTesting/src/mvAppleWindow.h @@ -0,0 +1,33 @@ +#pragma once + +#import +#import + +class GLFWwindow; + +class mvAppleWindow +{ + +public: + + bool m_running = true; + + mvAppleWindow(); + + virtual void show() {} + + virtual void setup(); + virtual void prerender(); + virtual void render(); + virtual void cleanup(); + +private: + + float m_clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + + GLFWwindow* m_window; + CAMetalLayer* m_layer; + MTLRenderPassDescriptor* m_renderPassDescriptor; + id m_commandQueue; + +}; diff --git a/ImguiTesting/src/mvAppleWindow.mm b/ImguiTesting/src/mvAppleWindow.mm new file mode 100644 index 000000000..3aa1fd9e5 --- /dev/null +++ b/ImguiTesting/src/mvAppleWindow.mm @@ -0,0 +1,127 @@ +#include "mvAppleWindow.h" +#include + +#define GLFW_INCLUDE_NONE +#define GLFW_EXPOSE_NATIVE_COCOA +#include +#include + +#include "implot.h" +#include "imgui.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_metal.h" +#include + +static void glfw_error_callback(int error, const char* description) +{ + fprintf(stderr, "Glfw Error %d: %s\n", error, description); +} + +mvAppleWindow::mvAppleWindow() +{ + // Setup Dear ImGui binding + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + // Setup style + ImGui::StyleColorsDark(); + + // Setup window + glfwSetErrorCallback(glfw_error_callback); + glfwInit(); + + // Create window with graphics context + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + m_window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", NULL, NULL); + + + id device = MTLCreateSystemDefaultDevice();; + m_commandQueue = [device newCommandQueue]; + + ImGui_ImplGlfw_InitForOpenGL(m_window, true); + ImGui_ImplMetal_Init(device); + + NSWindow *nswin = glfwGetCocoaWindow(m_window); + m_layer = [CAMetalLayer layer]; + m_layer.device = device; + m_layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + nswin.contentView.layer = m_layer; + nswin.contentView.wantsLayer = YES; + + m_renderPassDescriptor = [MTLRenderPassDescriptor new]; +} + +void mvAppleWindow::setup() +{ + +} + +void mvAppleWindow::prerender() +{ + m_running = !glfwWindowShouldClose(m_window); + + @autoreleasepool { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + int width, height; + glfwGetFramebufferSize(m_window, &width, &height); + m_layer.drawableSize = CGSizeMake(width, height); + id drawable = [m_layer nextDrawable]; + + id commandBuffer = [m_commandQueue commandBuffer]; + m_renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(m_clear_color[0], m_clear_color[1], + m_clear_color[2], m_clear_color[3]); + m_renderPassDescriptor.colorAttachments[0].texture = drawable.texture; + m_renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; + m_renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + id m_renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:m_renderPassDescriptor]; + [m_renderEncoder pushDebugGroup:@"ImGui demo"]; + + // Start the Dear ImGui frame + ImGui_ImplMetal_NewFrame(m_renderPassDescriptor); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + render(); + + // Rendering + ImGui::Render(); + ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, m_renderEncoder); + + [m_renderEncoder popDebugGroup]; + [m_renderEncoder endEncoding]; + + [commandBuffer presentDrawable:drawable]; + [commandBuffer commit]; + } + +} + +void mvAppleWindow::render() +{ + ImGui::ShowDemoWindow(); + ImPlot::ShowDemoWindow(); +} + +void mvAppleWindow::cleanup() +{ + // Cleanup + ImGui_ImplMetal_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + glfwDestroyWindow(m_window); + glfwTerminate(); +} + diff --git a/ImguiTesting/src/mvImGuiConfig.h b/ImguiTesting/src/mvImGuiConfig.h new file mode 100644 index 000000000..f26c5c0e8 --- /dev/null +++ b/ImguiTesting/src/mvImGuiConfig.h @@ -0,0 +1,2 @@ +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +#define IMGUI_ENABLE_FREETYPE \ No newline at end of file diff --git a/ImguiTesting/src/mvLinuxWindow.cpp b/ImguiTesting/src/mvLinuxWindow.cpp new file mode 100644 index 000000000..a55d0f915 --- /dev/null +++ b/ImguiTesting/src/mvLinuxWindow.cpp @@ -0,0 +1,111 @@ +// +// Created by jhoffs1 on 7/30/20. +// + +#include "mvLinuxWindow.h" +#include + +#include +#include + +#include "implot.h" +#include "imgui.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include + +static void glfw_error_callback(int error, const char* description) +{ + fprintf(stderr, "Glfw Error %d: %s\n", error, description); +} + +mvLinuxWindow::mvLinuxWindow() +{ + // Setup window + glfwSetErrorCallback(glfw_error_callback); + glfwInit(); + + // Create window with graphics context + // GL 3.0 + GLSL 130 + const char* glsl_version = "#version 130"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); + m_window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", nullptr, nullptr); + + glfwMakeContextCurrent(m_window); + glfwSwapInterval(1); // Enable vsync + + bool err = gl3wInit() != 0; + + // Setup Dear ImGui binding + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + // Setup style + ImGui::StyleColorsDark(); + + // Setup Platform/Renderer bindings + ImGui_ImplGlfw_InitForOpenGL(m_window, true); + ImGui_ImplOpenGL3_Init(glsl_version); + +} + +void mvLinuxWindow::setup() +{ + +} + +void mvLinuxWindow::prerender() +{ + m_running = !glfwWindowShouldClose(m_window); + + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); +} + +void mvLinuxWindow::render() +{ + ImGui::ShowDemoWindow(); + ImPlot::ShowDemoWindow(); +} + +void mvLinuxWindow::postrender() +{ + // Rendering + ImGui::Render(); + int display_w, display_h; + glfwGetFramebufferSize(m_window, &display_w, &display_h); + glViewport(0, 0, display_w, display_h); + glClearColor(m_clear_color[0], m_clear_color[1], m_clear_color[2], m_clear_color[3]); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + + glfwSwapBuffers(m_window); +} + +void mvLinuxWindow::cleanup() +{ + // Cleanup + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + glfwDestroyWindow(m_window); + glfwTerminate(); +} + diff --git a/ImguiTesting/src/mvLinuxWindow.h b/ImguiTesting/src/mvLinuxWindow.h new file mode 100644 index 000000000..c9ffae388 --- /dev/null +++ b/ImguiTesting/src/mvLinuxWindow.h @@ -0,0 +1,28 @@ +#pragma once + +class GLFWwindow; + +class mvLinuxWindow +{ + +public: + + bool m_running = true; + + mvLinuxWindow(); + + virtual void show() {} + + virtual void setup(); + virtual void prerender(); + virtual void render(); + virtual void postrender(); + virtual void cleanup(); + +private: + + float m_clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + + GLFWwindow* m_window; + +}; diff --git a/ImguiTesting/src/mvWindowsWindow.cpp b/ImguiTesting/src/mvWindowsWindow.cpp new file mode 100644 index 000000000..e331154c5 --- /dev/null +++ b/ImguiTesting/src/mvWindowsWindow.cpp @@ -0,0 +1,238 @@ +#include "mvWindowsWindow.h" +#include "implot.h" +#include "imnodes.h" + +// Forward declare message handler from imgui_impl_win32.cpp +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + + +mvWindowsWindow::mvWindowsWindow() +{ + m_wc = { sizeof(WNDCLASSEX), CS_CLASSDC, HandleMsgSetup, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; + RegisterClassEx(&m_wc); + + m_hwnd = CreateWindow(m_wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, m_wc.hInstance, NULL); + + + // Initialize Direct3D + if (!CreateDeviceD3D(m_hwnd)) + { + CleanupDeviceD3D(); + ::UnregisterClass(m_wc.lpszClassName, m_wc.hInstance); + } + +} + +void mvWindowsWindow::show() +{ + + // Show the window + ::ShowWindow(m_hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(m_hwnd); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + imnodes::Initialize(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + + // Setup Platform/Renderer bindings + ImGui_ImplWin32_Init(m_hwnd); + ImGui_ImplDX11_Init(s_pd3dDevice, s_pd3dDeviceContext); +} + +void mvWindowsWindow::setup() +{ + ZeroMemory(&m_msg, sizeof(m_msg)); +} + +void mvWindowsWindow::prerender() +{ + if (m_msg.message == WM_QUIT) + m_running = false; + + // Poll and handle messages (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + if (::PeekMessage(&m_msg, NULL, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&m_msg); + ::DispatchMessage(&m_msg); + //continue; + } + + // Start the Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); +} + +void mvWindowsWindow::postrender() +{ + + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Rendering + ImGui::Render(); + s_pd3dDeviceContext->OMSetRenderTargets(1, &s_mainRenderTargetView, NULL); + s_pd3dDeviceContext->ClearRenderTargetView(s_mainRenderTargetView, (float*)&clear_color); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + s_pSwapChain->Present(1, 0); // Present with vsync + //g_pSwapChain->Present(0, 0); // Present without vsync +} + +void mvWindowsWindow::cleanup() +{ + // Cleanup + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + imnodes::Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + CleanupDeviceD3D(); + ::DestroyWindow(m_hwnd); + ::UnregisterClass(m_wc.lpszClassName, m_wc.hInstance); +} + + +bool mvWindowsWindow::CreateDeviceD3D(HWND hWnd) +{ + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; + if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, + createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &s_pSwapChain, + &s_pd3dDevice, &featureLevel, &s_pd3dDeviceContext) != S_OK) + return false; + + CreateRenderTarget(); + return true; +} + +void mvWindowsWindow::CleanupDeviceD3D() +{ + CleanupRenderTarget(); + if (s_pSwapChain) + { + s_pSwapChain->Release(); + s_pSwapChain = NULL; + } + + if (s_pd3dDeviceContext) + { + s_pd3dDeviceContext->Release(); + s_pd3dDeviceContext = NULL; + } + + if (s_pd3dDevice) + { + s_pd3dDevice->Release(); + s_pd3dDevice = NULL; + } +} + +void mvWindowsWindow::CreateRenderTarget() +{ + ID3D11Texture2D* pBackBuffer; + s_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + s_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &s_mainRenderTargetView); + pBackBuffer->Release(); +} + +void mvWindowsWindow::CleanupRenderTarget() +{ + if (s_mainRenderTargetView) + { + s_mainRenderTargetView->Release(); + s_mainRenderTargetView = NULL; + } +} + + +LRESULT CALLBACK mvWindowsWindow::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept +{ + // use create parameter passed in from CreateWindow() to store window class pointer at WinAPI side + if (msg == WM_NCCREATE) + { + // extract ptr to window class from creation data + const CREATESTRUCTW* const pCreate = reinterpret_cast(lParam); + mvWindowsWindow* const pWnd = static_cast(pCreate->lpCreateParams); + // set WinAPI-managed user data to store ptr to window instance + SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast(pWnd)); + // set message proc to normal (non-setup) handler now that setup is finished + SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast(&mvWindowsWindow::HandleMsgThunk)); + // forward message to window instance handler + return pWnd->HandleMsg(hWnd, msg, wParam, lParam); + } + // if we get a message before the WM_NCCREATE message, handle with default handler + return DefWindowProc(hWnd, msg, wParam, lParam); +} + +LRESULT CALLBACK mvWindowsWindow::HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept +{ + // retrieve ptr to window instance + mvWindowsWindow* const pWnd = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + // forward message to window instance handler + return pWnd->HandleMsg(hWnd, msg, wParam, lParam); +} + +LRESULT mvWindowsWindow::HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (s_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + CleanupRenderTarget(); + s_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); + CreateRenderTarget(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} + + +ID3D11Device* mvWindowsWindow::s_pd3dDevice = NULL; +ID3D11DeviceContext* mvWindowsWindow::s_pd3dDeviceContext = NULL; +IDXGISwapChain* mvWindowsWindow::s_pSwapChain = NULL; +ID3D11RenderTargetView* mvWindowsWindow::s_mainRenderTargetView = NULL; \ No newline at end of file diff --git a/ImguiTesting/src/mvWindowsWindow.h b/ImguiTesting/src/mvWindowsWindow.h new file mode 100644 index 000000000..c6083bc1f --- /dev/null +++ b/ImguiTesting/src/mvWindowsWindow.h @@ -0,0 +1,61 @@ +#pragma once + +#include "imgui.h" +#include "imgui_impl_win32.h" +#include "imgui_impl_dx11.h" +#include +#define DIRECTINPUT_VERSION 0x0800 +#include +#include + +class mvWindowsWindow +{ + +public: + + bool m_running = true; + + mvWindowsWindow(); + + virtual void show(); + + virtual void setup(); + virtual void prerender(); + virtual void postrender(); + virtual void cleanup(); + +private: + + bool CreateDeviceD3D(HWND hWnd); + + void CleanupDeviceD3D(); + + void CreateRenderTarget(); + + void CleanupRenderTarget(); + +public: + + static ID3D11Device* getDevice() { return s_pd3dDevice; } + + static LRESULT CALLBACK HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + + static LRESULT CALLBACK HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + + LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; + +private: + + HWND m_hwnd; + WNDCLASSEX m_wc; + MSG m_msg; + +private: + + // Data + static ID3D11Device* s_pd3dDevice; + static ID3D11DeviceContext* s_pd3dDeviceContext; + static IDXGISwapChain* s_pSwapChain; + static ID3D11RenderTargetView* s_mainRenderTargetView; + +}; diff --git a/LICENSE b/LICENSE index 976c0f40f..c6c4a9cd7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Dear PyGui, LLC +Copyright (c) 2020 Raylock, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md deleted file mode 100644 index 40531a05f..000000000 --- a/README.md +++ /dev/null @@ -1,211 +0,0 @@ -

-
- Dear PyGui logo -

- -

A modern, fast and powerful GUI framework for Python

- -

- -

- Python versions - PYPI - Downloads - MIT License -

- -

- static-analysis - static-analysis - Deployment - Documentation Status -

- -

- -

- Features • - Installation • - How To Use • - Demo • - Resources • - Support • - Tech stack • - Credits • - License • - Gallery -

- -

- -
![Themes](https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/linuxthemes.PNG) - -## Features -- **Modern look** — Complete theme and style control -- **Great performance** — GPU-based rendering and efficient C/C++ code -- **Stable operation** — Asynchronous function support -- **Fast graphs** — Display over 1 million datapoints at 60 fps, zoom and pan -- **Node editor** — Intuitive user interaction -- **Built-in demo** — Quickly learn all features -- **Developer tools** — Theme and resource inspection, runtime metrics, debugger -- **Cross-platform** — Windows, Linux, MacOS -- **MIT license** - -

-

-          -

-

- -

-

-         -

-

- -## Installation - -Ensure you have at least Python 3.8 64bit. - ``` - pip install dearpygui - or - pip3 install dearpygui - ``` - -## How to use? - -Using Dear PyGui is as simple as the following Python script. - -```Python -import dearpygui.dearpygui as dpg - -def save_callback(): - print("Save Clicked") - -dpg.create_context() -dpg.create_viewport() -dpg.setup_dearpygui() - -with dpg.window(label="Example Window"): - dpg.add_text("Hello world") - dpg.add_button(label="Save", callback=save_callback) - dpg.add_input_text(label="string") - dpg.add_slider_float(label="float") - -dpg.show_viewport() -dpg.start_dearpygui() -dpg.destroy_context() -``` -
-

Dear PyGui example window

- -## Demo -The built-in demo shows all of Dear PyGui's functionality. To run the demo, you can run: - -```bash -python -m dearpygui.demo -``` - -Or you can use [this code](https://dearpygui.readthedocs.io/en/latest/tutorials/first-steps.html#demo) to run the demo. The following impression shows a few, but not nearly all, of the available widgets and features. Since the Python code of the demo can be inspected, you can leverage the demo code to build your own apps. -

-

Dear PyGui demo

- -## Resources - -- [Documentation / Tutorials](https://dearpygui.readthedocs.io/en/latest/index.html) :books: -- [Project status](https://github.com/hoffstadt/DearPyGui/wiki/What's-going-on%3F) -- [FAQ](https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq) -- [Feature Tracker](https://github.com/hoffstadt/DearPyGui/issues?q=is%3Aissue+is%3Aopen+label%3A%22type%3A+feature%22) -- [Bug Tracker](https://github.com/hoffstadt/DearPyGui/issues?q=is%3Aissue+is%3Aopen+label%3A%22type%3A+bug%22) -- [Useful code snippets demonstrating best practices](https://github.com/my1e5/dpg-examples) -- [Showcase apps including source code](https://github.com/hoffstadt/DearPyGui/wiki/Dear-PyGui-Showcase) :star: -- [Showcase apps made with older versions of Dear PyGui](https://github.com/hoffstadt/DearPyGui/wiki/Showcase-apps-older-Dear-PyGui-versions) -- [Useful tools and widgets](https://github.com/hoffstadt/DearPyGui/wiki/Tools-and-Widgets) - -## Support - -If you are having issues or want to help, here are some places you can go. - - [Discord Forum](https://discord.gg/tyE7Gu4) 💬 - - [Reddit](https://www.reddit.com/r/DearPyGui/) - -[![Chat on Discord](https://img.shields.io/discord/736279277242417272?logo=discord)](https://discord.gg/tyE7Gu4)       [![Reddit](https://img.shields.io/reddit/subreddit-subscribers/dearpygui?label=r%2Fdearpygui)](https://www.reddit.com/r/DearPyGui/) - -## Tech stack -Dear PyGui is built on top of Dear ImGui, including the [ImPlot](https://github.com/epezent/implot) and [imnodes](https://github.com/Nelarius/imnodes) extensions, and is fundamentally different than other Python GUI frameworks. Under the hood, it uses the immediate mode paradigm and your computer's GPU to facilitate extremely dynamic interfaces. In the same manner Dear ImGui provides a simple way to create tools for game developers, Dear PyGui provides a simple way for python developers to create quick and powerful GUIs for scripts. Dear PyGui is written in C/C++ resulting in highly performant Python applications. Dear PyGui is currently supported on the following platforms. -
- -| Platform | Graphics API | Newest Version | -|:---------|:-------------|:---------------| -| **Windows 10** | _DirectX 11_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | -| **macOS** | _Metal_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | -| **Linux** | _OpenGL 3_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | -| **Raspberry Pi 4** | _OpenGL ES_ | [![PYPI](https://img.shields.io/badge/pypi-v1.6-blue)](https://img.shields.io/badge/pypi-v1.6-blue) | - - -## Credits - -- Developed by [Jonathan Hoffstadt](https://github.com/hoffstadt), [Preston Cothren](https://github.com/Pcothren) and every direct or indirect contributor. - -- [Omar Cornut](http://www.miracleworld.net/) for all his incredible work on [Dear ImGui](https://github.com/ocornut/imgui). - -- [Evan Pezent](http://evanpezent.com/) for all his work on [ImPlot](https://github.com/epezent/implot). - -- [Johann Muszynski](https://github.com/Nelarius) for all of his work on [imnodes](https://github.com/Nelarius/imnodes). - -## License -Dear PyGui is licensed under the [MIT License](https://github.com/hoffstadt/DearPyGui/blob/master/LICENSE). - -## Sponsor -Continued maintenance and development are a full-time endeavor which we would like to sustain and grow. Ongoing development is financially supported by users and private sponsors. If you enjoy Dear PyGui please consider becoming a [sponsor](https://github.com/hoffstadt/DearPyGui/wiki/Sponsors) or buy us a [cup of coffee](https://www.buymeacoffee.com/DearPyGui). - -      - -## Gallery - -#### Plotting/Graphing -_Dear PyGui_ includes a plotting API built with [ImPlot](https://github.com/epezent/implot) - -         - -         - -         - -         - - -#### Node Editor -_Dear PyGui_ includes a node editor built with [imnodes](https://github.com/Nelarius/imnodes) -![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/nodes2.png) - - -#### Canvas -_Dear PyGui_ includes a drawing API to create custom drawings, plot, and even 2D games. -![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/tetris.png) - - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/3d.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/nodes1.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/space.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/snake.gif) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/drawing.png) - -
![BasicUsageExample](https://github.com/hoffstadt/DearPyGui/blob/assets/canvas.png?raw=true) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/nodes3.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/3d1.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/game1.png) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/mandlebrot.gif) - - ![](https://github.com/hoffstadt/DearPyGui/blob/assets/readme/nodes4.png) - -## SAST Tools - -[PVS-Studio](https://pvs-studio.com/en/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) - static analyzer for C, C++, C#, and Java code. diff --git a/assets/.gitignore b/Resources/.gitignore similarity index 72% rename from assets/.gitignore rename to Resources/.gitignore index 11cf88312..4427f4e71 100644 --- a/assets/.gitignore +++ b/Resources/.gitignore @@ -3,5 +3,4 @@ !*.otf !.gitignore !*.py -!*.png -!*.ico \ No newline at end of file +!*.png \ No newline at end of file diff --git a/assets/NotoSerifCJKjp-Medium.otf b/Resources/NotoSerifCJKjp-Medium.otf similarity index 100% rename from assets/NotoSerifCJKjp-Medium.otf rename to Resources/NotoSerifCJKjp-Medium.otf diff --git a/thirdparty/DearPyGui_Ext/Resources/Retron2000.ttf b/Resources/Retron2000.ttf similarity index 100% rename from thirdparty/DearPyGui_Ext/Resources/Retron2000.ttf rename to Resources/Retron2000.ttf diff --git a/assets/SpriteMapExample.png b/Resources/SpriteMapExample.png similarity index 100% rename from assets/SpriteMapExample.png rename to Resources/SpriteMapExample.png diff --git a/Scripts/BuildLocalWheelLinux.sh b/Scripts/BuildLocalWheelLinux.sh new file mode 100755 index 000000000..4cedfbad8 --- /dev/null +++ b/Scripts/BuildLocalWheelLinux.sh @@ -0,0 +1,24 @@ +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --with-pydebug --enable-shared +make +cd ../../.. + +cd .. +mkdir -p cmake-build-local +cd cmake-build-local +rm -rf * +cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=0 -DMVDPG_VERSION=local_build +make -j +cd .. + +cd Distribution +python3 BuildPythonWheel.py ../cmake-build-local/DearPyGui/core.so 0 +python3 -m ensurepip +python3 -m pip install --upgrade pip +python3 -m pip install twine --upgrade +python3 -m pip install wheel +python3 -m setup bdist_wheel --plat-name manylinux1_x86_64 --dist-dir ../dist +cd .. +cd Scripts diff --git a/Scripts/BuildLocalWheelMacArm.sh b/Scripts/BuildLocalWheelMacArm.sh new file mode 100644 index 000000000..b7881688c --- /dev/null +++ b/Scripts/BuildLocalWheelMacArm.sh @@ -0,0 +1,24 @@ +brew install openssl xz gdbm +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) --with-openssl=$(brew --prefix openssl) +make +make install + +cd ../../.. +mkdir cmake-build-local +cd cmake-build-local +cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=0 -DMVDPG_VERSION=local_build +cd .. +cmake --build cmake-build-local --config Release + +cd Distribution +"../Dependencies/cpython/debug/python.exe" BuildPythonWheel.py ../cmake-build-local/DearPyGui/core.so 0 +"../Dependencies/cpython/debug/python.exe" -m ensurepip +"../Dependencies/cpython/debug/python.exe" -m pip install --upgrade pip +"../Dependencies/cpython/debug/python.exe" -m pip install twine --upgrade +"../Dependencies/cpython/debug/python.exe" -m pip install wheel +"../Dependencies/cpython/debug/python.exe" -m setup bdist_wheel --plat-name macosx-11.0-arm64 --dist-dir ../dist +cd .. +cd Scripts diff --git a/Scripts/BuildLocalWheelMacIntel.sh b/Scripts/BuildLocalWheelMacIntel.sh new file mode 100755 index 000000000..afb443fd6 --- /dev/null +++ b/Scripts/BuildLocalWheelMacIntel.sh @@ -0,0 +1,24 @@ +brew install openssl xz gdbm +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) --with-openssl=$(brew --prefix openssl) +make +make install + +cd ../../.. +mkdir cmake-build-local +cd cmake-build-local +cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=0 -DMVDPG_VERSION=local_build +cd .. +cmake --build cmake-build-local --config Release + +cd Distribution +"../Dependencies/cpython/debug/python.exe" BuildPythonWheel.py ../cmake-build-local/DearPyGui/core.so 0 +"../Dependencies/cpython/debug/python.exe" -m ensurepip +"../Dependencies/cpython/debug/python.exe" -m pip install --upgrade pip +"../Dependencies/cpython/debug/python.exe" -m pip install twine --upgrade +"../Dependencies/cpython/debug/python.exe" -m pip install wheel +"../Dependencies/cpython/debug/python.exe" -m setup bdist_wheel --plat-name macosx-10.6-x86_64 --dist-dir ../dist +cd .. +cd Scripts diff --git a/Scripts/BuildLocalWheelRPi.sh b/Scripts/BuildLocalWheelRPi.sh new file mode 100644 index 000000000..ca2332205 --- /dev/null +++ b/Scripts/BuildLocalWheelRPi.sh @@ -0,0 +1,23 @@ +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --enable-shared +make +cd ../../.. + +mkdir -p cmake-build-local +cd cmake-build-local +rm -rf * +cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=0 -DMVDPG_VERSION=local_build +make -j3 +cd .. + +cd Distribution +python3 BuildPythonWheel.py ../cmake-build-local/DearPyGui/core.so 0 +python3 -m ensurepip +python3 -m pip install --upgrade pip +python3 -m pip install twine --upgrade +python3 -m pip install wheel +python3 -m setup bdist_wheel --plat-name linux_armv7l --dist-dir ../dist +cd .. +cd Scripts diff --git a/Scripts/BuildLocalWheelWindows.bat b/Scripts/BuildLocalWheelWindows.bat new file mode 100644 index 000000000..c3554b655 --- /dev/null +++ b/Scripts/BuildLocalWheelWindows.bat @@ -0,0 +1,29 @@ +@echo off + +rem get current this batch file directory +set dir=%~dp0 + +rem clean up previous build +echo Cleaning previous python builds +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -p x64 -t CleanAll + +rem build python +echo Building python in Debug and Release for x64 +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -p x64 -t Build + +cd .. +mkdir cmake-build-local +cd cmake-build-local +cmake .. -G "Visual Studio 16 2019" -A "x64" -DMVDIST_ONLY=True -DMVPY_VERSION=0 -DMVDPG_VERSION=local_build +cd .. +cmake --build cmake-build-local --config "Release" + +cd Distribution +call "../Dependencies/cpython/PCbuild/amd64/python.exe" BuildPythonWheel.py ..\cmake-build-local\DearPyGui\Release\core.pyd 0 +call "../Dependencies/cpython/PCbuild/amd64/python.exe" -m ensurepip +call "../Dependencies/cpython/PCbuild/amd64/python.exe" -m pip install --upgrade pip +call "../Dependencies/cpython/PCbuild/amd64/python.exe" -m pip install twine +call "../Dependencies/cpython/PCbuild/amd64/python.exe" -m pip install wheel +call "../Dependencies/cpython/PCbuild/amd64/python.exe" -m setup bdist_wheel --plat-name win_amd64 --dist-dir ../dist +cd .. +cd Scripts \ No newline at end of file diff --git a/Scripts/BuildPythonForLinux.sh b/Scripts/BuildPythonForLinux.sh new file mode 100755 index 000000000..53123c356 --- /dev/null +++ b/Scripts/BuildPythonForLinux.sh @@ -0,0 +1,5 @@ +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --with-pydebug --enable-shared +make diff --git a/Scripts/BuildPythonForMac.sh b/Scripts/BuildPythonForMac.sh new file mode 100755 index 000000000..dbc090eb0 --- /dev/null +++ b/Scripts/BuildPythonForMac.sh @@ -0,0 +1,6 @@ +cd ../Dependencies/cpython +mkdir debug +cd debug +../configure --with-pydebug --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) +make +make install diff --git a/scripts/BuildPythonForWindows.bat b/Scripts/BuildPythonForWindows.bat old mode 100644 new mode 100755 similarity index 56% rename from scripts/BuildPythonForWindows.bat rename to Scripts/BuildPythonForWindows.bat index 52858ff56..ac3b60744 --- a/scripts/BuildPythonForWindows.bat +++ b/Scripts/BuildPythonForWindows.bat @@ -9,19 +9,19 @@ if "%~1"=="--ci" goto Release :Debug rem clean up previous build echo Cleaning previous python builds -call "%dir%..\thirdparty\cpython\PCbuild\build.bat" -c Debug -p x64 -t CleanAll +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -c Debug -p x64 -t CleanAll rem build python echo Building python in Debug and Release for x64 -call "%dir%..\thirdparty\cpython\PCbuild\build.bat" -c Debug -p x64 -t Build +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -c Debug -p x64 -t Build :Release rem clean up previous build echo Cleaning previous python builds -call "%dir%..\thirdparty\cpython\PCbuild\build.bat" -p x64 -t CleanAll +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -p x64 -t CleanAll rem build python echo Building python in Debug and Release for x64 -call "%dir%..\thirdparty\cpython\PCbuild\build.bat" -p x64 -t Build +call "%dir%..\Dependencies\cpython\PCbuild\build.bat" -p x64 -t Build pause \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 000000000..cd41134aa --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,233 @@ +version: 0.6.{build} + +branches: + only: + - master +build: + verbosity: minimal + +# Do not build on tags +skip_tags: true + +environment: + + pypi_password: + secure: tKYM1oHNwH7n+FO1exDSPzz76oio0iXtsfkZ0o7kuOY= + + git_token: + secure: kRikZcYHTs5za4HnpeKZfM8dAD6emA68ZpDDkS+hvXa9IEPOAR8C7LCFnmKMTful + + matrix: + + - APPVEYOR_BUILD_WORKER_IMAGE: macos-mojave + ARCH: "x64" + CONFIG: Release + PYVER: 36 + PYLOC: "python" + PYSTACK: "3.6" + PYFULLVERSION: "3.6.12" + MACOS: "true" + + - APPVEYOR_BUILD_WORKER_IMAGE: Ubuntu + ARCH: "x64" + CONFIG: Release + PYVER: 36 + PYLOC: "python" + PYSTACK: "3.6" + PYFULLVERSION: "3.6.12" + + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + GENERATOR: "Visual Studio 16 2019" + ARCH: "x64" + CONFIG: Release + PYVER: 36 + PYLOC: "C:/Python36-x64/python.exe" + PYSTACK: "3.6" + PYFULLVERSION: "3.6.12" + + - APPVEYOR_BUILD_WORKER_IMAGE: macos-mojave + ARCH: "x64" + CONFIG: Release + PYVER: 37 + PYLOC: "python" + PYSTACK: "3.7" + PYFULLVERSION: "3.7.9" + MACOS: "true" + + - APPVEYOR_BUILD_WORKER_IMAGE: Ubuntu + ARCH: "x64" + CONFIG: Release + PYVER: 37 + PYLOC: "python" + PYSTACK: "3.7" + PYFULLVERSION: "3.7.9" + + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + GENERATOR: "Visual Studio 16 2019" + ARCH: "x64" + CONFIG: Release + PYVER: 37 + PYLOC: "C:/Python37-x64/python.exe" + PYSTACK: "3.7" + PYFULLVERSION: "3.7.9" + + - APPVEYOR_BUILD_WORKER_IMAGE: macos-mojave + ARCH: "x64" + CONFIG: Release + PYVER: 38 + PYLOC: "python" + PYSTACK: "3.8" + PYFULLVERSION: "3.8.6" + MACOS: "true" + + - APPVEYOR_BUILD_WORKER_IMAGE: Ubuntu + ARCH: "x64" + CONFIG: Release + PYVER: 38 + PYLOC: "python" + PYSTACK: "3.8" + PYFULLVERSION: "3.8.6" + + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + GENERATOR: "Visual Studio 16 2019" + ARCH: "x64" + CONFIG: Release + PYVER: 38 + PYLOC: "C:/Python38-x64/python.exe" + PYSTACK: "3.8" + PYFULLVERSION: "3.8.5" + + - APPVEYOR_BUILD_WORKER_IMAGE: macos-mojave + ARCH: "x64" + CONFIG: Release + PYVER: 39 + PYLOC: "python" + PYSTACK: "3.9" + PYFULLVERSION: "3.9.1" + MACOS: "true" + + - APPVEYOR_BUILD_WORKER_IMAGE: Ubuntu + ARCH: "x64" + CONFIG: Release + PYVER: 39 + PYLOC: "python" + PYSTACK: "3.9" + PYFULLVERSION: "3.9.1" + + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + GENERATOR: "Visual Studio 16 2019" + ARCH: "x64" + CONFIG: Release + PYVER: 39 + PYLOC: "C:/Python39-x64/python.exe" + PYSTACK: "3.9" + PYFULLVERSION: "3.9.0" + PYDOCRUN: "true" + +matrix: + fast_finish: true + +stack: + python %PYSTACK% + +# actual build +build_script: + + # Windows + - cmd: git submodule update --init --recursive ./Dependencies/imgui + - cmd: git submodule update --init --recursive ./Dependencies/freetype + - cmd: git submodule update --init --recursive ./Dependencies/ImGuiFileDialog + - cmd: mkdir cmake-build-release + - cmd: cd cmake-build-Release + - cmd: cmake .. -G "%GENERATOR%" -A "%ARCH%" -DMVDIST_ONLY=True -DMVPY_VERSION=%PYVER% -DMVDPG_VERSION=%APPVEYOR_BUILD_VERSION% + - cmd: cd .. + - cmd: cmake --build cmake-build-release --config "%CONFIG%" + + # Ubuntu Only + - sh: | + if [ "$MACOS" = "" ]; then + sudo apt-get update + sudo apt-get install libglu1-mesa-dev libgl1-mesa-dev xorg-dev libxrandr-dev -y + sudo apt-get install libfreetype6-dev -y + sudo apt-get install libharfbuzz-dev -y + fi + + # Ubuntu & MacOS + - sh: git submodule update --init --recursive ./Dependencies/imgui + - sh: git submodule update --init --recursive ./Dependencies/freetype + - sh: git submodule update --init --recursive ./Dependencies/ImGuiFileDialog + - sh: git submodule update --init --recursive ./Dependencies/glfw + - sh: mkdir cmake-build-release + - sh: cd cmake-build-release + - sh: | + if [ "$MACOS" = "" ]; then + cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=${PYVER} -DMVDPG_VERSION=${APPVEYOR_BUILD_VERSION} -DBUILD_SHARED_LIBS:BOOL=true + else + cmake .. -DMVDIST_ONLY=True -DMVPY_VERSION=${PYVER} -DMVDPG_VERSION=${APPVEYOR_BUILD_VERSION} + fi + - sh: cd .. + - sh: cmake --build cmake-build-release --config "${CONFIG}" + +on_success: + + - cd Distribution + + # Windows + - cmd: call %PYLOC% -m pip install --upgrade pip + - cmd: call %PYLOC% BuildPythonWheel.py C:\projects\dearpygui\cmake-build-release\DearPyGui\Release\core.pyd "%APPVEYOR_BUILD_VERSION%" + - cmd: call %PYLOC% -m pip install twine + - cmd: call %PYLOC% -m pip install wheel + - cmd: call %PYLOC% -m setup bdist_wheel --plat-name win_amd64 --dist-dir C:/projects/dearpygui/dist + - cmd: if "%APPVEYOR_REPO_COMMIT_MESSAGE:(test)=%" neq "%APPVEYOR_REPO_COMMIT_MESSAGE%" call %PYLOC% -m twine upload --repository testpypi C:/projects/dearpygui/dist/* -u RaylockLLC -p %pypi_password% --skip-existing + - cmd: if "%APPVEYOR_REPO_COMMIT_MESSAGE:(release)=%" neq "%APPVEYOR_REPO_COMMIT_MESSAGE%" call %PYLOC% -m twine upload --repository testpypi C:/projects/dearpygui/dist/* -u RaylockLLC -p %pypi_password% --skip-existing + - cmd: if "%APPVEYOR_REPO_COMMIT_MESSAGE:(release)=%" neq "%APPVEYOR_REPO_COMMIT_MESSAGE%" call %PYLOC% -m twine upload C:/projects/dearpygui/dist/* -u RaylockLLC -p %pypi_password% --skip-existing + + # deploy docs + - ps: | + if ( $env:APPVEYOR_REPO_COMMIT_MESSAGE -like "*(release)*" ) + { + if ( $env:PYDOCRUN -like "*true*" ) + { + cd .. + git checkout gh-pages + Add-Content -Path "$HOME\.git-credentials" -Value "https://$($env:git_token):x-oauth-basic@github.com`n" -NoNewline + C:\Python39-x64\python.exe -m pip install C:\projects\dearpygui\dist\dearpygui-$env:APPVEYOR_BUILD_VERSION-cp39-cp39-win_amd64.whl + C:\Python39-x64\python.exe -m pip install pdoc3 + C:\Python39-x64\python.exe -m pdoc --html dearpygui -f + C:\Python39-x64\python.exe html_script.py + git config --global credential.helper store + git config --global user.email "jonathanhoffstadt@yahoo.com" + git config --global user.name "Jonathan Hoffstadt" + git commit -a -m "Update Docs for $env:APPVEYOR_BUILD_VERSION" + git push origin gh-pages -q + } + } + + # Ubuntu & MacOS + - sh: | + ${PYLOC} -m pip install --upgrade pip + if [ "$MACOS" = "" ]; then + ${PYLOC} BuildPythonWheel.py /home/appveyor/projects/dearpygui/cmake-build-release/DearPyGui/core.so ${APPVEYOR_BUILD_VERSION} + ${PYLOC} -m pip install twine --upgrade + ${PYLOC} -m pip install wheel + ${PYLOC} -m setup bdist_wheel --plat-name manylinux1_x86_64 --dist-dir /home/appveyor/projects/dearpygui/dist + if [[ "${APPVEYOR_REPO_COMMIT_MESSAGE}" == *"(test)"* ]]; then + ${PYLOC} -m twine upload --repository testpypi /home/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + fi + if [[ "${APPVEYOR_REPO_COMMIT_MESSAGE}" == *"(release)"* ]]; then + ${PYLOC} -m twine upload --repository testpypi /home/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + ${PYLOC} -m twine upload /home/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + fi + else + ${PYLOC} BuildPythonWheel.py /Users/appveyor/projects/dearpygui/cmake-build-release/DearPyGui/core.so ${APPVEYOR_BUILD_VERSION} + ${PYLOC} -m pip install twine --upgrade + ${PYLOC} -m pip install wheel + ${PYLOC} -m setup bdist_wheel --plat-name macosx-10.6-x86_64 --dist-dir /Users/appveyor/projects/dearpygui/dist + if [[ "${APPVEYOR_REPO_COMMIT_MESSAGE}" == *"(test)"* ]]; then + ${PYLOC} -m twine upload --repository testpypi /Users/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + fi + if [[ "${APPVEYOR_REPO_COMMIT_MESSAGE}" == *"(release)"* ]]; then + ${PYLOC} -m twine upload --repository testpypi /Users/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + ${PYLOC} -m twine upload /Users/appveyor/projects/dearpygui/dist/* -u RaylockLLC -p ${pypi_password} --skip-existing + fi + fi diff --git a/dearpygui/.gitignore b/dearpygui/.gitignore deleted file mode 100644 index 69eb1512b..000000000 --- a/dearpygui/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -* -!__init__.py -!.gitignore -!_dearpygui.pyi -!_dearpygui_RTD.py -!_deprecated.py -!_header.py -!dearpygui.py -!demo.py -!experimental.py -!type_info.py diff --git a/dearpygui/__init__.py b/dearpygui/__init__.py deleted file mode 100644 index fc80254b6..000000000 --- a/dearpygui/__init__.py +++ /dev/null @@ -1 +0,0 @@ -pass \ No newline at end of file diff --git a/dearpygui/_dearpygui.pyi b/dearpygui/_dearpygui.pyi deleted file mode 100644 index 4bb98661e..000000000 --- a/dearpygui/_dearpygui.pyi +++ /dev/null @@ -1,1934 +0,0 @@ -from typing import List, Any, Callable, Union, Tuple -from dearpygui._dearpygui import * - -########################################################## -# This file is generated automatically by mvPythonParser # -########################################################## - -# ~ Dear PyGui Version: master -def add_2d_histogram_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', xbins: int ='', ybins: int ='', xmin_range: float ='', xmax_range: float ='', ymin_range: float ='', ymax_range: float ='', density: bool ='', outliers: bool ='', col_major: bool ='') -> Union[int, str]: - """Adds a 2d histogram series.""" - ... - -def add_3d_slider(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[float], Tuple[float, ...]] ='', max_x: float ='', max_y: float ='', max_z: float ='', min_x: float ='', min_y: float ='', min_z: float ='', scale: float ='') -> Union[int, str]: - """Adds a 3D box slider.""" - ... - -def add_alias(alias : str, item : Union[int, str]) -> None: - """Adds an alias.""" - ... - -def add_area_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', fill: Union[List[int], Tuple[int, ...]] ='', contribute_to_bounds: bool ='') -> Union[int, str]: - """Adds an area series to a plot.""" - ... - -def add_axis_tag(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', default_value: float ='', color: Union[List[int], Tuple[int, ...]] ='', auto_rounding: bool ='') -> Union[int, str]: - """Adds custom labels to axes.""" - ... - -def add_bar_group_series(values : Union[List[float], Tuple[float, ...]], label_ids : Union[List[str], Tuple[str, ...]], group_size : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', group_width: float ='', shift: int ='', horizontal: bool ='', stacked: bool ='') -> Union[int, str]: - """Adds a bar groups series to a plot.""" - ... - -def add_bar_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', weight: float ='', horizontal: bool ='') -> Union[int, str]: - """Adds a bar series to a plot.""" - ... - -def add_bool_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a bool value.""" - ... - -def add_button(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', small: bool ='', arrow: bool ='', direction: int ='', repeat: bool ='') -> Union[int, str]: - """Adds a button.""" - ... - -def add_candle_series(dates : Union[List[float], Tuple[float, ...]], opens : Union[List[float], Tuple[float, ...]], closes : Union[List[float], Tuple[float, ...]], lows : Union[List[float], Tuple[float, ...]], highs : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', bull_color: Union[List[int], Tuple[int, ...]] ='', bear_color: Union[List[int], Tuple[int, ...]] ='', weight: float ='', tooltip: bool ='', time_unit: int ='') -> Union[int, str]: - """Adds a candle series to a plot.""" - ... - -def add_char_remap(source : int, target : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Remaps a character.""" - ... - -def add_checkbox(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: bool ='') -> Union[int, str]: - """Adds a checkbox.""" - ... - -def add_child_window(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', border: bool ='', autosize_x: bool ='', autosize_y: bool ='', no_scrollbar: bool ='', horizontal_scrollbar: bool ='', menubar: bool ='', no_scroll_with_mouse: bool ='', flattened_navigation: bool ='', always_use_window_padding: bool ='', resizable_x: bool ='', resizable_y: bool ='', always_auto_resize: bool ='', frame_style: bool ='', auto_resize_x: bool ='', auto_resize_y: bool ='') -> Union[int, str]: - """Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended.""" - ... - -def add_clipper(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region.""" - ... - -def add_collapsing_header(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', closable: bool ='', default_open: bool ='', open_on_double_click: bool ='', open_on_arrow: bool ='', leaf: bool ='', bullet: bool ='') -> Union[int, str]: - """Adds a collapsing header to add items to. Must be closed with the end command.""" - ... - -def add_color_button(default_value : Union[List[int], Tuple[int, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', no_alpha: bool ='', no_border: bool ='', no_drag_drop: bool ='', alpha_preview: int ='', no_tooltip: bool ='') -> Union[int, str]: - """Adds a color button.""" - ... - -def add_color_edit(default_value : Union[List[int], Tuple[int, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', no_alpha: bool ='', no_picker: bool ='', no_options: bool ='', no_small_preview: bool ='', no_inputs: bool ='', no_tooltip: bool ='', no_label: bool ='', no_drag_drop: bool ='', alpha_bar: bool ='', alpha_preview: int ='', display_mode: int ='', display_type: int ='', input_mode: int ='') -> Union[int, str]: - """Adds an RGBA color editor. Left clicking the small color preview will provide a color picker. Click and draging the small color preview will copy the color to be applied on any other color widget.""" - ... - -def add_color_picker(default_value : Union[List[int], Tuple[int, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', no_alpha: bool ='', no_side_preview: bool ='', no_small_preview: bool ='', no_inputs: bool ='', no_tooltip: bool ='', no_label: bool ='', alpha_bar: bool ='', display_rgb: bool ='', display_hsv: bool ='', display_hex: bool ='', picker_mode: int ='', alpha_preview: int ='', display_type: int ='', input_mode: int ='') -> Union[int, str]: - """Adds an RGB color picker. Right click the color picker for options. Click and drag the color preview to copy the color and drop on any other color widget to apply. Right Click allows the style of the color picker to be changed.""" - ... - -def add_color_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Union[List[float], Tuple[float, ...]] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a color value.""" - ... - -def add_colormap(colors : List[Union[List[int], Tuple[int, ...]]], qualitative : bool, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a legend that pairs colors with normalized value 0.0->1.0. Each color will be This is typically used with a heat series. (ex. [[0, 0, 0, 255], [255, 255, 255, 255]] will be mapped to a soft transition from 0.0-1.0)""" - ... - -def add_colormap_button(default_value : Union[List[int], Tuple[int, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='') -> Union[int, str]: - """Adds a button that a color map can be bound to.""" - ... - -def add_colormap_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a colormap registry.""" - ... - -def add_colormap_scale(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', colormap: Union[int, str] ='', min_scale: float ='', max_scale: float ='', format: str ='', reverse_dir: bool ='', mirror: bool ='') -> Union[int, str]: - """Adds a legend that pairs values with colors. This is typically used with a heat series. """ - ... - -def add_colormap_slider(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='') -> Union[int, str]: - """Adds a color slider that a color map can be bound to.""" - ... - -def add_combo(items : Union[List[str], Tuple[str, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: str ='', popup_align_left: bool ='', no_arrow_button: bool ='', no_preview: bool ='', fit_width: bool ='', height_mode: int ='') -> Union[int, str]: - """Adds a combo dropdown that allows a user to select a single option from a drop down window. All items will be shown as selectables on the dropdown.""" - ... - -def add_custom_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], channel_count : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', callback: Callable ='', show: bool ='', y1: Any ='', y2: Any ='', y3: Any ='', tooltip: bool ='', no_fit: bool ='') -> Union[int, str]: - """Adds a custom series to a plot. New in 1.6.""" - ... - -def add_date_picker(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: dict ='', level: int ='') -> Union[int, str]: - """Adds a date picker.""" - ... - -def add_digital_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a digital series to a plot. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot.""" - ... - -def add_double4_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Any ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a double value.""" - ... - -def add_double_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: float ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a double value.""" - ... - -def add_drag_double(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', format: str ='', speed: float ='', min_value: float ='', max_value: float ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag for a single double value. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_doublex(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Any ='', size: int ='', format: str ='', speed: float ='', min_value: float ='', max_value: float ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag input for a set of double values up to 4. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_float(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', format: str ='', speed: float ='', min_value: float ='', max_value: float ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_floatx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[float], Tuple[float, ...]] ='', size: int ='', format: str ='', speed: float ='', min_value: float ='', max_value: float ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag input for a set of float values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_int(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: int ='', format: str ='', speed: float ='', min_value: int ='', max_value: int ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_intx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[int], Tuple[int, ...]] ='', size: int ='', format: str ='', speed: float ='', min_value: int ='', max_value: int ='', no_input: bool ='', clamped: bool ='') -> Union[int, str]: - """Adds drag input for a set of int values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_drag_line(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', callback: Callable ='', show: bool ='', default_value: float ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', show_label: bool ='', vertical: bool ='', delayed: bool ='', no_cursor: bool ='', no_fit: bool ='', no_inputs: bool ='') -> Union[int, str]: - """Adds a drag line to a plot.""" - ... - -def add_drag_payload(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', show: bool ='', drag_data: Any ='', drop_data: Any ='', payload_type: str ='') -> Union[int, str]: - """User data payload for drag and drop operations.""" - ... - -def add_drag_point(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', callback: Callable ='', show: bool ='', default_value: Any ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', show_label: bool ='', offset: Union[List[float], Tuple[float, ...]] ='', clamped: bool ='', delayed: bool ='', no_cursor: bool ='', no_fit: bool ='', no_inputs: bool ='') -> Union[int, str]: - """Adds a drag point to a plot.""" - ... - -def add_drag_rect(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', callback: Callable ='', show: bool ='', default_value: Any ='', color: Union[List[int], Tuple[int, ...]] ='', delayed: bool ='', no_cursor: bool ='', no_fit: bool ='', no_inputs: bool ='') -> Union[int, str]: - """Adds a drag rectangle to a plot.""" - ... - -def add_draw_layer(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', perspective_divide: bool ='', depth_clipping: bool ='', cull_mode: int ='') -> Union[int, str]: - """New in 1.1. Creates a layer useful for grouping drawlist items.""" - ... - -def add_draw_node(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate.""" - ... - -def add_drawlist(width : int, height : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='') -> Union[int, str]: - """Adds a drawing canvas.""" - ... - -def add_dynamic_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a dynamic texture.""" - ... - -def add_error_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], negative : Union[List[float], Tuple[float, ...]], positive : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', contribute_to_bounds: bool ='', horizontal: bool ='') -> Union[int, str]: - """Adds an error series to a plot.""" - ... - -def add_file_dialog(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', callback: Callable ='', show: bool ='', default_path: str ='', default_filename: str ='', file_count: int ='', modal: bool ='', directory_selector: bool ='', min_size: Union[List[int], Tuple[int, ...]] ='', max_size: Union[List[int], Tuple[int, ...]] ='', cancel_callback: Callable ='') -> Union[int, str]: - """Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary.""" - ... - -def add_file_extension(extension : str, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', custom_text: str ='', color: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Creates a file extension filter option in the file dialog.""" - ... - -def add_filter_set(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc])""" - ... - -def add_float4_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Union[List[float], Tuple[float, ...]] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a float4 value.""" - ... - -def add_float_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: float ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a float value.""" - ... - -def add_float_vect_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Union[List[float], Tuple[float, ...]] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a float vect value.""" - ... - -def add_font(file : str, size : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', pixel_snapH: bool ='', pixel_snapV: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds font to a font registry.""" - ... - -def add_font_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a font registry.""" - ... - -def add_group(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', horizontal: bool ='', horizontal_spacing: float ='', xoffset: float ='') -> Union[int, str]: - """Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. -Enable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.)""" - ... - -def add_handler_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a handler registry.""" - ... - -def add_heat_series(x : Union[List[float], Tuple[float, ...]], rows : int, cols : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', scale_min: float ='', scale_max: float ='', bounds_min: Any ='', bounds_max: Any ='', format: str ='', contribute_to_bounds: bool ='', col_major: bool ='') -> Union[int, str]: - """Adds a heat series to a plot.""" - ... - -def add_histogram_series(x : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', bins: int ='', bar_scale: float ='', min_range: float ='', max_range: float ='', cumulative: bool ='', density: bool ='', outliers: bool ='', horizontal: bool ='', contribute_to_bounds: bool ='') -> Union[int, str]: - """Adds a histogram series to a plot.""" - ... - -def add_image(texture_tag : Union[int, str], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', tint_color: Union[List[float], Tuple[float, ...]] ='', border_color: Union[List[float], Tuple[float, ...]] ='', uv_min: Union[List[float], Tuple[float, ...]] ='', uv_max: Union[List[float], Tuple[float, ...]] ='') -> Union[int, str]: - """Adds an image from a specified texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) for texture coordinates will generally display the entire texture.""" - ... - -def add_image_button(texture_tag : Union[int, str], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', tint_color: Union[List[float], Tuple[float, ...]] ='', background_color: Union[List[float], Tuple[float, ...]] ='', uv_min: Union[List[float], Tuple[float, ...]] ='', uv_max: Union[List[float], Tuple[float, ...]] ='') -> Union[int, str]: - """Adds an button with a texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) texture coordinates will generally display the entire texture""" - ... - -def add_image_series(texture_tag : Union[int, str], bounds_min : Union[List[float], Tuple[float, ...]], bounds_max : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', uv_min: Union[List[float], Tuple[float, ...]] ='', uv_max: Union[List[float], Tuple[float, ...]] ='', tint_color: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds an image series to a plot.""" - ... - -def add_inf_line_series(x : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', horizontal: bool ='') -> Union[int, str]: - """Adds an infinite line series to a plot.""" - ... - -def add_input_double(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', format: str ='', min_value: float ='', max_value: float ='', step: float ='', step_fast: float ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds input for an double. Useful when input float is not accurate enough. +/- buttons can be activated by setting the value of step.""" - ... - -def add_input_doublex(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Any ='', format: str ='', min_value: float ='', max_value: float ='', size: int ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds multi double input for up to 4 double values. Useful when input float mulit is not accurate enough.""" - ... - -def add_input_float(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', format: str ='', min_value: float ='', max_value: float ='', step: float ='', step_fast: float ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds input for an float. +/- buttons can be activated by setting the value of step.""" - ... - -def add_input_floatx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[float], Tuple[float, ...]] ='', format: str ='', min_value: float ='', max_value: float ='', size: int ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds multi float input for up to 4 float values.""" - ... - -def add_input_int(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: int ='', min_value: int ='', max_value: int ='', step: int ='', step_fast: int ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds input for an int. +/- buttons can be activated by setting the value of step.""" - ... - -def add_input_intx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[int], Tuple[int, ...]] ='', min_value: int ='', max_value: int ='', size: int ='', min_clamped: bool ='', max_clamped: bool ='', on_enter: bool ='', readonly: bool ='', accept_empty_input: bool ='', display_empty_value: bool ='') -> Union[int, str]: - """Adds multi int input for up to 4 integer values.""" - ... - -def add_input_text(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: str ='', hint: str ='', multiline: bool ='', no_spaces: bool ='', uppercase: bool ='', tab_input: bool ='', decimal: bool ='', hexadecimal: bool ='', readonly: bool ='', password: bool ='', scientific: bool ='', on_enter: bool ='', auto_select_all: bool ='', ctrl_enter_for_new_line: bool ='', no_horizontal_scroll: bool ='', always_overwrite: bool ='', no_undo_redo: bool ='', escape_clears_all: bool ='', elide_left: bool ='') -> Union[int, str]: - """Adds input for text.""" - ... - -def add_int4_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Union[List[int], Tuple[int, ...]] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a int4 value.""" - ... - -def add_int_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: int ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a int value.""" - ... - -def add_item_activated_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a activated handler.""" - ... - -def add_item_active_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a active handler.""" - ... - -def add_item_clicked_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a clicked handler.""" - ... - -def add_item_deactivated_after_edit_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a deactivated after edit handler.""" - ... - -def add_item_deactivated_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a deactivated handler.""" - ... - -def add_item_double_clicked_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a double click handler.""" - ... - -def add_item_edited_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds an edited handler.""" - ... - -def add_item_focus_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='', event_type: int ='') -> Union[int, str]: - """Adds a focus handler.""" - ... - -def add_item_handler_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds an item handler registry.""" - ... - -def add_item_hover_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='', event_type: int ='') -> Union[int, str]: - """Adds a hover handler.""" - ... - -def add_item_resize_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a resize handler.""" - ... - -def add_item_scroll_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a scroll handler.""" - ... - -def add_item_toggled_open_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='', two_way: bool ='') -> Union[int, str]: - """Adds a togged open handler.""" - ... - -def add_item_visible_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', callback: Callable ='', show: bool ='') -> Union[int, str]: - """Adds a visible handler.""" - ... - -def add_key_down_handler(key : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a key down handler.""" - ... - -def add_key_press_handler(key : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a key press handler.""" - ... - -def add_key_release_handler(key : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a key release handler.""" - ... - -def add_knob_float(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', min_value: float ='', max_value: float ='') -> Union[int, str]: - """Adds a knob that rotates based on change in x mouse position.""" - ... - -def add_line_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', segments: bool ='', loop: bool ='', skip_nan: bool ='', no_clip: bool ='', shaded: bool ='') -> Union[int, str]: - """Adds a line series to a plot.""" - ... - -def add_listbox(items : Union[List[str], Tuple[str, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: str ='', num_items: int ='') -> Union[int, str]: - """Adds a listbox. If height is not large enough to show all items a scroll bar will appear.""" - ... - -def add_loading_indicator(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', style: int ='', circle_count: int ='', speed: float ='', radius: float ='', thickness: float ='', color: Union[List[int], Tuple[int, ...]] ='', secondary_color: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds a rotating animated loading symbol.""" - ... - -def add_menu(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='') -> Union[int, str]: - """Adds a menu to an existing menu bar.""" - ... - -def add_menu_bar(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a menu bar to a window.""" - ... - -def add_menu_item(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: bool ='', shortcut: str ='', check: bool ='') -> Union[int, str]: - """Adds a menu item to an existing menu. Menu items act similar to selectables and has a bool value. When placed in a menu the checkmark will reflect its value.""" - ... - -def add_mouse_click_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse click handler.""" - ... - -def add_mouse_double_click_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse double click handler.""" - ... - -def add_mouse_down_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse down handler.""" - ... - -def add_mouse_drag_handler(button : int ='', threshold : float ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse drag handler.""" - ... - -def add_mouse_move_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse move handler.""" - ... - -def add_mouse_release_handler(button : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse release handler.""" - ... - -def add_mouse_wheel_handler(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', callback: Callable ='', show: bool ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a mouse wheel handler.""" - ... - -def add_node(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', draggable: bool ='') -> Union[int, str]: - """Adds a node to a node editor.""" - ... - -def add_node_attribute(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', attribute_type: int ='', shape: int ='', category: str ='') -> Union[int, str]: - """Adds a node attribute to a node.""" - ... - -def add_node_editor(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', callback: Callable ='', show: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', delink_callback: Callable ='', menubar: bool ='', minimap: bool ='', minimap_location: int ='') -> Union[int, str]: - """Adds a node editor.""" - ... - -def add_node_link(attr_1 : Union[int, str], attr_2 : Union[int, str], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a node link between 2 node attributes.""" - ... - -def add_pie_series(x : float, y : float, radius : float, values : Union[List[float], Tuple[float, ...]], labels : Union[List[str], Tuple[str, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', format: str ='', angle: float ='', normalize: bool ='', ignore_hidden: bool ='') -> Union[int, str]: - """Adds an pie series to a plot.""" - ... - -def add_plot(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', no_title: bool ='', no_menus: bool ='', no_box_select: bool ='', no_mouse_pos: bool ='', query: bool ='', query_color: Union[List[float], Tuple[float, ...]] ='', min_query_rects: int ='', max_query_rects: int ='', crosshairs: bool ='', equal_aspects: bool ='', no_inputs: bool ='', no_frame: bool ='', use_local_time: bool ='', use_ISO8601: bool ='', use_24hour_clock: bool ='', pan_button: int ='', pan_mod: int ='', context_menu_button: int ='', fit_button: int ='', box_select_button: int ='', box_select_mod: int ='', box_select_cancel_button: int ='', query_toggle_mod: int ='', horizontal_mod: int ='', vertical_mod: int ='', override_mod: int ='', zoom_mod: int ='', zoom_rate: int ='') -> Union[int, str]: - """Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier.""" - ... - -def add_plot_annotation(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', default_value: Any ='', offset: Union[List[float], Tuple[float, ...]] ='', color: Union[List[int], Tuple[int, ...]] ='', clamped: bool ='') -> Union[int, str]: - """Adds an annotation to a plot.""" - ... - -def add_plot_axis(axis : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', no_label: bool ='', no_gridlines: bool ='', no_tick_marks: bool ='', no_tick_labels: bool ='', no_initial_fit: bool ='', no_menus: bool ='', no_side_switch: bool ='', no_highlight: bool ='', opposite: bool ='', foreground_grid: bool ='', tick_format: str ='', scale: int ='', invert: bool ='', auto_fit: bool ='', range_fit: bool ='', pan_stretch: bool ='', lock_min: bool ='', lock_max: bool ='') -> Union[int, str]: - """Adds an axis to a plot.""" - ... - -def add_plot_legend(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', location: int ='', horizontal: bool ='', sort: bool ='', outside: bool ='', no_highlight_item: bool ='', no_highlight_axis: bool ='', no_menus: bool ='', no_buttons: bool ='') -> Union[int, str]: - """Adds a plot legend to a plot.""" - ... - -def add_progress_bar(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', overlay: str ='', default_value: float ='') -> Union[int, str]: - """Adds a progress bar.""" - ... - -def add_radio_button(items : Union[List[str], Tuple[str, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: str ='', horizontal: bool ='') -> Union[int, str]: - """Adds a set of radio buttons. If items keyword is empty, nothing will be shown.""" - ... - -def add_raw_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', format: int ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a raw texture.""" - ... - -def add_scatter_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', no_clip: bool ='') -> Union[int, str]: - """Adds a scatter series to a plot.""" - ... - -def add_selectable(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: bool ='', span_columns: bool ='', disable_popup_close: bool ='', select_on_nav: bool ='') -> Union[int, str]: - """Adds a selectable. Similar to a button but can indicate its selected state.""" - ... - -def add_separator(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds a horizontal line separator. Use 'label' parameter to add text and mvStyleVar_SeparatorText* elements to style it.""" - ... - -def add_series_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: Any ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a plot series value.""" - ... - -def add_shade_series(x : Union[List[float], Tuple[float, ...]], y1 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', y2: Any ='') -> Union[int, str]: - """Adds a shade series to a plot.""" - ... - -def add_simple_plot(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[float], Tuple[float, ...]] ='', overlay: str ='', histogram: bool ='', autosize: bool ='', min_scale: float ='', max_scale: float ='') -> Union[int, str]: - """Adds a simple plot for visualization of a 1 dimensional set of values.""" - ... - -def add_slider_double(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', vertical: bool ='', no_input: bool ='', clamped: bool ='', min_value: float ='', max_value: float ='', format: str ='') -> Union[int, str]: - """Adds slider for a single double value. Useful when slider float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_slider_doublex(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Any ='', size: int ='', no_input: bool ='', clamped: bool ='', min_value: float ='', max_value: float ='', format: str ='') -> Union[int, str]: - """Adds multi slider for up to 4 double values. Usueful for when multi slide float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_slider_float(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: float ='', vertical: bool ='', no_input: bool ='', clamped: bool ='', min_value: float ='', max_value: float ='', format: str ='') -> Union[int, str]: - """Adds slider for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_slider_floatx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[float], Tuple[float, ...]] ='', size: int ='', no_input: bool ='', clamped: bool ='', min_value: float ='', max_value: float ='', format: str ='') -> Union[int, str]: - """Adds multi slider for up to 4 float values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_slider_int(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: int ='', vertical: bool ='', no_input: bool ='', clamped: bool ='', min_value: int ='', max_value: int ='', format: str ='') -> Union[int, str]: - """Adds slider for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_slider_intx(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', enabled: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: Union[List[int], Tuple[int, ...]] ='', size: int ='', no_input: bool ='', clamped: bool ='', min_value: int ='', max_value: int ='', format: str ='') -> Union[int, str]: - """Adds multi slider for up to 4 int values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes.""" - ... - -def add_spacer(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds a spacer item that can be used to help with layouts or can be used as a placeholder item.""" - ... - -def add_stage(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='') -> Union[int, str]: - """Adds a stage.""" - ... - -def add_stair_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', pre_step: bool ='', shaded: bool ='') -> Union[int, str]: - """Adds a stair series to a plot.""" - ... - -def add_static_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a static texture.""" - ... - -def add_stem_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', horizontal: bool ='') -> Union[int, str]: - """Adds a stem series to a plot.""" - ... - -def add_string_value(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', source: Union[int, str] ='', default_value: str ='', parent: Union[int, str] ='') -> Union[int, str]: - """Adds a string value.""" - ... - -def add_subplots(rows : int, columns : int, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', row_ratios: Union[List[float], Tuple[float, ...]] ='', column_ratios: Union[List[float], Tuple[float, ...]] ='', no_title: bool ='', no_menus: bool ='', no_resize: bool ='', no_align: bool ='', share_series: bool ='', link_rows: bool ='', link_columns: bool ='', link_all_x: bool ='', link_all_y: bool ='', column_major: bool ='') -> Union[int, str]: - """Adds a collection of plots.""" - ... - -def add_synced_tables(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', filter_key: str ='') -> Union[int, str]: - """Links all tables that are immediate children of this container so that they share their state (mostly column sizes). Other children are rendered as is. This is an experimental feature, use with caution.""" - ... - -def add_tab(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drop_callback: Callable ='', show: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', closable: bool ='', no_tooltip: bool ='', order_mode: int ='', unsaved_document: bool ='', no_close_with_middle_click: bool ='', no_reorder: bool ='') -> Union[int, str]: - """Adds a tab to a tab bar.""" - ... - -def add_tab_bar(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', reorderable: bool ='', tab_list_popup_button: bool ='', no_close_with_middle_click: bool ='', no_scrolling_buttons: bool ='', no_tooltip: bool ='', draw_selected_overline: bool ='') -> Union[int, str]: - """Adds a tab bar.""" - ... - -def add_tab_button(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', no_reorder: bool ='', leading: bool ='', trailing: bool ='', no_tooltip: bool ='', unsaved_document: bool ='') -> Union[int, str]: - """Adds a tab button to a tab bar.""" - ... - -def add_table(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', header_row: bool ='', clipper: bool ='', inner_width: int ='', policy: int ='', freeze_rows: int ='', freeze_columns: int ='', sort_multi: bool ='', sort_tristate: bool ='', resizable: bool ='', reorderable: bool ='', hideable: bool ='', sortable: bool ='', context_menu_in_body: bool ='', row_background: bool ='', borders_innerH: bool ='', borders_outerH: bool ='', borders_innerV: bool ='', borders_outerV: bool ='', no_host_extendX: bool ='', no_host_extendY: bool ='', no_keep_columns_visible: bool ='', precise_widths: bool ='', no_clip: bool ='', pad_outerX: bool ='', no_pad_outerX: bool ='', no_pad_innerX: bool ='', scrollX: bool ='', scrollY: bool ='', no_saved_settings: bool ='') -> Union[int, str]: - """Adds a table.""" - ... - -def add_table_cell(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', height: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', filter_key: str ='') -> Union[int, str]: - """Adds a table.""" - ... - -def add_table_column(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', enabled: bool ='', init_width_or_weight: float ='', default_hide: bool ='', default_sort: bool ='', width_stretch: bool ='', width_fixed: bool ='', no_resize: bool ='', no_reorder: bool ='', no_hide: bool ='', no_clip: bool ='', no_sort: bool ='', no_sort_ascending: bool ='', no_sort_descending: bool ='', no_header_width: bool ='', prefer_sort_ascending: bool ='', prefer_sort_descending: bool ='', indent_enable: bool ='', indent_disable: bool ='', angled_header: bool ='', no_header_label: bool ='') -> Union[int, str]: - """Adds a table column.""" - ... - -def add_table_row(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', height: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', filter_key: str ='') -> Union[int, str]: - """Adds a table row.""" - ... - -def add_template_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='') -> Union[int, str]: - """Adds a template registry.""" - ... - -def add_text(default_value : str ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', wrap: int ='', bullet: bool ='', color: Union[List[int], Tuple[int, ...]] ='', show_label: bool ='') -> Union[int, str]: - """Adds text. Text can have an optional label that will display to the right of the text.""" - ... - -def add_text_point(x : float, y : float, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', source: Union[int, str] ='', show: bool ='', offset: Union[List[float], Tuple[float, ...]] ='', vertical: bool ='') -> Union[int, str]: - """Adds a label series to a plot. x and y can only have one elements each.""" - ... - -def add_texture_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a dynamic texture.""" - ... - -def add_theme(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='') -> Union[int, str]: - """Adds a theme.""" - ... - -def add_theme_color(target : int ='', value : Union[List[int], Tuple[int, ...]] ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', category: int ='') -> Union[int, str]: - """Adds a theme color.""" - ... - -def add_theme_component(item_type : int ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', enabled_state: bool ='') -> Union[int, str]: - """Adds a theme component.""" - ... - -def add_theme_style(target : int ='', x : float ='', y : float ='', *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', category: int ='') -> Union[int, str]: - """Adds a theme style.""" - ... - -def add_time_picker(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', callback: Callable ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_value: dict ='', hour24: bool ='') -> Union[int, str]: - """Adds a time picker.""" - ... - -def add_tooltip(parent : Union[int, str], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='', delay: float ='', hide_on_activity: bool ='') -> Union[int, str]: - """Adds a tooltip window.""" - ... - -def add_tree_node(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', before: Union[int, str] ='', payload_type: str ='', drag_callback: Callable ='', drop_callback: Callable ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', filter_key: str ='', tracked: bool ='', track_offset: float ='', default_open: bool ='', open_on_double_click: bool ='', open_on_arrow: bool ='', leaf: bool ='', bullet: bool ='', selectable: bool ='', span_text_width: bool ='', span_full_width: bool ='', catch_nav_left: bool ='', lines: int ='') -> Union[int, str]: - """Adds a tree node to add items to.""" - ... - -def add_value_registry(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='') -> Union[int, str]: - """Adds a value registry.""" - ... - -def add_viewport_drawlist(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', show: bool ='', filter_key: str ='', front: bool ='') -> Union[int, str]: - """A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children.""" - ... - -def add_viewport_menu_bar(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', indent: int ='', parent: Union[int, str] ='', show: bool ='') -> Union[int, str]: - """Adds a menubar to the viewport.""" - ... - -def add_window(*, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', width: int ='', height: int ='', indent: int ='', show: bool ='', pos: Union[List[int], Tuple[int, ...]] ='', min_size: Union[List[int], Tuple[int, ...]] ='', max_size: Union[List[int], Tuple[int, ...]] ='', menubar: bool ='', collapsed: bool ='', autosize: bool ='', no_resize: bool ='', unsaved_document: bool ='', no_title_bar: bool ='', no_move: bool ='', no_scrollbar: bool ='', no_collapse: bool ='', horizontal_scrollbar: bool ='', no_focus_on_appearing: bool ='', no_bring_to_front_on_focus: bool ='', no_close: bool ='', no_background: bool ='', modal: bool ='', popup: bool ='', no_saved_settings: bool ='', no_open_over_existing_popup: bool ='', no_scroll_with_mouse: bool ='', no_docking: bool ='', copy_contents_shortcut: bool ='', on_close: Callable ='') -> Union[int, str]: - """Creates a new window for following items to be added to.""" - ... - -def apply_transform(item : Union[int, str], transform : Any) -> None: - """New in 1.1. Applies a transformation matrix to a layer.""" - ... - -def bind_colormap(item : Union[int, str], source : Union[int, str]) -> None: - """Sets the color map for widgets that accept it.""" - ... - -def bind_font(font : Union[int, str]) -> Union[int, str]: - """Binds a global font.""" - ... - -def bind_item_font(item : Union[int, str], font : Union[int, str]) -> None: - """Sets an item's font.""" - ... - -def bind_item_handler_registry(item : Union[int, str], handler_registry : Union[int, str]) -> None: - """Binds an item handler registry to an item.""" - ... - -def bind_item_theme(item : Union[int, str], theme : Union[int, str]) -> None: - """Binds a theme to an item.""" - ... - -def bind_theme(theme : Union[int, str]) -> None: - """Binds a global theme.""" - ... - -def capture_next_item(callback : Callable, *, user_data: Any ='') -> None: - """Captures the next item.""" - ... - -def clear_selected_links(node_editor : Union[int, str]) -> None: - """Clears a node editor's selected links.""" - ... - -def clear_selected_nodes(node_editor : Union[int, str]) -> None: - """Clears a node editor's selected nodes.""" - ... - -def configure_app(*, load_init_file: str ='', docking: bool ='', docking_space: bool ='', docking_shift_only: bool ='', init_file: str ='', auto_save_init_file: bool ='', device: int ='', auto_device: bool ='', allow_alias_overwrites: bool ='', manual_alias_management: bool ='', skip_required_args: bool ='', skip_positional_args: bool ='', skip_keyword_args: bool ='', wait_for_input: bool ='', manual_callback_management: bool ='', keyboard_navigation: bool ='', anti_aliased_lines: bool ='', anti_aliased_lines_use_tex: bool ='', anti_aliased_fill: bool ='', win32_alt_enter_fullscreen: bool ='', **kwargs) -> None: - """Configures app.""" - ... - -def configure_item(item : Union[int, str], **kwargs) -> None: - """Configures an item.""" - ... - -def configure_viewport(item : Union[int, str], **kwargs) -> None: - """Configures a viewport.""" - ... - -def create_context() -> None: - """Creates the Dear PyGui context.""" - ... - -def create_fps_matrix(eye : Union[List[float], Tuple[float, ...]], pitch : float, yaw : float) -> Any: - """New in 1.1. Create a 'first person shooter' matrix.""" - ... - -def create_lookat_matrix(eye : Union[List[float], Tuple[float, ...]], target : Union[List[float], Tuple[float, ...]], up : Union[List[float], Tuple[float, ...]]) -> Any: - """New in 1.1. Creates a 'Look at matrix'.""" - ... - -def create_orthographic_matrix(left : float, right : float, bottom : float, top : float, zNear : float, zFar : float) -> Any: - """New in 1.1. Creates an orthographic matrix.""" - ... - -def create_perspective_matrix(fov : float, aspect : float, zNear : float, zFar : float) -> Any: - """New in 1.1. Creates a perspective matrix.""" - ... - -def create_rotation_matrix(angle : float, axis : Union[List[float], Tuple[float, ...]]) -> Any: - """New in 1.1. Applies a transformation matrix to a layer.""" - ... - -def create_scale_matrix(scales : Union[List[float], Tuple[float, ...]]) -> Any: - """New in 1.1. Applies a transformation matrix to a layer.""" - ... - -def create_translation_matrix(translation : Union[List[float], Tuple[float, ...]]) -> Any: - """New in 1.1. Creates a translation matrix.""" - ... - -def create_viewport(*, title: str ='', small_icon: str ='', large_icon: str ='', width: int ='', height: int ='', x_pos: int ='', y_pos: int ='', min_width: int ='', max_width: int ='', min_height: int ='', max_height: int ='', resizable: bool ='', vsync: bool ='', always_on_top: bool ='', decorated: bool ='', clear_color: Union[List[float], Tuple[float, ...]] ='', disable_close: bool ='') -> None: - """Creates a viewport. Viewports are required.""" - ... - -def delete_item(item : Union[int, str], *, children_only: bool ='', slot: int ='') -> None: - """Deletes an item..""" - ... - -def destroy_context() -> None: - """Destroys the Dear PyGui context.""" - ... - -def does_alias_exist(alias : str) -> bool: - """Checks if an alias exist.""" - ... - -def does_item_exist(item : Union[int, str]) -> bool: - """Checks if an item exist..""" - ... - -def draw_arrow(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', size: int ='') -> Union[int, str]: - """Adds an arrow.""" - ... - -def draw_bezier_cubic(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', segments: int ='') -> Union[int, str]: - """Adds a cubic bezier curve.""" - ... - -def draw_bezier_quadratic(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', segments: int ='') -> Union[int, str]: - """Adds a quadratic bezier curve.""" - ... - -def draw_circle(center : Union[List[float], Tuple[float, ...]], radius : float, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', segments: int ='') -> Union[int, str]: - """Adds a circle""" - ... - -def draw_ellipse(pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', thickness: float ='', segments: int ='') -> Union[int, str]: - """Adds an ellipse.""" - ... - -def draw_image(texture_tag : Union[int, str], pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', uv_min: Union[List[float], Tuple[float, ...]] ='', uv_max: Union[List[float], Tuple[float, ...]] ='', color: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds an image (for a drawing).""" - ... - -def draw_image_quad(texture_tag : Union[int, str], p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', uv1: Union[List[float], Tuple[float, ...]] ='', uv2: Union[List[float], Tuple[float, ...]] ='', uv3: Union[List[float], Tuple[float, ...]] ='', uv4: Union[List[float], Tuple[float, ...]] ='', color: Union[List[int], Tuple[int, ...]] ='') -> Union[int, str]: - """Adds an image (for a drawing).""" - ... - -def draw_line(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='') -> Union[int, str]: - """Adds a line.""" - ... - -def draw_polygon(points : List[List[float]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', thickness: float ='') -> Union[int, str]: - """Adds a polygon.""" - ... - -def draw_polyline(points : List[List[float]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', closed: bool ='', color: Union[List[int], Tuple[int, ...]] ='', thickness: float ='') -> Union[int, str]: - """Adds a polyline.""" - ... - -def draw_quad(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', thickness: float ='') -> Union[int, str]: - """Adds a quad.""" - ... - -def draw_rectangle(pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', multicolor: bool ='', rounding: float ='', thickness: float ='', corner_colors: Any ='') -> Union[int, str]: - """Adds a rectangle.""" - ... - -def draw_text(pos : Union[List[float], Tuple[float, ...]], text : str, *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', size: float ='') -> Union[int, str]: - """Adds text (drawlist).""" - ... - -def draw_triangle(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], *, label: str ='', user_data: Any ='', use_internal_label: bool ='', tag: Union[int, str] ='', parent: Union[int, str] ='', before: Union[int, str] ='', show: bool ='', color: Union[List[int], Tuple[int, ...]] ='', fill: Union[List[int], Tuple[int, ...]] ='', thickness: float ='') -> Union[int, str]: - """Adds a triangle.""" - ... - -def empty_container_stack() -> None: - """Emptyes the container stack.""" - ... - -def fit_axis_data(axis : Union[int, str]) -> None: - """Sets the axis boundaries max/min in the data series currently on the plot.""" - ... - -def focus_item(item : Union[int, str]) -> None: - """Focuses an item.""" - ... - -def generate_uuid() -> Union[int, str]: - """Generate a new UUID.""" - ... - -def get_active_window() -> Union[int, str]: - """Returns the active window.""" - ... - -def get_alias_id(alias : str) -> Union[int, str]: - """Returns the ID associated with an alias.""" - ... - -def get_aliases() -> Union[List[str], Tuple[str, ...]]: - """Returns all aliases.""" - ... - -def get_all_items() -> Union[List[int], Tuple[int, ...]]: - """Returns all items.""" - ... - -def get_app_configuration() -> dict: - """Returns app configuration.""" - ... - -def get_axis_limits(axis : Union[int, str]) -> Union[List[float], Tuple[float, ...]]: - """Get the specified axis limits.""" - ... - -def get_callback_queue() -> Any: - """New in 1.2. Returns and clears callback queue.""" - ... - -def get_clipboard_text() -> str: - """New in 1.3. Gets the clipboard text.""" - ... - -def get_colormap_color(colormap : Union[int, str], index : int) -> Union[List[int], Tuple[int, ...]]: - """Returns a color from a colormap given an index >= 0. (ex. 0 will be the first color in the color list of the color map) Modulo will be performed against the number of items in the color list.""" - ... - -def get_delta_time() -> float: - """Returns time since last frame.""" - ... - -def get_drawing_mouse_pos() -> Union[List[int], Tuple[int, ...]]: - """Returns mouse position in drawing.""" - ... - -def get_file_dialog_info(file_dialog : Union[int, str]) -> dict: - """Returns information related to the file dialog. Typically used while the file dialog is in use to query data about the state or info related to the file dialog.""" - ... - -def get_focused_item() -> Union[int, str]: - """Returns the item currently having focus.""" - ... - -def get_frame_count() -> int: - """Returns frame count.""" - ... - -def get_frame_rate() -> float: - """Returns the average frame rate across 120 frames.""" - ... - -def get_global_font_scale() -> float: - """Returns global font scale.""" - ... - -def get_item_alias(item : Union[int, str]) -> str: - """Returns an item's alias.""" - ... - -def get_item_configuration(item : Union[int, str]) -> dict: - """Returns an item's configuration.""" - ... - -def get_item_info(item : Union[int, str]) -> dict: - """Returns an item's information.""" - ... - -def get_item_state(item : Union[int, str]) -> dict: - """Returns an item's state.""" - ... - -def get_item_types() -> dict: - """Returns an item types.""" - ... - -def get_mouse_drag_delta() -> float: - """Returns mouse drag delta.""" - ... - -def get_mouse_pos(*, local: bool ='') -> Union[List[int], Tuple[int, ...]]: - """Returns mouse position.""" - ... - -def get_platform() -> int: - """New in 1.6. Returns platform constant.""" - ... - -def get_plot_mouse_pos() -> Union[List[int], Tuple[int, ...]]: - """Returns mouse position in plot.""" - ... - -def get_plot_query_rects(plot : Union[int, str]) -> List[List[float]]: - """Returns the query rects of the plot. Returns an array of array containing the top-left coordinates and bottom-right coordinates of the plot area.""" - ... - -def get_selected_links(node_editor : Union[int, str]) -> List[List[str]]: - """Returns a node editor's selected links.""" - ... - -def get_selected_nodes(node_editor : Union[int, str]) -> Union[List[int], Tuple[int, ...]]: - """Returns a node editor's selected nodes.""" - ... - -def get_text_size(text : str, *, wrap_width: float ='', font: Union[int, str] ='') -> Union[List[float], Tuple[float, ...]]: - """Returns width/height of text with specified font (must occur after 1st frame).""" - ... - -def get_total_time() -> float: - """Returns total time since Dear PyGui has started.""" - ... - -def get_value(item : Union[int, str]) -> Any: - """Returns an item's value.""" - ... - -def get_values(items : Union[List[int], Tuple[int, ...]]) -> Any: - """Returns values of a list of items.""" - ... - -def get_viewport_configuration(item : Union[int, str]) -> dict: - """Returns a viewport's configuration.""" - ... - -def get_windows() -> Union[List[int], Tuple[int, ...]]: - """Returns all windows.""" - ... - -def get_x_scroll(item : Union[int, str]) -> float: - """Undocumented""" - ... - -def get_x_scroll_max(item : Union[int, str]) -> float: - """Undocumented""" - ... - -def get_y_scroll(item : Union[int, str]) -> float: - """Undocumented""" - ... - -def get_y_scroll_max(item : Union[int, str]) -> float: - """Undocumented""" - ... - -def highlight_table_cell(table : Union[int, str], row : int, column : int, color : Union[List[int], Tuple[int, ...]]) -> None: - """Highlight specified table cell.""" - ... - -def highlight_table_column(table : Union[int, str], column : int, color : Union[List[int], Tuple[int, ...]]) -> None: - """Highlight specified table column.""" - ... - -def highlight_table_row(table : Union[int, str], row : int, color : Union[List[int], Tuple[int, ...]]) -> None: - """Highlight specified table row.""" - ... - -def is_dearpygui_running() -> bool: - """Checks if Dear PyGui is running""" - ... - -def is_key_down(key : int) -> bool: - """Checks if key is down.""" - ... - -def is_key_pressed(key : int) -> bool: - """Checks if key is pressed.""" - ... - -def is_key_released(key : int) -> bool: - """Checks if key is released.""" - ... - -def is_mouse_button_clicked(button : int) -> bool: - """Checks if mouse button is clicked.""" - ... - -def is_mouse_button_double_clicked(button : int) -> bool: - """Checks if mouse button is double clicked.""" - ... - -def is_mouse_button_down(button : int) -> bool: - """Checks if mouse button is down.""" - ... - -def is_mouse_button_dragging(button : int, threshold : float) -> bool: - """Checks if mouse button is down and dragging.""" - ... - -def is_mouse_button_released(button : int) -> bool: - """Checks if mouse button is released.""" - ... - -def is_table_cell_highlighted(table : Union[int, str], row : int, column : int) -> bool: - """Checks if a table cell is highlighted.""" - ... - -def is_table_column_highlighted(table : Union[int, str], column : int) -> bool: - """Checks if a table column is highlighted.""" - ... - -def is_table_row_highlighted(table : Union[int, str], row : int) -> bool: - """Checks if a table row is highlighted.""" - ... - -def is_viewport_ok() -> bool: - """Checks if a viewport has been created and shown.""" - ... - -def last_container() -> Union[int, str]: - """Returns the last container item added.""" - ... - -def last_item() -> Union[int, str]: - """Returns the last item added.""" - ... - -def last_root() -> Union[int, str]: - """Returns the last root added (registry or window).""" - ... - -def load_image(file : str, *, gamma: float ='', gamma_scale_factor: float ='') -> Any: - """Loads an image. Returns width, height, channels, mvBuffer""" - ... - -def lock_mutex() -> None: - """Locks render thread mutex.""" - ... - -def maximize_viewport() -> None: - """Maximizes the viewport.""" - ... - -def minimize_viewport() -> None: - """Minimizes a viewport.""" - ... - -def move_item(item : Union[int, str], *, parent: Union[int, str] ='', before: Union[int, str] ='') -> None: - """Moves an item to a new location.""" - ... - -def move_item_down(item : Union[int, str]) -> None: - """Moves an item down.""" - ... - -def move_item_up(item : Union[int, str]) -> None: - """Moves an item up.""" - ... - -def output_frame_buffer(file : str ='', *, callback: Callable ='') -> Any: - """Outputs frame buffer as a png if file is specified or through the second argument of a callback if specified. Render loop must have been started.""" - ... - -def pop_container_stack() -> Union[int, str]: - """Pops the top item off the parent stack and return its ID.""" - ... - -def push_container_stack(item : Union[int, str]) -> bool: - """Pushes an item onto the container stack.""" - ... - -def remove_alias(alias : str) -> None: - """Removes an alias.""" - ... - -def render_dearpygui_frame() -> None: - """Render a single Dear PyGui frame.""" - ... - -def reorder_items(container : Union[int, str], slot : int, new_order : Union[List[int], Tuple[int, ...]]) -> None: - """Reorders an item's children.""" - ... - -def reset_axis_limits_constraints(axis : Union[int, str]) -> None: - """Remove an axis' limits constraints""" - ... - -def reset_axis_ticks(axis : Union[int, str]) -> None: - """Removes the manually set axis ticks and applies the default axis ticks""" - ... - -def reset_axis_zoom_constraints(axis : Union[int, str]) -> None: - """Remove an axis' zoom constraints""" - ... - -def reset_pos(item : Union[int, str]) -> None: - """Resets an item's position after using 'set_item_pos'.""" - ... - -def sample_colormap(colormap : Union[int, str], t : float) -> Union[List[int], Tuple[int, ...]]: - """Returns a color from a colormap given t between 0.0-1.0.""" - ... - -def save_image(file : str, width : int, height : int, data : Any, *, components: int ='', quality: int ='') -> None: - """Saves an image. Possible formats: png, bmp, tga, hdr, jpg.""" - ... - -def save_init_file(file : str) -> None: - """Save dpg.ini file.""" - ... - -def set_axis_limits(axis : Union[int, str], ymin : float, ymax : float) -> None: - """Sets limits on the axis for pan and zoom.""" - ... - -def set_axis_limits_auto(axis : Union[int, str]) -> None: - """Removes all limits on specified axis.""" - ... - -def set_axis_limits_constraints(axis : Union[int, str], vmin : float, vmax : float) -> None: - """Sets an axis' limits constraints so that users can't pan beyond a min or max value""" - ... - -def set_axis_ticks(axis : Union[int, str], label_pairs : Any) -> None: - """Replaces axis ticks with 'label_pairs' argument.""" - ... - -def set_axis_zoom_constraints(axis : Union[int, str], vmin : float, vmax : float) -> None: - """Sets an axis' zoom constraints so that users can't zoom beyond a min or max value""" - ... - -def set_clip_space(item : Union[int, str], top_left_x : float, top_left_y : float, width : float, height : float, min_depth : float, max_depth : float) -> None: - """New in 1.1. Set the clip space for depth clipping and 'viewport' transformation.""" - ... - -def set_clipboard_text(text : str) -> None: - """New in 1.3. Sets the clipboard text.""" - ... - -def set_exit_callback(callback : Callable, *, user_data: Any ='') -> str: - """Sets a callback to run on last frame.""" - ... - -def set_frame_callback(frame : int, callback : Callable, *, user_data: Any ='') -> str: - """Sets a callback to run on first frame.""" - ... - -def set_global_font_scale(scale : float) -> None: - """Sets global font scale.""" - ... - -def set_item_alias(item : Union[int, str], alias : str) -> None: - """Sets an item's alias.""" - ... - -def set_item_children(item : Union[int, str], source : Union[int, str], slot : int) -> None: - """Sets an item's children.""" - ... - -def set_primary_window(window : Union[int, str], value : bool ='') -> None: - """Sets the primary window.""" - ... - -def set_table_row_color(table : Union[int, str], row : int, color : Union[List[int], Tuple[int, ...]]) -> None: - """Set table row color.""" - ... - -def set_value(item : Union[int, str], value : Any) -> None: - """Set's an item's value.""" - ... - -def set_viewport_resize_callback(callback : Callable, *, user_data: Any ='') -> str: - """Sets a callback to run on viewport resize.""" - ... - -def set_x_scroll(item : Union[int, str], value : float, *, when: int ='') -> None: - """Sets horizontal scroll position.""" - ... - -def set_y_scroll(item : Union[int, str], value : float, *, when: int ='') -> None: - """Sets vertical scroll position.""" - ... - -def setup_dearpygui() -> None: - """Sets up Dear PyGui""" - ... - -def show_imgui_demo() -> None: - """Shows the imgui demo.""" - ... - -def show_implot_demo() -> None: - """Shows the implot demo.""" - ... - -def show_item_debug(item : Union[int, str]) -> None: - """Shows an item's debug window""" - ... - -def show_tool(tool : Union[int, str]) -> str: - """Shows a built in tool.""" - ... - -def show_viewport(*, minimized: bool ='', maximized: bool ='') -> None: - """Shows the main viewport.""" - ... - -def split_frame() -> None: - """Waits one frame.""" - ... - -def stop_dearpygui() -> None: - """Stops Dear PyGui""" - ... - -def toggle_viewport_fullscreen() -> None: - """Toggle viewport fullscreen mode..""" - ... - -def top_container_stack() -> Union[int, str]: - """Returns the item on the top of the container stack.""" - ... - -def unhighlight_table_cell(table : Union[int, str], row : int, column : int) -> None: - """Unhighlight specified table cell.""" - ... - -def unhighlight_table_column(table : Union[int, str], column : int) -> None: - """Unhighlight specified table column.""" - ... - -def unhighlight_table_row(table : Union[int, str], row : int) -> None: - """Unhighlight specified table row.""" - ... - -def unlock_mutex() -> None: - """Unlocks render thread mutex""" - ... - -def unset_table_row_color(table : Union[int, str], row : int) -> None: - """Remove user set table row color.""" - ... - -def unstage(item : Union[int, str]) -> None: - """Unstages an item.""" - ... - -mvGraphicsBackend_D3D11=0 -mvGraphicsBackend_D3D12=0 -mvGraphicsBackend_VULKAN=0 -mvGraphicsBackend_METAL=0 -mvGraphicsBackend_OPENGL=0 -mvMouseButton_Left=0 -mvMouseButton_Right=0 -mvMouseButton_Middle=0 -mvMouseButton_X1=0 -mvMouseButton_X2=0 -mvKey_ModDisabled=0 -mvKey_None=0 -mvKey_0=0 -mvKey_1=0 -mvKey_2=0 -mvKey_3=0 -mvKey_4=0 -mvKey_5=0 -mvKey_6=0 -mvKey_7=0 -mvKey_8=0 -mvKey_9=0 -mvKey_A=0 -mvKey_B=0 -mvKey_C=0 -mvKey_D=0 -mvKey_E=0 -mvKey_F=0 -mvKey_G=0 -mvKey_H=0 -mvKey_I=0 -mvKey_J=0 -mvKey_K=0 -mvKey_L=0 -mvKey_M=0 -mvKey_N=0 -mvKey_O=0 -mvKey_P=0 -mvKey_Q=0 -mvKey_R=0 -mvKey_S=0 -mvKey_T=0 -mvKey_U=0 -mvKey_V=0 -mvKey_W=0 -mvKey_X=0 -mvKey_Y=0 -mvKey_Z=0 -mvKey_Back=0 -mvKey_Tab=0 -mvKey_Return=0 -mvKey_LShift=0 -mvKey_RShift=0 -mvKey_LControl=0 -mvKey_RControl=0 -mvKey_LAlt=0 -mvKey_RAlt=0 -mvKey_Pause=0 -mvKey_CapsLock=0 -mvKey_Escape=0 -mvKey_Spacebar=0 -mvKey_End=0 -mvKey_Home=0 -mvKey_Left=0 -mvKey_Up=0 -mvKey_Right=0 -mvKey_Down=0 -mvKey_Print=0 -mvKey_Insert=0 -mvKey_Delete=0 -mvKey_NumPad0=0 -mvKey_NumPad1=0 -mvKey_NumPad2=0 -mvKey_NumPad3=0 -mvKey_NumPad4=0 -mvKey_NumPad5=0 -mvKey_NumPad6=0 -mvKey_NumPad7=0 -mvKey_NumPad8=0 -mvKey_NumPad9=0 -mvKey_NumPadEnter=0 -mvKey_NumPadEqual=0 -mvKey_Subtract=0 -mvKey_Decimal=0 -mvKey_Divide=0 -mvKey_Multiply=0 -mvKey_Add=0 -mvKey_F1=0 -mvKey_F2=0 -mvKey_F3=0 -mvKey_F4=0 -mvKey_F5=0 -mvKey_F6=0 -mvKey_F7=0 -mvKey_F8=0 -mvKey_F9=0 -mvKey_F10=0 -mvKey_F11=0 -mvKey_F12=0 -mvKey_F13=0 -mvKey_F14=0 -mvKey_F15=0 -mvKey_F16=0 -mvKey_F17=0 -mvKey_F18=0 -mvKey_F19=0 -mvKey_F20=0 -mvKey_F21=0 -mvKey_F22=0 -mvKey_F23=0 -mvKey_F24=0 -mvKey_NumLock=0 -mvKey_ScrollLock=0 -mvKey_Period=0 -mvKey_Slash=0 -mvKey_Backslash=0 -mvKey_Open_Brace=0 -mvKey_Close_Brace=0 -mvKey_Browser_Back=0 -mvKey_Browser_Forward=0 -mvKey_Comma=0 -mvKey_Minus=0 -mvKey_Menu=0 -mvKey_ModSuper=0 -mvKey_ModShift=0 -mvKey_ModAlt=0 -mvKey_ModCtrl=0 -mvKey_Clear=0 -mvKey_Prior=0 -mvKey_Next=0 -mvKey_Select=0 -mvKey_Execute=0 -mvKey_LWin=0 -mvKey_RWin=0 -mvKey_Apps=0 -mvKey_Sleep=0 -mvKey_Help=0 -mvKey_Browser_Refresh=0 -mvKey_Browser_Stop=0 -mvKey_Browser_Search=0 -mvKey_Browser_Favorites=0 -mvKey_Browser_Home=0 -mvKey_Volume_Mute=0 -mvKey_Volume_Down=0 -mvKey_Volume_Up=0 -mvKey_Media_Next_Track=0 -mvKey_Media_Prev_Track=0 -mvKey_Media_Stop=0 -mvKey_Media_Play_Pause=0 -mvKey_Launch_Mail=0 -mvKey_Launch_Media_Select=0 -mvKey_Launch_App1=0 -mvKey_Launch_App2=0 -mvKey_Colon=0 -mvKey_Plus=0 -mvKey_Tilde=0 -mvKey_Quote=0 -mvKey_F25=0 -mvAll=0 -mvTool_About=0 -mvTool_Debug=0 -mvTool_Doc=0 -mvTool_ItemRegistry=0 -mvTool_Metrics=0 -mvTool_Stack=0 -mvTool_Style=0 -mvTool_Font=0 -mvFontAtlas=0 -mvAppUUID=0 -mvInvalidUUID=0 -mvDir_None=0 -mvDir_Left=0 -mvDir_Right=0 -mvDir_Up=0 -mvDir_Down=0 -mvComboHeight_Small=0 -mvComboHeight_Regular=0 -mvComboHeight_Large=0 -mvComboHeight_Largest=0 -mvEventType_Off=0 -mvEventType_Enter=0 -mvEventType_On=0 -mvEventType_Leave=0 -mvSetScrollFlags_Now=0 -mvSetScrollFlags_Delayed=0 -mvSetScrollFlags_Both=0 -mvScrollDirection_XAxis=0 -mvScrollDirection_YAxis=0 -mvScrollDirection_Horizontal=0 -mvScrollDirection_Vertical=0 -mvLoadInd_DottedCircle=0 -mvLoadInd_Ring=0 -mvPlatform_Windows=0 -mvPlatform_Apple=0 -mvPlatform_Linux=0 -mvColorEdit_AlphaPreviewNone=0 -mvColorEdit_AlphaPreview=0 -mvColorEdit_AlphaPreviewHalf=0 -mvColorEdit_uint8=0 -mvColorEdit_float=0 -mvColorEdit_rgb=0 -mvColorEdit_hsv=0 -mvColorEdit_hex=0 -mvColorEdit_input_rgb=0 -mvColorEdit_input_hsv=0 -mvPlotColormap_Default=0 -mvPlotColormap_Deep=0 -mvPlotColormap_Dark=0 -mvPlotColormap_Pastel=0 -mvPlotColormap_Paired=0 -mvPlotColormap_Viridis=0 -mvPlotColormap_Plasma=0 -mvPlotColormap_Hot=0 -mvPlotColormap_Cool=0 -mvPlotColormap_Pink=0 -mvPlotColormap_Jet=0 -mvPlotColormap_Twilight=0 -mvPlotColormap_RdBu=0 -mvPlotColormap_BrBG=0 -mvPlotColormap_PiYG=0 -mvPlotColormap_Spectral=0 -mvPlotColormap_Greys=0 -mvColorPicker_bar=0 -mvColorPicker_wheel=0 -mvTabOrder_Reorderable=0 -mvTabOrder_Fixed=0 -mvTabOrder_Leading=0 -mvTabOrder_Trailing=0 -mvTimeUnit_Us=0 -mvTimeUnit_Ms=0 -mvTimeUnit_S=0 -mvTimeUnit_Min=0 -mvTimeUnit_Hr=0 -mvTimeUnit_Day=0 -mvTimeUnit_Mo=0 -mvTimeUnit_Yr=0 -mvDatePickerLevel_Day=0 -mvDatePickerLevel_Month=0 -mvDatePickerLevel_Year=0 -mvCullMode_None=0 -mvCullMode_Back=0 -mvCullMode_Front=0 -mvFontRangeHint_Default=0 -mvFontRangeHint_Japanese=0 -mvFontRangeHint_Korean=0 -mvFontRangeHint_Chinese_Full=0 -mvFontRangeHint_Chinese_Simplified_Common=0 -mvFontRangeHint_Cyrillic=0 -mvFontRangeHint_Thai=0 -mvFontRangeHint_Vietnamese=0 -mvNode_PinShape_Circle=0 -mvNode_PinShape_CircleFilled=0 -mvNode_PinShape_Triangle=0 -mvNode_PinShape_TriangleFilled=0 -mvNode_PinShape_Quad=0 -mvNode_PinShape_QuadFilled=0 -mvNode_Attr_Input=0 -mvNode_Attr_Output=0 -mvNode_Attr_Static=0 -mvPlotBin_Sqrt=0 -mvPlotBin_Sturges=0 -mvPlotBin_Rice=0 -mvPlotBin_Scott=0 -mvXAxis=0 -mvXAxis2=0 -mvXAxis3=0 -mvYAxis=0 -mvYAxis2=0 -mvYAxis3=0 -mvPlotScale_Linear=0 -mvPlotScale_Time=0 -mvPlotScale_Log10=0 -mvPlotScale_SymLog=0 -mvPlotMarker_None=0 -mvPlotMarker_Circle=0 -mvPlotMarker_Square=0 -mvPlotMarker_Diamond=0 -mvPlotMarker_Up=0 -mvPlotMarker_Down=0 -mvPlotMarker_Left=0 -mvPlotMarker_Right=0 -mvPlotMarker_Cross=0 -mvPlotMarker_Plus=0 -mvPlotMarker_Asterisk=0 -mvPlot_Location_Center=0 -mvPlot_Location_North=0 -mvPlot_Location_South=0 -mvPlot_Location_West=0 -mvPlot_Location_East=0 -mvPlot_Location_NorthWest=0 -mvPlot_Location_NorthEast=0 -mvPlot_Location_SouthWest=0 -mvPlot_Location_SouthEast=0 -mvNodeMiniMap_Location_BottomLeft=0 -mvNodeMiniMap_Location_BottomRight=0 -mvNodeMiniMap_Location_TopLeft=0 -mvNodeMiniMap_Location_TopRight=0 -mvTable_SizingFixedFit=0 -mvTable_SizingFixedSame=0 -mvTable_SizingStretchProp=0 -mvTable_SizingStretchSame=0 -mvTreeLines_None=0 -mvTreeLines_Full=0 -mvTreeLines_ToNodes=0 -mvFormat_Float_rgba=0 -mvFormat_Float_rgb=0 -mvThemeCat_Core=0 -mvThemeCat_Plots=0 -mvThemeCat_Nodes=0 -mvThemeCol_Text=0 -mvThemeCol_TextDisabled=0 -mvThemeCol_WindowBg=0 -mvThemeCol_ChildBg=0 -mvThemeCol_PopupBg=0 -mvThemeCol_Border=0 -mvThemeCol_BorderShadow=0 -mvThemeCol_FrameBg=0 -mvThemeCol_FrameBgHovered=0 -mvThemeCol_FrameBgActive=0 -mvThemeCol_TitleBg=0 -mvThemeCol_TitleBgActive=0 -mvThemeCol_TitleBgCollapsed=0 -mvThemeCol_MenuBarBg=0 -mvThemeCol_ScrollbarBg=0 -mvThemeCol_ScrollbarGrab=0 -mvThemeCol_ScrollbarGrabHovered=0 -mvThemeCol_ScrollbarGrabActive=0 -mvThemeCol_CheckMark=0 -mvThemeCol_SliderGrab=0 -mvThemeCol_SliderGrabActive=0 -mvThemeCol_Button=0 -mvThemeCol_ButtonHovered=0 -mvThemeCol_ButtonActive=0 -mvThemeCol_Header=0 -mvThemeCol_HeaderHovered=0 -mvThemeCol_HeaderActive=0 -mvThemeCol_Separator=0 -mvThemeCol_SeparatorHovered=0 -mvThemeCol_SeparatorActive=0 -mvThemeCol_ResizeGrip=0 -mvThemeCol_ResizeGripHovered=0 -mvThemeCol_ResizeGripActive=0 -mvThemeCol_InputTextCursor=0 -mvThemeCol_TabHovered=0 -mvThemeCol_Tab=0 -mvThemeCol_TabSelected=0 -mvThemeCol_TabSelectedOverline=0 -mvThemeCol_TabDimmed=0 -mvThemeCol_TabDimmedSelected=0 -mvThemeCol_TabDimmedSelectedOverline=0 -mvThemeCol_DockingPreview=0 -mvThemeCol_DockingEmptyBg=0 -mvThemeCol_PlotLines=0 -mvThemeCol_PlotLinesHovered=0 -mvThemeCol_PlotHistogram=0 -mvThemeCol_PlotHistogramHovered=0 -mvThemeCol_TableHeaderBg=0 -mvThemeCol_TableBorderStrong=0 -mvThemeCol_TableBorderLight=0 -mvThemeCol_TableRowBg=0 -mvThemeCol_TableRowBgAlt=0 -mvThemeCol_TextSelectedBg=0 -mvThemeCol_TreeLines=0 -mvThemeCol_DragDropTarget=0 -mvThemeCol_DragDropTargetBg=0 -mvThemeCol_UnsavedMarker=0 -mvThemeCol_NavCursor=0 -mvThemeCol_NavWindowingHighlight=0 -mvThemeCol_NavWindowingDimBg=0 -mvThemeCol_ModalWindowDimBg=0 -mvThemeCol_TabActive=0 -mvThemeCol_TabUnfocused=0 -mvThemeCol_TabUnfocusedActive=0 -mvThemeCol_NavHighlight=0 -mvPlotCol_Line=0 -mvPlotCol_Fill=0 -mvPlotCol_MarkerOutline=0 -mvPlotCol_MarkerFill=0 -mvPlotCol_ErrorBar=0 -mvPlotCol_FrameBg=0 -mvPlotCol_PlotBg=0 -mvPlotCol_PlotBorder=0 -mvPlotCol_LegendBg=0 -mvPlotCol_LegendBorder=0 -mvPlotCol_LegendText=0 -mvPlotCol_TitleText=0 -mvPlotCol_InlayText=0 -mvPlotCol_AxisText=0 -mvPlotCol_AxisGrid=0 -mvPlotCol_AxisTick=0 -mvPlotCol_AxisBg=0 -mvPlotCol_AxisBgHovered=0 -mvPlotCol_AxisBgActive=0 -mvPlotCol_Selection=0 -mvPlotCol_Crosshairs=0 -mvNodeCol_NodeBackground=0 -mvNodeCol_NodeBackgroundHovered=0 -mvNodeCol_NodeBackgroundSelected=0 -mvNodeCol_NodeOutline=0 -mvNodeCol_TitleBar=0 -mvNodeCol_TitleBarHovered=0 -mvNodeCol_TitleBarSelected=0 -mvNodeCol_Link=0 -mvNodeCol_LinkHovered=0 -mvNodeCol_LinkSelected=0 -mvNodeCol_Pin=0 -mvNodeCol_PinHovered=0 -mvNodeCol_BoxSelector=0 -mvNodeCol_BoxSelectorOutline=0 -mvNodeCol_GridBackground=0 -mvNodeCol_GridLine=0 -mvNodesCol_GridLinePrimary=0 -mvNodesCol_MiniMapBackground=0 -mvNodesCol_MiniMapBackgroundHovered=0 -mvNodesCol_MiniMapOutline=0 -mvNodesCol_MiniMapOutlineHovered=0 -mvNodesCol_MiniMapNodeBackground=0 -mvNodesCol_MiniMapNodeBackgroundHovered=0 -mvNodesCol_MiniMapNodeBackgroundSelected=0 -mvNodesCol_MiniMapNodeOutline=0 -mvNodesCol_MiniMapLink=0 -mvNodesCol_MiniMapLinkSelected=0 -mvNodesCol_MiniMapCanvas=0 -mvNodesCol_MiniMapCanvasOutline=0 -mvStyleVar_Alpha=0 -mvStyleVar_DisabledAlpha=0 -mvStyleVar_WindowPadding=0 -mvStyleVar_WindowRounding=0 -mvStyleVar_WindowBorderSize=0 -mvStyleVar_WindowMinSize=0 -mvStyleVar_WindowTitleAlign=0 -mvStyleVar_ChildRounding=0 -mvStyleVar_ChildBorderSize=0 -mvStyleVar_PopupRounding=0 -mvStyleVar_PopupBorderSize=0 -mvStyleVar_FramePadding=0 -mvStyleVar_FrameRounding=0 -mvStyleVar_FrameBorderSize=0 -mvStyleVar_ItemSpacing=0 -mvStyleVar_ItemInnerSpacing=0 -mvStyleVar_IndentSpacing=0 -mvStyleVar_CellPadding=0 -mvStyleVar_ScrollbarSize=0 -mvStyleVar_ScrollbarRounding=0 -mvStyleVar_ScrollbarPadding=0 -mvStyleVar_GrabMinSize=0 -mvStyleVar_GrabRounding=0 -mvStyleVar_ImageBorderSize=0 -mvStyleVar_TabRounding=0 -mvStyleVar_TabBorderSize=0 -mvStyleVar_TabMinWidthBase=0 -mvStyleVar_TabMinWidthShrink=0 -mvStyleVar_TabBarBorderSize=0 -mvStyleVar_TabBarOverlineSize=0 -mvStyleVar_TableAngledHeadersAngle=0 -mvStyleVar_TableAngledHeadersTextAlign=0 -mvStyleVar_TreeLinesSize=0 -mvStyleVar_TreeLinesRounding=0 -mvStyleVar_ButtonTextAlign=0 -mvStyleVar_SelectableTextAlign=0 -mvStyleVar_SeparatorTextBorderSize=0 -mvStyleVar_SeparatorTextAlign=0 -mvStyleVar_SeparatorTextPadding=0 -mvStyleVar_DockingSeparatorSize=0 -mvPlotStyleVar_LineWeight=0 -mvPlotStyleVar_Marker=0 -mvPlotStyleVar_MarkerSize=0 -mvPlotStyleVar_MarkerWeight=0 -mvPlotStyleVar_FillAlpha=0 -mvPlotStyleVar_ErrorBarSize=0 -mvPlotStyleVar_ErrorBarWeight=0 -mvPlotStyleVar_DigitalBitHeight=0 -mvPlotStyleVar_DigitalBitGap=0 -mvPlotStyleVar_PlotBorderSize=0 -mvPlotStyleVar_MinorAlpha=0 -mvPlotStyleVar_MajorTickLen=0 -mvPlotStyleVar_MinorTickLen=0 -mvPlotStyleVar_MajorTickSize=0 -mvPlotStyleVar_MinorTickSize=0 -mvPlotStyleVar_MajorGridSize=0 -mvPlotStyleVar_MinorGridSize=0 -mvPlotStyleVar_PlotPadding=0 -mvPlotStyleVar_LabelPadding=0 -mvPlotStyleVar_LegendPadding=0 -mvPlotStyleVar_LegendInnerPadding=0 -mvPlotStyleVar_LegendSpacing=0 -mvPlotStyleVar_MousePosPadding=0 -mvPlotStyleVar_AnnotationPadding=0 -mvPlotStyleVar_FitPadding=0 -mvPlotStyleVar_PlotDefaultSize=0 -mvPlotStyleVar_PlotMinSize=0 -mvNodeStyleVar_GridSpacing=0 -mvNodeStyleVar_NodeCornerRounding=0 -mvNodeStyleVar_NodePadding=0 -mvNodeStyleVar_NodeBorderThickness=0 -mvNodeStyleVar_LinkThickness=0 -mvNodeStyleVar_LinkLineSegmentsPerLength=0 -mvNodeStyleVar_LinkHoverDistance=0 -mvNodeStyleVar_PinCircleRadius=0 -mvNodeStyleVar_PinQuadSideLength=0 -mvNodeStyleVar_PinTriangleSideLength=0 -mvNodeStyleVar_PinLineThickness=0 -mvNodeStyleVar_PinHoverRadius=0 -mvNodeStyleVar_PinOffset=0 -mvNodesStyleVar_MiniMapPadding=0 -mvNodesStyleVar_MiniMapOffset=0 -mvInputText=0 -mvButton=0 -mvRadioButton=0 -mvTabBar=0 -mvTab=0 -mvImage=0 -mvMenuBar=0 -mvViewportMenuBar=0 -mvMenu=0 -mvMenuItem=0 -mvChildWindow=0 -mvGroup=0 -mvSliderFloat=0 -mvSliderInt=0 -mvFilterSet=0 -mvDragFloat=0 -mvDragInt=0 -mvInputFloat=0 -mvInputInt=0 -mvColorEdit=0 -mvClipper=0 -mvColorPicker=0 -mvTooltip=0 -mvCollapsingHeader=0 -mvSeparator=0 -mvCheckbox=0 -mvListbox=0 -mvText=0 -mvCombo=0 -mvPlot=0 -mvSimplePlot=0 -mvDrawlist=0 -mvWindowAppItem=0 -mvSelectable=0 -mvTreeNode=0 -mvProgressBar=0 -mvSpacer=0 -mvImageButton=0 -mvTimePicker=0 -mvDatePicker=0 -mvColorButton=0 -mvFileDialog=0 -mvTabButton=0 -mvDrawNode=0 -mvNodeEditor=0 -mvNode=0 -mvNodeAttribute=0 -mvTable=0 -mvTableColumn=0 -mvTableRow=0 -mvSyncedTables=0 -mvDrawLine=0 -mvDrawArrow=0 -mvDrawTriangle=0 -mvDrawImageQuad=0 -mvDrawCircle=0 -mvDrawEllipse=0 -mvDrawBezierCubic=0 -mvDrawBezierQuadratic=0 -mvDrawQuad=0 -mvDrawRect=0 -mvDrawText=0 -mvDrawPolygon=0 -mvDrawPolyline=0 -mvDrawImage=0 -mvDragFloatMulti=0 -mvDragIntMulti=0 -mvSliderFloatMulti=0 -mvSliderIntMulti=0 -mvInputIntMulti=0 -mvInputFloatMulti=0 -mvDragPoint=0 -mvDragLine=0 -mvDragRect=0 -mvAnnotation=0 -mvAxisTag=0 -mvLineSeries=0 -mvScatterSeries=0 -mvStemSeries=0 -mvStairSeries=0 -mvBarSeries=0 -mvBarGroupSeries=0 -mvErrorSeries=0 -mvInfLineSeries=0 -mvHeatSeries=0 -mvImageSeries=0 -mvPieSeries=0 -mvShadeSeries=0 -mvLabelSeries=0 -mvHistogramSeries=0 -mvDigitalSeries=0 -mv2dHistogramSeries=0 -mvCandleSeries=0 -mvAreaSeries=0 -mvColorMapScale=0 -mvSlider3D=0 -mvKnobFloat=0 -mvLoadingIndicator=0 -mvNodeLink=0 -mvTextureRegistry=0 -mvStaticTexture=0 -mvDynamicTexture=0 -mvStage=0 -mvDrawLayer=0 -mvViewportDrawlist=0 -mvFileExtension=0 -mvPlotLegend=0 -mvPlotAxis=0 -mvHandlerRegistry=0 -mvKeyDownHandler=0 -mvKeyPressHandler=0 -mvKeyReleaseHandler=0 -mvMouseMoveHandler=0 -mvMouseWheelHandler=0 -mvMouseClickHandler=0 -mvMouseDoubleClickHandler=0 -mvMouseDownHandler=0 -mvMouseReleaseHandler=0 -mvMouseDragHandler=0 -mvHoverHandler=0 -mvActiveHandler=0 -mvFocusHandler=0 -mvVisibleHandler=0 -mvEditedHandler=0 -mvActivatedHandler=0 -mvDeactivatedHandler=0 -mvDeactivatedAfterEditHandler=0 -mvToggledOpenHandler=0 -mvClickedHandler=0 -mvDoubleClickedHandler=0 -mvScrollHandler=0 -mvDragPayload=0 -mvResizeHandler=0 -mvFont=0 -mvFontRegistry=0 -mvTheme=0 -mvThemeColor=0 -mvThemeStyle=0 -mvThemeComponent=0 -mvCharRemap=0 -mvValueRegistry=0 -mvIntValue=0 -mvFloatValue=0 -mvFloat4Value=0 -mvInt4Value=0 -mvBoolValue=0 -mvStringValue=0 -mvDoubleValue=0 -mvDouble4Value=0 -mvColorValue=0 -mvFloatVectValue=0 -mvSeriesValue=0 -mvRawTexture=0 -mvSubPlots=0 -mvColorMap=0 -mvColorMapRegistry=0 -mvColorMapButton=0 -mvColorMapSlider=0 -mvTemplateRegistry=0 -mvTableCell=0 -mvItemHandlerRegistry=0 -mvInputDouble=0 -mvInputDoubleMulti=0 -mvDragDouble=0 -mvDragDoubleMulti=0 -mvSliderDouble=0 -mvSliderDoubleMulti=0 -mvCustomSeries=0 -mvReservedUUID_0=0 -mvReservedUUID_1=0 -mvReservedUUID_2=0 -mvReservedUUID_3=0 -mvReservedUUID_4=0 -mvReservedUUID_5=0 -mvReservedUUID_6=0 -mvReservedUUID_7=0 -mvReservedUUID_8=0 -mvReservedUUID_9=0 -mvReservedUUID_10=0 diff --git a/dearpygui/_dearpygui_RTD.py b/dearpygui/_dearpygui_RTD.py deleted file mode 100644 index 9044483a0..000000000 --- a/dearpygui/_dearpygui_RTD.py +++ /dev/null @@ -1,9599 +0,0 @@ - -########################################################## -# Dear PyGui User Interface (MODIFIED FOR READTHEDOCS) -# ~ Version: master -# -# Notes: -# * This file is automatically generated. -# -# Resources: -# * FAQ: https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq -# * Homepage: https://github.com/hoffstadt/DearPyGui -# * Wiki: https://github.com/hoffstadt/DearPyGui/wiki -# * Issues: https://github.com/hoffstadt/DearPyGui/issues -# * Discussions: https://github.com/hoffstadt/DearPyGui/discussions -########################################################## - -from typing import List, Any, Callable, Union, Tuple -from contextlib import contextmanager -import warnings -import functools -import inspect -import dearpygui._dearpygui as internal_dpg -from dearpygui._dearpygui import mvBuffer -from dearpygui._dearpygui import mvVec4 -from dearpygui._dearpygui import mvMat4 - -######################################################################################################################## -# User API Index -# -# * Sections -# - Helper Commands -# - Tool Commands -# - Information Commands -# - Configuration Getter Commands -# - Configuration Setter Commands -# - State Commands -# - Viewport Setter Commands -# - Viewport Getter Commands -# - Deprecated Commands -# - Container Context Managers -# - Public _dearpygui Wrappings -# - Constants -# -######################################################################################################################## - -######################################################################################################################## -# Helper Commands -######################################################################################################################## - -def run_callbacks(jobs): - """ New in 1.2. Runs callbacks from the callback queue and checks arguments. """ - - if jobs is None: - pass - else: - for job in jobs: - if job[0] is None: - pass - else: - sig = inspect.signature(job[0]) - args = [] - for arg in range(len(sig.parameters)): - args.append(job[arg+1]) - job[0](*args) - -def get_major_version(): - """ return Dear PyGui Major Version """ - return internal_dpg.get_app_configuration()["major_version"] - -def get_minor_version(): - """ return Dear PyGui Minor Version """ - return internal_dpg.get_app_configuration()["minor_version"] - -def get_dearpygui_version(): - """ return Dear PyGui Version """ - return internal_dpg.get_app_configuration()["version"] - -def configure_item(item : Union[int, str], **kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_item(item, **kwargs) - -def configure_app(**kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_app(**kwargs) - -def configure_viewport(item : Union[int, str], **kwargs) -> None: - """Configures a viewport after creation.""" - internal_dpg.configure_viewport(item, **kwargs) - -def start_dearpygui(): - """Prepares viewport (if not done already). sets up, cleans up, and runs main event loop. - - Returns: - None - """ - - if not internal_dpg.is_viewport_ok(): - raise RuntimeError("Viewport was not created and shown.") - - while(internal_dpg.is_dearpygui_running()): - internal_dpg.render_dearpygui_frame() - - -@contextmanager -def mutex(): - """ Handles locking/unlocking render thread mutex. """ - try: - yield internal_dpg.lock_mutex() - finally: - internal_dpg.unlock_mutex() - - -@contextmanager -def popup(parent: Union[int, str], mousebutton: int = internal_dpg.mvMouseButton_Right, modal: bool=False, tag:Union[int, str]=0, min_size:Union[List[int], Tuple[int, ...]]=[100,100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], no_move: bool=False, no_background: bool=False) -> int: - """A window that will be displayed when a parent item is hovered and the corresponding mouse button has been clicked. By default a popup will shrink fit the items it contains. - This is useful for context windows, and simple modal window popups. - When popups are used a modal they have more avaliable settings (i.e. title, resize, width, height) These - can be set by using configure item. - This is a light wrapper over window. For more control over a modal|popup window use a normal window with the modal|popup keyword - and set the item handler and mouse events manually. - - Args: - parent: The UI item that will need to be hovered. - **mousebutton: The mouse button that will trigger the window to popup. - **modal: Will force the user to interact with the popup. - **min_size: New in 1.4. Minimum window size. - **max_size: New in 1.4. Maximum window size. - **no_move: New in 1.4. Prevents the window from moving based on user input. - **no_background: New in 1.4. Sets Background and border alpha to transparent. - - Returns: - item's uuid - """ - try: - if tag == 0: - _internal_popup_id = internal_dpg.generate_uuid() - else: - _internal_popup_id = tag - _handler_reg_id = internal_dpg.add_item_handler_registry() - internal_dpg.add_item_clicked_handler(mousebutton, parent=internal_dpg.last_item(), callback=lambda: internal_dpg.configure_item(_internal_popup_id, show=True)) - internal_dpg.bind_item_handler_registry(parent, _handler_reg_id) - if modal: - internal_dpg.add_window(modal=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - else: - internal_dpg.add_window(popup=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - internal_dpg.push_container_stack(internal_dpg.last_container()) - yield _internal_popup_id - - finally: - internal_dpg.pop_container_stack() - - -######################################################################################################################## -# Tool Commands -######################################################################################################################## - -def show_style_editor() -> None: - """Shows the standard style editor window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Style) - - -def show_metrics() -> None: - """Shows the standard metrics window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Metrics) - - -def show_about() -> None: - """Shows the standard about window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_About) - - -def show_debug() -> None: - """Shows the standard debug window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Debug) - - -def show_documentation() -> None: - """Shows the standard documentation window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Doc) - - -def show_font_manager() -> None: - """Shows a debug tool for the font manager - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Font) - - -def show_item_registry() -> None: - """Shows the item hierarchy of your application - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_ItemRegistry) - - -######################################################################################################################## -# Information Commands -######################################################################################################################## - -def get_item_slot(item: Union[int, str]) -> Union[int, None]: - """Returns an item's target slot. - - Returns: - slot as a int - """ - return internal_dpg.get_item_info(item)["target"] - - -def is_item_container(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is a container. - - Returns: - status as a bool - """ - return internal_dpg.get_item_info(item)["container"] - - -def get_item_parent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's parent. - - Returns: - parent as a int or None - """ - return internal_dpg.get_item_info(item)["parent"] - - -def get_item_children(item: Union[int, str] , slot: int = -1) -> Union[dict, List[int], None]: - """Provides access to the item's children slots. - - Returns: - A 2-D tuple of children slots ex. ((child_slot_1),(child_slot_2),(child_slot_3),...) or a single slot if slot is used. - """ - if slot < 0 or slot > 4: - return internal_dpg.get_item_info(item)["children"] - return internal_dpg.get_item_info(item)["children"][slot] - - -def get_item_type(item: Union[int, str]) -> Union[str]: - """Gets the item's type. - - Returns: - type as a string or None - """ - return internal_dpg.get_item_info(item)["type"] - - -def get_item_theme(item: Union[int, str]) -> int: - """Gets the item's theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["theme"] - - -def get_item_font(item: Union[int, str]) -> int: - """Gets the item's font. - - Returns: - font's uuid - """ - return internal_dpg.get_item_info(item)["font"] - - -def get_item_disabled_theme(item: Union[int, str]) -> int: - """Gets the item's disabled theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["disabled_theme"] - - -######################################################################################################################## -# Configuration Setter Commands -######################################################################################################################## - -def enable_item(item: Union[int, str]): - """Enables the item. - - Args: - **item: Item to enable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=True) - - -def disable_item(item: Union[int, str]): - """Disables the item. - - Args: - **item: Item to disable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=False) - - -def set_item_label(item: Union[int, str], label: str): - """Sets the item's displayed label, anything after the characters "##" in the name will not be shown. - - Args: - item: Item label will be applied to. - label: Displayed name to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, label=label) - - -def set_item_source(item: Union[int, str], source: Union[int, str]): - """Sets the item's value, to the source's value. Widget's value will now be "linked" to source's value. - - Args: - item: Item to me linked. - source: Source to link to. - - Returns: - None - """ - internal_dpg.configure_item(item, source=source) - - -def set_item_pos(item: Union[int, str], pos: List[float]): - """Sets the item's position. - - Args: - item: Item the absolute position will be applied to. - pos: X and Y positions relative to parent of the item. - - Returns: - None - """ - internal_dpg.configure_item(item, pos=pos) - - -def set_item_width(item: Union[int, str], width: int): - """Sets the item's width. - - Args: - item: Item the Width will be applied to. - width: Width to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, width=width) - - -def set_item_height(item: Union[int, str], height: int): - """Sets the item's height. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, height=height) - - -def set_item_indent(item: Union[int, str], indent: int): - """Sets the item's indent. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, indent=indent) - - -def set_item_track_offset(item: Union[int, str], offset: float): - """Sets the item's track offset. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, track_offset=offset) - - -def set_item_payload_type(item: Union[int, str], payload_type: str): - """Sets the item's payload type. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, payload_type=str) - - -def set_item_callback(item: Union[int, str], callback: Callable): - """Sets the item's callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, callback=callback) - - -def set_item_drag_callback(item: Union[int, str], callback: Callable): - """Sets the item's drag callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drag_callback=callback) - - -def set_item_drop_callback(item: Union[int, str], callback: Callable): - """Sets the item's drop callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drop_callback=callback) - - -def track_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=True) - - -def untrack_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=False) - - -def set_item_user_data(item: Union[int, str], user_data: Any): - """Sets the item's callack_data to any python object. - - Args: - item: Item the callback will be applied to. - user_data: Callback_data to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, user_data=user_data) - - -def show_item(item: Union[int, str]): - """Shows the item. - - Args: - item: Item to show. - - Returns: - None - """ - internal_dpg.configure_item(item, show=True) - - -def hide_item(item: Union[int, str], *, children_only: bool = False): - """Hides the item. - - Args: - **item: Item to hide. - - Returns: - None - """ - if children_only: - children = get_item_children(item) - for child in children: - internal_dpg.configure_item(child, show=False) - else: - internal_dpg.configure_item(item, show=False) - - -######################################################################################################################## -# Configuration Getter Commands -######################################################################################################################## - -def get_item_label(item: Union[int, str]) -> Union[str, None]: - """Gets the item's label. - - Returns: - label as a string or None - """ - return internal_dpg.get_item_configuration(item)["label"] - - -def get_item_filter_key(item: Union[int, str]) -> Union[str, None]: - """Gets the item's filter key. - - Returns: - filter key as a string or None - """ - return internal_dpg.get_item_configuration(item)["filter_key"] - - -def is_item_tracked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is tracked. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["tracked"] - - -def get_item_indent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's indent. - - Returns: - indent as a int or None - """ - return internal_dpg.get_item_configuration(item)["indent"] - - -def get_item_track_offset(item: Union[int, str]) -> Union[float, None]: - """Gets the item's track offset. - - Returns: - track offset as a int or None - """ - return internal_dpg.get_item_configuration(item)["track_offset"] - - -def get_item_width(item: Union[int, str]) -> Union[int, None]: - """Gets the item's width. - - Returns: - width as a int or None - """ - return internal_dpg.get_item_configuration(item)["width"] - - -def get_item_height(item: Union[int, str]) -> Union[int, None]: - """Gets the item's height. - - Returns: - height as a int or None - """ - return internal_dpg.get_item_configuration(item)["height"] - - -def get_item_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["callback"] - - -def get_item_drag_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drag callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drag_callback"] - - -def get_item_drop_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drop callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drop_callback"] - - -def get_item_user_data(item: Union[int, str]) -> Union[Any, None]: - """Gets the item's callback data. - - Returns: - callback data as a python object or None - """ - return internal_dpg.get_item_configuration(item)["user_data"] - - -def get_item_source(item: Union[int, str]) -> Union[str, None]: - """Gets the item's source. - - Returns: - source as a string or None - """ - return internal_dpg.get_item_configuration(item)["source"] - - -######################################################################################################################## -# State Commands -######################################################################################################################## - -def is_item_hovered(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is hovered. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["hovered"] - - -def is_item_active(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is active. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["active"] - - -def is_item_focused(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is focused. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["focused"] - - -def is_item_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["clicked"] - - -def is_item_left_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is left clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["left_clicked"] - - -def is_item_right_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is right clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["right_clicked"] - - -def is_item_middle_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is middle clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["middle_clicked"] - - -def is_item_visible(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is visible. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["visible"] - - -def is_item_edited(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is edited. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["edited"] - - -def is_item_activated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is activated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["activated"] - - -def is_item_deactivated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated"] - - -def is_item_deactivated_after_edit(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated_after_edit. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated_after_edit"] - - -def is_item_toggled_open(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is toggled_open. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["toggled_open"] - - -def is_item_ok(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is ok and can be used. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["ok"] - - -def is_item_shown(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is shown. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["show"] - - -def is_item_enabled(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is enabled. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["enabled"] - - -def get_item_pos(item: Union[int, str]) -> List[int]: - """Returns item's position. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["pos"] - - -def get_available_content_region(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["content_region_avail"] - - -def get_item_rect_size(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_size"] - - -def get_item_rect_min(item: Union[int, str]) -> List[int]: - """Returns item's minimum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_min"] - - -def get_item_rect_max(item: Union[int, str]) -> List[int]: - """Returns item's maximum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_max"] - - -######################################################################################################################## -# Viewport Setter Commands -######################################################################################################################## - -def set_viewport_clear_color(color: List[int]): - """Sets the viewport's clear color. - - Returns: - None - """ - internal_dpg.configure_viewport(0, clear_color=color) - - -def set_viewport_small_icon(icon: str): - """Sets the viewport's small icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, small_icon=icon) - - -def set_viewport_large_icon(icon: str): - """Sets the viewport's large icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, large_icon=icon) - - -def set_viewport_pos(pos: List[float]): - """Sets the viewport's position. - - Returns: - None - """ - internal_dpg.configure_viewport(0, x_pos=pos[0], y_pos=pos[1]) - - -def set_viewport_width(width: int): - """Sets the viewport's width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, width=width) - - -def set_viewport_height(height: int): - """Sets the viewport's height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, height=height) - - -def set_viewport_min_width(width: int): - """Sets the viewport's minimum width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_width=width) - - -def set_viewport_max_width(width: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_width=width) - - -def set_viewport_min_height(height: int): - """Sets the viewport's minimum height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_height=height) - - -def set_viewport_max_height(height: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_height=height) - - -def set_viewport_title(title: str): - """Sets the viewport's title. - - Returns: - None - """ - internal_dpg.configure_viewport(0, title=title) - - -def set_viewport_always_top(value: bool): - """Sets the viewport always on top. - - Returns: - None - """ - internal_dpg.configure_viewport(0, always_on_top=value) - - -def set_viewport_resizable(value: bool): - """Sets the viewport resizable. - - Returns: - None - """ - internal_dpg.configure_viewport(0, resizable=value) - -def set_viewport_vsync(value: bool): - """Sets the viewport vsync. - - Returns: - None - """ - internal_dpg.configure_viewport(0, vsync=value) - - -def set_viewport_decorated(value: bool): - """Sets the viewport to be decorated. - - Returns: - None - """ - internal_dpg.configure_viewport(0, decorated=value) - -######################################################################################################################## -# Viewport Getter Commands -######################################################################################################################## - -def get_viewport_clear_color() ->List[int]: - """Gets the viewport's clear color. - - Returns: - List[int] - """ - return internal_dpg.get_viewport_configuration()["clear_color"] - - -def get_viewport_pos() ->List[float]: - """Gets the viewport's position. - - Returns: - viewport position. - """ - config = internal_dpg.get_viewport_configuration() - x_pos = config["x_pos"] - y_pos = config["y_pos"] - return [x_pos, y_pos] - - -def get_viewport_width() -> int: - """Gets the viewport's width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["width"] - - -def get_viewport_client_width() -> int: - """Gets the viewport's client width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_width"] - - -def get_viewport_client_height() -> int: - """Gets the viewport's client height. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_height"] - - -def get_viewport_height() -> int: - """Gets the viewport's height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["height"] - - -def get_viewport_min_width() -> int: - """Gets the viewport's minimum width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_width"] - - -def get_viewport_max_width() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_width"] - - -def get_viewport_min_height() -> int: - """Gets the viewport's minimum height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_height"] - - -def get_viewport_max_height() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_height"] - - -def get_viewport_title() -> str: - """Gets the viewport's title. - - Returns: - str - """ - return internal_dpg.get_viewport_configuration()["title"] - - -def is_viewport_always_top() -> bool: - """Checks the viewport always on top flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["always_on_top"] - - -def is_viewport_resizable() -> bool: - """Checks the viewport resizable flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["resizable"] - - -def is_viewport_vsync_on() -> bool: - """Checks the viewport vsync flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["vsync"] - - -def is_viewport_decorated() -> bool: - """Checks if the viewport is docorated. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["decorated"] - -########################################################## -# Deprecated Commands -########################################################## - -from typing import Union - - -def deprecated(reason): - - string_types = (type(b''), type(u'')) - - if isinstance(reason, string_types): - - def decorator(func1): - - fmt1 = "Call to deprecated function {name} ({reason})." - - @functools.wraps(func1) - def new_func1(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt1.format(name=func1.__name__, reason=reason), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func1(*args, **kwargs) - - return new_func1 - - return decorator - - elif inspect.isfunction(reason): - - func2 = reason - fmt2 = "Call to deprecated function {name}." - - @functools.wraps(func2) - def new_func2(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt2.format(name=func2.__name__), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func2(*args, **kwargs) - - return new_func2 - -@deprecated("Use 'configure_app(init_file=file)'.") -def set_init_file(file="dpg.ini"): - """ deprecated function """ - internal_dpg.configure_app(init_file=file) - -@deprecated("Use 'configure_app(init_file=file, load_init_file=True)'.") -def load_init_file(file): - """ deprecated function """ - internal_dpg.configure_app(init_file=file, load_init_file=True) - -@deprecated("Use: `is_viewport_ok(...)`") -def is_viewport_created(): - """ deprecated function """ - return internal_dpg.is_viewport_ok() - -@deprecated("Use: \ncreate_viewport()\nsetup_dearpygui()\nshow_viewport()") -def setup_viewport(): - """ deprecated function """ - internal_dpg.create_viewport() - internal_dpg.setup_dearpygui() - internal_dpg.show_viewport() - -@deprecated("Use: `bind_item_theme(...)`") -def set_item_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_theme(item, theme) - -@deprecated("Use: `bind_item_type_disabled_theme(...)`") -def set_item_type_disabled_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_disabled_theme(item, theme) - -@deprecated("Use: `bind_item_type_theme(...)`") -def set_item_type_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_theme(item, theme) - -@deprecated("Use: `bind_item_font(...)`") -def set_item_font(item, font): - """ deprecated function """ - return internal_dpg.bind_item_font(item, font) - -@deprecated("Use: `add_item_activated_handler(...)`") -def add_activated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_activated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_active_handler(...)`") -def add_active_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_active_handler(parent, **kwargs) - -@deprecated("Use: `add_item_clicked_handler(...)`") -def add_clicked_handler(parent, button=-1, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_clicked_handler(parent, button, **kwargs) - -@deprecated("Use: `add_item_deactived_after_edit_handler(...)`") -def add_deactivated_after_edit_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_after_edit_handler(parent, **kwargs) - -@deprecated("Use: `add_item_deactivated_handler(...)`") -def add_deactivated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_edited_handler(...)`") -def add_edited_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_edited_handler(parent, **kwargs) - -@deprecated("Use: `add_item_focus_handler(...)`") -def add_focus_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_focus_handler(parent, **kwargs) - -@deprecated("Use: `add_item_hover_handler(...)`") -def add_hover_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_hover_handler(parent, **kwargs) - -@deprecated("Use: `add_item_resize_handler(...)`") -def add_resize_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_resize_handler(parent, **kwargs) - -@deprecated("Use: `add_item_toggled_open_handler(...)`") -def add_toggled_open_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_toggled_open_handler(parent, **kwargs) - -@deprecated("Use: `add_item_visible_handler(...)`") -def add_visible_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_visible_handler(parent, **kwargs) - -@deprecated("Use: `bind_colormap(...)`") -def set_colormap(item, source): - """ deprecated function """ - return internal_dpg.bind_colormap(item, source) - -@deprecated("Use: `bind_theme(0)`") -def reset_default_theme(item, source): - """ deprecated function """ - return internal_dpg.bind_theme(item, source) - -@deprecated -def set_staging_mode(mode): - """ deprecated function """ - pass - -@deprecated -def add_table_next_column(**kwargs): - """ deprecated function """ - pass - -@deprecated("Use: add_stage") -def add_staging_container(**kwargs): - """ deprecated function """ - return internal_dpg.add_stage(**kwargs) - -@deprecated("Use: stage") -@contextmanager -def staging_container(**kwargs): - """ - deprecated function - Args: - **label (str): Overrides 'name' as label. - **user_data (Any): User data for callbacks. - **use_internal_label (bool): Use generated internal label instead of user specified (appends ### uuid). - **id (Union[int, str]): Unique id used to programmatically refer to the item.If label is unused this will be the label. - Yields: - Union[int, str] - """ - try: - warnings.warn("'staging_container' is deprecated and was changed to 'stage'", DeprecationWarning, 2) - widget = internal_dpg.add_stage_container(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: add_spacer(...)") -def add_spacing(**kwargs): - """ (deprecated function) Adds vertical spacing. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - count (int, optional): Number of spacings to add the size is dependant on the curret style. - Returns: - Union[int, str] - """ - - if 'count' in kwargs.keys(): - count = kwargs["count"] - kwargs.pop("count", None) - internal_dpg.add_group(**kwargs) - internal_dpg.push_container_stack(internal_dpg.last_container()) - for i in range(count): - internal_dpg.add_spacer() - result_id = internal_dpg.pop_container_stack() - else: - result_id = internal_dpg.add_spacer(**kwargs) - return result_id - -@deprecated("Use: add_spacer(...)") -def add_dummy(**kwargs): - """ (deprecated function) Adds a spacer or 'dummy' object. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - Returns: - Union[int, str] - """ - - return internal_dpg.add_spacer(**kwargs) - -@deprecated("Use: `destroy_context()`") -def cleanup_dearpygui(): - """ deprecated function """ - return internal_dpg.destroy_context() - -@deprecated("Use: group(horizontal=True)") -def add_same_line(**kwargs): - """ deprecated function """ - - last_item = internal_dpg.last_item() - group = internal_dpg.add_group(horizontal=True, **kwargs) - internal_dpg.move_item(last_item, parent=group) - internal_dpg.capture_next_item(lambda s: internal_dpg.move_item(s, parent=group)) - return group - -@deprecated("Use: `get_plot_query_rects()`") -def is_plot_queried(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns true if the plot is currently being queried. - - Args: - plot (Union[int, str]): - Returns: - bool - """ - - return len(internal_dpg.get_plot_query_rects(plot, **kwargs)) > 0 - -@deprecated("Use: `get_plot_query_rects()`") -def get_plot_query_area(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns the last/current query area of the plot. If no area is available [0, 0, 0, 0] will be returned. - - Args: - plot (Union[int, str]): - Returns: - Union[List[float], Tuple[float, ...]] - """ - - if rects := internal_dpg.get_plot_query_rects(plot, **kwargs): - return rects[0] - else: - return [0, 0, 0, 0] - -@deprecated("Use: `add_inf_line_series(horizontal=True)`") -def add_hline_series(x, **kwargs): - """ (deprecated function) Adds an infinite horizontal line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs, horizontal=True) - - -@deprecated("Use: `add_inf_line_series()`") -def add_vline_series(x, **kwargs): - """ (deprecated function) Adds an infinite vertical line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs) - - -@deprecated("Use: `add_child_window()`") -def add_child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Returns: - Union[int, str] - """ - - return internal_dpg.add_child_window(**kwargs) - - -@deprecated("Use: `child_window()`") -@contextmanager -def child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_child_window(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: Just not recommended") -def setup_registries() -> None: - """Adds default registries for fonts, handlers, textures, colormaps, and values.""" - internal_dpg.add_font_registry(tag=internal_dpg.mvReservedUUID_0) - internal_dpg.add_handler_registry(tag=internal_dpg.mvReservedUUID_1) - internal_dpg.add_texture_registry(tag=internal_dpg.mvReservedUUID_2) - internal_dpg.add_value_registry(tag=internal_dpg.mvReservedUUID_3) - internal_dpg.add_colormap_registry(tag=internal_dpg.mvReservedUUID_4) - -@deprecated("Useless and doesn't work anyway") -def is_item_search_delayed(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is search delayed. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["delay_search"] - -@deprecated("Use: `set_frame_callback()`") -def set_start_callback(callback): - """ deprecated function """ - return internal_dpg.set_frame_callback(3, callback) - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_chars(chars : Union[List[int], Tuple[int, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds specific font characters to a font. - - Args: - chars (Union[List[int], Tuple[int, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range(first_char : int, last_char : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters to a font. - - Args: - first_char (int): - last_char (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range_hint(hint : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters (mvFontRangeHint_ constants). - - Args: - hint (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -########################################################## -# Container Context Managers -########################################################## - - -@contextmanager -def child_window(**kwargs): - """ Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - flattened_navigation (bool, optional): Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) - always_use_window_padding (bool, optional): Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) - resizable_x (bool, optional): Allow resize from right border (layout direction). Enable .ini saving. - resizable_y (bool, optional): Allow resize from bottom border (layout direction). - always_auto_resize (bool, optional): Combined with auto_resize_x/auto_resize_y. Always measure size even when child is hidden and always disable clipping optimization! NOT RECOMMENDED. - frame_style (bool, optional): Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - auto_resize_x (bool, optional): Enable auto-resizing width based on child content. Read 'IMPORTANT: Size measurement' details above. - auto_resize_y (bool, optional): Enable auto-resizing height based on child content. Read 'IMPORTANT: Size measurement' details above. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_child_window(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def clipper(**kwargs): - """ Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_clipper(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def collapsing_header(**kwargs): - """ Adds a collapsing header to add items to. Must be closed with the end command. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Adds the ability to hide this widget by pressing the (x) in the top right of widget. - default_open (bool, optional): Sets the collapseable header open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_collapsing_header(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def colormap_registry(**kwargs): - """ Adds a colormap registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_colormap_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def custom_series(x, y, channel_count, **kwargs): - """ Adds a custom series to a plot. New in 1.6. - - Args: - x (Any): - y (Any): - channel_count (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - y1 (Any, optional): - y2 (Any, optional): - y3 (Any, optional): - tooltip (bool, optional): Show tooltip when plot is hovered. - no_fit (bool, optional): the item won't be considered for plot fits - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_custom_series(x, y, channel_count, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def drag_payload(**kwargs): - """ User data payload for drag and drop operations. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - drag_data (Any, optional): Drag data - drop_data (Any, optional): Drop data - payload_type (str, optional): - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_drag_payload(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def draw_layer(**kwargs): - """ New in 1.1. Creates a layer useful for grouping drawlist items. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - perspective_divide (bool, optional): New in 1.1. apply perspective divide - depth_clipping (bool, optional): New in 1.1. apply depth clipping - cull_mode (int, optional): New in 1.1. culling mode, mvCullMode_* constants. Only works with triangles currently. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_draw_layer(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def draw_node(**kwargs): - """ New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_draw_node(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def drawlist(width, height, **kwargs): - """ Adds a drawing canvas. - - Args: - width (int): - height (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_drawlist(width, height, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def file_dialog(**kwargs): - """ Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_path (str, optional): Path that the file dialog will default to when opened. - default_filename (str, optional): Default name that will show in the file name input. - file_count (int, optional): Number of visible files in the dialog. - modal (bool, optional): Forces user interaction with the file selector. - directory_selector (bool, optional): Shows only directory/paths as options. Allows selection of directory/paths only. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - cancel_callback (Callable, optional): Callback called when cancel button is clicked. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_file_dialog(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def filter_set(**kwargs): - """ Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc]) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_filter_set(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def font(file, size, **kwargs): - """ Adds font to a font registry. - - Args: - file (str): - size (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - pixel_snapH (bool, optional): Align every glyph to pixel boundary in horizontal direction. Useful if you are rendering text piece-by-piece (e.g. for coloring). - pixel_snapV (bool, optional): Align scaled GlyphOffset.y to pixel boundaries in ImGui. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - default_font (bool, optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_font(file, size, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def font_registry(**kwargs): - """ Adds a font registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_font_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def group(**kwargs): - """ Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. -Enable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - horizontal (bool, optional): Forces child widgets to be added in a horizontal layout. - horizontal_spacing (float, optional): Spacing for the horizontal layout. - xoffset (float, optional): Offset from containing window x item location within group. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_group(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def handler_registry(**kwargs): - """ Adds a handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_handler_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def item_handler_registry(**kwargs): - """ Adds an item handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_item_handler_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def menu(**kwargs): - """ Adds a menu to an existing menu bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_menu(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def menu_bar(**kwargs): - """ Adds a menu bar to a window. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_menu_bar(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node(**kwargs): - """ Adds a node to a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - draggable (bool, optional): Allow node to be draggable. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_node(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node_attribute(**kwargs): - """ Adds a node attribute to a node. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - attribute_type (int, optional): mvNode_Attr_Input, mvNode_Attr_Output, or mvNode_Attr_Static. - shape (int, optional): Pin shape. - category (str, optional): Category - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_node_attribute(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node_editor(**kwargs): - """ Adds a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - delink_callback (Callable, optional): Callback ran when a link is detached. - menubar (bool, optional): Shows or hides the menubar. - minimap (bool, optional): Shows or hides the Minimap. New in 1.6. - minimap_location (int, optional): mvNodeMiniMap_Location_* constants. New in 1.6. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_node_editor(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def plot(**kwargs): - """ Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_title (bool, optional): the plot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_box_select (bool, optional): the user will not be able to box-select with right-click drag - no_mouse_pos (bool, optional): the text of mouse position, in plot coordinates, will not be displayed inside of the plot - query (bool, optional): the user will be able to draw query rects with CTRL + right-click drag - query_color (Union[List[float], Tuple[float, ...]], optional): Color of the query rectangles. - min_query_rects (int, optional): The minimum number of query rects that can be in the plot. If there are less rects than this value, it won't be possible to delete them. - max_query_rects (int, optional): The maximum number of query rects that can be in the plot. If the number is reached any rect added will replace the latest one. (0 means unlimited) - crosshairs (bool, optional): the default mouse cursor will be replaced with a crosshair when hovered - equal_aspects (bool, optional): primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes) - no_inputs (bool, optional): the user will not be able to interact with the plot - no_frame (bool, optional): the ImGui frame will not be rendered - use_local_time (bool, optional): axis labels will be formatted for your timezone when - use_ISO8601 (bool, optional): dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.) - use_24hour_clock (bool, optional): times will be formatted using a 24 hour clock - pan_button (int, optional): mouse button that enables panning when held - pan_mod (int, optional): optional modifier that must be held for panning - context_menu_button (int, optional): opens context menus (if enabled) when clicked - fit_button (int, optional): fits visible data when double clicked - box_select_button (int, optional): begins box selection when pressed and confirms selection when released - box_select_mod (int, optional): begins box selection when pressed and confirms selection when released - box_select_cancel_button (int, optional): cancels active box selection when pressed - query_toggle_mod (int, optional): when held, active box selections turn into queries - horizontal_mod (int, optional): expands active box selection/query horizontally to plot edge when held - vertical_mod (int, optional): expands active box selection/query vertically to plot edge when held - override_mod (int, optional): when held, all input is ignored; used to enable axis/plots as DND sources - zoom_mod (int, optional): optional modifier that must be held for scroll wheel zooming - zoom_rate (int, optional): zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - no_highlight (bool, optional): (deprecated)Removed because not supported from the backend anymore. To control the highlighting of series use the same argument in `add_plot_legend` - no_child (bool, optional): (deprecated)a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications) - anti_aliased (bool, optional): (deprecated)This feature was deprecated in ImPlot. To enable/disable anti_aliasing use `dpg.configure_app()` with the `anti_aliasing` parameters. - query_button (int, optional): (deprecated)This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - query_mod (int, optional): (deprecated)This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_plot(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def plot_axis(axis, **kwargs): - """ Adds an axis to a plot. - - Args: - axis (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - no_label (bool, optional): the axis label will not be displayed - no_gridlines (bool, optional): no grid lines will be displayed - no_tick_marks (bool, optional): no tick marks will be displayed - no_tick_labels (bool, optional): no text labels will be displayed - no_initial_fit (bool, optional): axis will not be initially fit to data extents on the first rendered frame - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_side_switch (bool, optional): the user will not be able to switch the axis side by dragging it - no_highlight (bool, optional): the axis will not have its background highlighted when hovered or held - opposite (bool, optional): axis ticks and labels will be rendered on the conventionally opposite side (i.e, right or top) - foreground_grid (bool, optional): grid lines will be displayed in the foreground (i.e. on top of data) instead of the background - tick_format (str, optional): Sets a custom tick label formatter - scale (int, optional): Sets the axis' scale. Can have only mvPlotScale_ values - invert (bool, optional): the axis values will be inverted (i.e. growing from right to left) - auto_fit (bool, optional): axis will be auto-fitting to data extents - range_fit (bool, optional): axis will only fit points if the point is in the visible range of the **orthogonal** axis - pan_stretch (bool, optional): panning in a locked or constrained state will cause the axis to stretch if possible - lock_min (bool, optional): the axis minimum value will be locked when panning/zooming - lock_max (bool, optional): the axis maximum value will be locked when panning/zooming - id (Union[int, str], optional): (deprecated) - log_scale (bool, optional): (deprecated)Old way to set log scale in the axis. Use 'scale' argument instead. - time (bool, optional): (deprecated)Old way to set time scale in the axis. Use 'scale' argument instead. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_plot_axis(axis, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def stage(**kwargs): - """ Adds a stage. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_stage(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def subplots(rows, columns, **kwargs): - """ Adds a collection of plots. - - Args: - rows (int): - columns (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - row_ratios (Union[List[float], Tuple[float, ...]], optional): - column_ratios (Union[List[float], Tuple[float, ...]], optional): - no_title (bool, optional): the subplot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_resize (bool, optional): resize splitters between subplot cells will be not be provided - no_align (bool, optional): subplot edges will not be aligned vertically or horizontally - share_series (bool, optional): when set to True, series from all sub-plots will be shared to some extent, using a single common color set and showing them in a single legend in the subplots item. Otherwise each plot will be independent from others and will have its own legend - link_rows (bool, optional): link the y-axis limits of all plots in each row (does not apply auxiliary y-axes) - link_columns (bool, optional): link the x-axis limits of all plots in each column - link_all_x (bool, optional): link the x-axis limits in every plot in the subplot - link_all_y (bool, optional): link the y-axis limits in every plot in the subplot (does not apply to auxiliary y-axes) - column_major (bool, optional): subplots are added in column major order instead of the default row major order - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_subplots(rows, columns, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def synced_tables(**kwargs): - """ Links all tables that are immediate children of this container so that they share their state (mostly column sizes). Other children are rendered as is. This is an experimental feature, use with caution. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_synced_tables(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tab(**kwargs): - """ Adds a tab to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Creates a button on the tab that can hide the tab. - no_tooltip (bool, optional): Disable tooltip for the given tab. - order_mode (int, optional): set using a constant: mvTabOrder_Reorderable: allows reordering, mvTabOrder_Fixed: fixed ordering, mvTabOrder_Leading: adds tab to front, mvTabOrder_Trailing: adds tab to back - unsaved_document (bool, optional): Display a dot next to the title. - no_close_with_middle_click (bool, optional): Disable closing this tab (if closable==True) by clicking with middle mouse button. - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_tab(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tab_bar(**kwargs): - """ Adds a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - reorderable (bool, optional): Allows for the user to change the order of the tabs. - tab_list_popup_button (bool, optional): Show a button to select active tab from a dropdown list. - no_close_with_middle_click (bool, optional): Disable closing tabs (that have closable=True) by clicking with middle mouse button. - no_scrolling_buttons (bool, optional): Disable left/right scrolling buttons when tab buttons don't fit the container width. - no_tooltip (bool, optional): Disable tooltips when hovering a tab with a long name. - draw_selected_overline (bool, optional): Draw selected overline markers over selected tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_tab_bar(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table(**kwargs): - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - header_row (bool, optional): show headers at the top of the columns - clipper (bool, optional): Use clipper (rows must be same height). - inner_width (int, optional): - policy (int, optional): - freeze_rows (int, optional): - freeze_columns (int, optional): - sort_multi (bool, optional): Hold shift when clicking headers to sort on multiple column. - sort_tristate (bool, optional): Allow no sorting, disable default sorting. - resizable (bool, optional): Enable resizing columns - reorderable (bool, optional): Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - hideable (bool, optional): Enable hiding/disabling columns in context menu. - sortable (bool, optional): Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - context_menu_in_body (bool, optional): Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - row_background (bool, optional): Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - borders_innerH (bool, optional): Draw horizontal borders between rows. - borders_outerH (bool, optional): Draw horizontal borders at the top and bottom. - borders_innerV (bool, optional): Draw vertical borders between columns. - borders_outerV (bool, optional): Draw vertical borders on the left and right sides. - no_host_extendX (bool, optional): Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - no_host_extendY (bool, optional): Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - no_keep_columns_visible (bool, optional): Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - precise_widths (bool, optional): Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - no_clip (bool, optional): Disable clipping rectangle for every individual columns. - pad_outerX (bool, optional): Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. - no_pad_outerX (bool, optional): Default if BordersOuterV is off. Disable outer-most padding. - no_pad_innerX (bool, optional): Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - scrollX (bool, optional): Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - scrollY (bool, optional): Enable vertical scrolling. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_table(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table_cell(**kwargs): - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_table_cell(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table_row(**kwargs): - """ Adds a table row. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_table_row(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def template_registry(**kwargs): - """ Adds a template registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_template_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def texture_registry(**kwargs): - """ Adds a dynamic texture. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_texture_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def theme(**kwargs): - """ Adds a theme. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - default_theme (bool, optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_theme(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def theme_component(item_type=0, **kwargs): - """ Adds a theme component. - - Args: - item_type (int, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - enabled_state (bool, optional): - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_theme_component(item_type, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tooltip(parent, **kwargs): - """ Adds a tooltip window. - - Args: - parent (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - delay (float, optional): Activation delay: time, in seconds, during which the mouse should stay still in order to display the tooltip. May be zero for instant activation. - hide_on_activity (bool, optional): Hide the tooltip if the user has moved the mouse. If False, the tooltip will follow mouse pointer. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_tooltip(parent, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tree_node(**kwargs): - """ Adds a tree node to add items to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_open (bool, optional): Sets the tree node open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - selectable (bool, optional): Makes the tree selectable. - span_text_width (bool, optional): Makes hitbox and highlight only cover the label. - span_full_width (bool, optional): Extend hit box to the left-most and right-most edges (cover the indent area). - catch_nav_left (bool, optional): Keyboard navigation: left arrow within this node's children, if unhandled, moves focus to this node. When setting it to True on a node, better set it on all children nodes in the subtree as well, otherwise it might give unexpected navigation jumps. - lines (int, optional): Experimental. Draw lines connecting tree_node hierarchy. One of dpg.mvTreeLines constants. To work correctly, must be configured the same way in every tree node. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_tree_node(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def value_registry(**kwargs): - """ Adds a value registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_value_registry(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def viewport_drawlist(**kwargs): - """ A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - front (bool, optional): Draws to the front of the view port instead of the back. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_viewport_drawlist(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def viewport_menu_bar(**kwargs): - """ Adds a menubar to the viewport. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_viewport_menu_bar(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def window(**kwargs): - """ Creates a new window for following items to be added to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - menubar (bool, optional): Shows or hides the menubar. - collapsed (bool, optional): Collapse the window. - autosize (bool, optional): Autosized the window to fit it's items. - no_resize (bool, optional): Allows for the window size to be changed or fixed. - unsaved_document (bool, optional): Show a special marker if the document is not saved. - no_title_bar (bool, optional): Title name for the title bar of the window. - no_move (bool, optional): Allows for the window's position to be changed or fixed. - no_scrollbar (bool, optional): Disable scrollbars. (window can still scroll with mouse or programmatically) - no_collapse (bool, optional): Disable user collapsing window by double-clicking on it. - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear. (off by default) - no_focus_on_appearing (bool, optional): Disable taking focus when transitioning from hidden to visible state. - no_bring_to_front_on_focus (bool, optional): Disable bringing window to front when taking focus. (e.g. clicking on it or programmatically giving it focus) - no_close (bool, optional): Disable user closing the window by removing the close button. - no_background (bool, optional): Sets Background and border alpha to transparent. - modal (bool, optional): Fills area behind window according to the theme and disables user ability to interact with anything except the window. - popup (bool, optional): Fills area behind window according to the theme, removes title bar, collapse and close. Window can be closed by selecting area in the background behind the window. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - no_open_over_existing_popup (bool, optional): Don't open if there's already a popup - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - no_docking (bool, optional): Disable docking of this window - copy_contents_shortcut (bool, optional): Experimental. If True, window contents can be copied to clipboard by pressing Ctrl+C. Might be useful for message boxes. - on_close (Callable, optional): Callback ran when window is closed. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_window(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -########################################################## -# Core Wrappings -########################################################## - -def add_2d_histogram_series(x, y, **kwargs): - """ Adds a 2d histogram series. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - xbins (int, optional): - ybins (int, optional): - xmin_range (float, optional): set the min x range value, the values under this min will be ignored - xmax_range (float, optional): set the max x range value, the values over this max will be ignored - ymin_range (float, optional): set the min y range value, the values under this min will be ignored - ymax_range (float, optional): set the max y range value, the values over this max will be ignored. If all xmin, xmax, ymin and ymax are 0.0, then the values will be the min and max values of the series - density (bool, optional): counts will be normalized, i.e. the PDF will be visualized - outliers (bool, optional): exclude values outside the specified histogram range from the count used for normalizing - col_major (bool, optional): data will be read in column major order - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_2d_histogram_series(x, y, **kwargs) - -def add_3d_slider(**kwargs): - """ Adds a 3D box slider. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - max_x (float, optional): Applies upper limit to slider. - max_y (float, optional): Applies upper limit to slider. - max_z (float, optional): Applies upper limit to slider. - min_x (float, optional): Applies lower limit to slider. - min_y (float, optional): Applies lower limit to slider. - min_z (float, optional): Applies lower limit to slider. - scale (float, optional): Size of the widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_3d_slider(**kwargs) - -def add_alias(alias, item): - """ Adds an alias. - - Args: - alias (str): - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.add_alias(alias, item) - -def add_area_series(x, y, **kwargs): - """ Adds an area series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - fill (Union[List[int], Tuple[int, ...]], optional): - contribute_to_bounds (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_area_series(x, y, **kwargs) - -def add_axis_tag(**kwargs): - """ Adds custom labels to axes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - default_value (float, optional): - color (Union[List[int], Tuple[int, ...]], optional): - auto_rounding (bool, optional): When enabled, the value displayed on the tag will be automatically rounded to the precision of other values displayed at axis' ticks. Only makes sense when label is not set, i.e. when the tag displays its location on the axis. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_axis_tag(**kwargs) - -def add_bar_group_series(values, label_ids, group_size, **kwargs): - """ Adds a bar groups series to a plot. - - Args: - values (Any): - label_ids (Union[List[str], Tuple[str, ...]]): Label of each bar in a group - group_size (int): Number of bars in a group - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - group_width (float, optional): Size of bar groups - shift (int, optional): The position on the x axis where to start plotting bar groups - horizontal (bool, optional): bar groups will be rendered horizontally on the current y-axis - stacked (bool, optional): items in a group will be stacked on top of each other - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_bar_group_series(values, label_ids, group_size, **kwargs) - -def add_bar_series(x, y, **kwargs): - """ Adds a bar series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - weight (float, optional): - horizontal (bool, optional): bars will be rendered horizontally on the current y-axis - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_bar_series(x, y, **kwargs) - -def add_bool_value(**kwargs): - """ Adds a bool value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (bool, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_bool_value(**kwargs) - -def add_button(**kwargs): - """ Adds a button. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - small (bool, optional): Shrinks the size of the button to the text of the label it contains. Useful for embedding in text. - arrow (bool, optional): Displays an arrow in place of the text string. This requires the direction keyword. - direction (int, optional): Sets the cardinal direction for the arrow by using constants mvDir_Left, mvDir_Up, mvDir_Down, mvDir_Right, mvDir_None. Arrow keyword must be set to True. - repeat (bool, optional): Hold to continuosly repeat the click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_button(**kwargs) - -def add_candle_series(dates, opens, closes, lows, highs, **kwargs): - """ Adds a candle series to a plot. - - Args: - dates (Any): - opens (Any): - closes (Any): - lows (Any): - highs (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - bull_color (Union[List[int], Tuple[int, ...]], optional): - bear_color (Union[List[int], Tuple[int, ...]], optional): - weight (float, optional): - tooltip (bool, optional): - time_unit (int, optional): mvTimeUnit_* constants. Default mvTimeUnit_Day. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_candle_series(dates, opens, closes, lows, highs, **kwargs) - -def add_char_remap(source, target, **kwargs): - """ Remaps a character. - - Args: - source (int): - target (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_char_remap(source, target, **kwargs) - -def add_checkbox(**kwargs): - """ Adds a checkbox. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): Sets the default value of the checkmark - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_checkbox(**kwargs) - -def add_child_window(**kwargs): - """ Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - flattened_navigation (bool, optional): Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) - always_use_window_padding (bool, optional): Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) - resizable_x (bool, optional): Allow resize from right border (layout direction). Enable .ini saving. - resizable_y (bool, optional): Allow resize from bottom border (layout direction). - always_auto_resize (bool, optional): Combined with auto_resize_x/auto_resize_y. Always measure size even when child is hidden and always disable clipping optimization! NOT RECOMMENDED. - frame_style (bool, optional): Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - auto_resize_x (bool, optional): Enable auto-resizing width based on child content. Read 'IMPORTANT: Size measurement' details above. - auto_resize_y (bool, optional): Enable auto-resizing height based on child content. Read 'IMPORTANT: Size measurement' details above. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_child_window(**kwargs) - -def add_clipper(**kwargs): - """ Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_clipper(**kwargs) - -def add_collapsing_header(**kwargs): - """ Adds a collapsing header to add items to. Must be closed with the end command. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Adds the ability to hide this widget by pressing the (x) in the top right of widget. - default_open (bool, optional): Sets the collapseable header open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_collapsing_header(**kwargs) - -def add_color_button(default_value=(0, 0, 0, 255), **kwargs): - """ Adds a color button. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_border (bool, optional): Disable border around the image. - no_drag_drop (bool, optional): Disable ability to drag and drop small preview (color square) to apply colors to other items. - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - no_tooltip (bool, optional): Disable tooltip when hovering the button. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_color_button(default_value, **kwargs) - -def add_color_edit(default_value=(0, 0, 0, 255), **kwargs): - """ Adds an RGBA color editor. Left clicking the small color preview will provide a color picker. Click and draging the small color preview will copy the color to be applied on any other color widget. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_picker (bool, optional): Disable picker popup when color square is clicked. - no_options (bool, optional): Disable toggling options menu when right-clicking on inputs/small preview. - no_small_preview (bool, optional): Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown. - no_inputs (bool, optional): Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square) - no_tooltip (bool, optional): Disable tooltip when hovering the preview. - no_label (bool, optional): Disable display of inline text label. - no_drag_drop (bool, optional): Disable ability to drag and drop small preview (color square) to apply colors to other items. - alpha_bar (bool, optional): Show vertical alpha bar/gradient in picker. - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - display_mode (int, optional): mvColorEdit_rgb, mvColorEdit_hsv, or mvColorEdit_hex - display_type (int, optional): mvColorEdit_uint8 or mvColorEdit_float - input_mode (int, optional): mvColorEdit_input_* values - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_color_edit(default_value, **kwargs) - -def add_color_picker(default_value=(0, 0, 0, 255), **kwargs): - """ Adds an RGB color picker. Right click the color picker for options. Click and drag the color preview to copy the color and drop on any other color widget to apply. Right Click allows the style of the color picker to be changed. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_side_preview (bool, optional): Disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden. - no_small_preview (bool, optional): Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown. - no_inputs (bool, optional): Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square) - no_tooltip (bool, optional): Disable tooltip when hovering the preview. - no_label (bool, optional): Disable display of inline text label. - alpha_bar (bool, optional): Show vertical alpha bar/gradient in picker. - display_rgb (bool, optional): Override _display_ type among RGB/HSV/Hex. - display_hsv (bool, optional): Override _display_ type among RGB/HSV/Hex. - display_hex (bool, optional): Override _display_ type among RGB/HSV/Hex. - picker_mode (int, optional): mvColorPicker_bar or mvColorPicker_wheel - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - display_type (int, optional): mvColorEdit_uint8 or mvColorEdit_float - input_mode (int, optional): mvColorEdit_input_* values. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_color_picker(default_value, **kwargs) - -def add_color_value(**kwargs): - """ Adds a color value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_color_value(**kwargs) - -def add_colormap(colors, qualitative, **kwargs): - """ Adds a legend that pairs colors with normalized value 0.0->1.0. Each color will be This is typically used with a heat series. (ex. [[0, 0, 0, 255], [255, 255, 255, 255]] will be mapped to a soft transition from 0.0-1.0) - - Args: - colors (Any): colors that will be mapped to the normalized value 0.0->1.0 - qualitative (bool): Qualitative will create hard transitions for color boundries across the value range when enabled. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_colormap(colors, qualitative, **kwargs) - -def add_colormap_button(default_value=(0, 0, 0, 255), **kwargs): - """ Adds a button that a color map can be bound to. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_colormap_button(default_value, **kwargs) - -def add_colormap_registry(**kwargs): - """ Adds a colormap registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_colormap_registry(**kwargs) - -def add_colormap_scale(**kwargs): - """ Adds a legend that pairs values with colors. This is typically used with a heat series. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - colormap (Union[int, str], optional): mvPlotColormap_* constants or mvColorMap uuid from a color map registry - min_scale (float, optional): Sets the min number of the color scale. Typically is the same as the min scale from the heat series. - max_scale (float, optional): Sets the max number of the color scale. Typically is the same as the max scale from the heat series. - format (str, optional): Formatting used for the labels. - reverse_dir (bool, optional): invert the colormap bar and axis scale (this only affects rendering; if you only want to reverse the scale mapping, make scale_min > scale_max) - mirror (bool, optional): render the colormap label and tick labels on the opposite side - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_colormap_scale(**kwargs) - -def add_colormap_slider(**kwargs): - """ Adds a color slider that a color map can be bound to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_colormap_slider(**kwargs) - -def add_combo(items=(), **kwargs): - """ Adds a combo dropdown that allows a user to select a single option from a drop down window. All items will be shown as selectables on the dropdown. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown in the drop down window. Can consist of any combination of types but will convert all items to strings to be shown. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): Sets a selected item from the drop down by specifying the string value. - popup_align_left (bool, optional): Align the contents on the popup toward the left. - no_arrow_button (bool, optional): Display the preview box without the square arrow button indicating dropdown activity. - no_preview (bool, optional): Display only the square arrow button and not the selected value. - fit_width (bool, optional): Fit the available width. - height_mode (int, optional): Controlls the number of items shown in the dropdown by the constants mvComboHeight_Small, mvComboHeight_Regular, mvComboHeight_Large, mvComboHeight_Largest - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_combo(items, **kwargs) - -def add_custom_series(x, y, channel_count, **kwargs): - """ Adds a custom series to a plot. New in 1.6. - - Args: - x (Any): - y (Any): - channel_count (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - y1 (Any, optional): - y2 (Any, optional): - y3 (Any, optional): - tooltip (bool, optional): Show tooltip when plot is hovered. - no_fit (bool, optional): the item won't be considered for plot fits - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_custom_series(x, y, channel_count, **kwargs) - -def add_date_picker(**kwargs): - """ Adds a date picker. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (dict, optional): - level (int, optional): Use avaliable constants. mvDatePickerLevel_Day, mvDatePickerLevel_Month, mvDatePickerLevel_Year - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_date_picker(**kwargs) - -def add_digital_series(x, y, **kwargs): - """ Adds a digital series to a plot. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_digital_series(x, y, **kwargs) - -def add_double4_value(**kwargs): - """ Adds a double value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Any, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_double4_value(**kwargs) - -def add_double_value(**kwargs): - """ Adds a double value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (float, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_double_value(**kwargs) - -def add_drag_double(**kwargs): - """ Adds drag for a single double value. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_double(**kwargs) - -def add_drag_doublex(**kwargs): - """ Adds drag input for a set of double values up to 4. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - size (int, optional): Number of doubles to be displayed. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_doublex(**kwargs) - -def add_drag_float(**kwargs): - """ Adds drag for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_float(**kwargs) - -def add_drag_floatx(**kwargs): - """ Adds drag input for a set of float values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - size (int, optional): Number of floats to be displayed. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_floatx(**kwargs) - -def add_drag_int(**kwargs): - """ Adds drag for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (int, optional): Applies a limit only to draging entry only. - max_value (int, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_int(**kwargs) - -def add_drag_intx(**kwargs): - """ Adds drag input for a set of int values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - size (int, optional): Number of ints to be displayed. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (int, optional): Applies a limit only to draging entry only. - max_value (int, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_intx(**kwargs) - -def add_drag_line(**kwargs): - """ Adds a drag line to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (float, optional): - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - show_label (bool, optional): - vertical (bool, optional): - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_line(**kwargs) - -def add_drag_payload(**kwargs): - """ User data payload for drag and drop operations. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - drag_data (Any, optional): Drag data - drop_data (Any, optional): Drop data - payload_type (str, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_payload(**kwargs) - -def add_drag_point(**kwargs): - """ Adds a drag point to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - show_label (bool, optional): - offset (Union[List[float], Tuple[float, ...]], optional): Offset of the label, in pixels, relative to the drag point itself - clamped (bool, optional): Keep the label within the visible area of the plot even if the drag point itself goes outside of the visible area - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_point(**kwargs) - -def add_drag_rect(**kwargs): - """ Adds a drag rectangle to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): The coordinates are specified in a sequence of: (xmin, ymin, xmax, ymax) - color (Union[List[int], Tuple[int, ...]], optional): - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_drag_rect(**kwargs) - -def add_draw_layer(**kwargs): - """ New in 1.1. Creates a layer useful for grouping drawlist items. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - perspective_divide (bool, optional): New in 1.1. apply perspective divide - depth_clipping (bool, optional): New in 1.1. apply depth clipping - cull_mode (int, optional): New in 1.1. culling mode, mvCullMode_* constants. Only works with triangles currently. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_draw_layer(**kwargs) - -def add_draw_node(**kwargs): - """ New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_draw_node(**kwargs) - -def add_drawlist(width, height, **kwargs): - """ Adds a drawing canvas. - - Args: - width (int): - height (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_drawlist(width, height, **kwargs) - -def add_dynamic_texture(width, height, default_value, **kwargs): - """ Adds a dynamic texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_dynamic_texture(width, height, default_value, **kwargs) - -def add_error_series(x, y, negative, positive, **kwargs): - """ Adds an error series to a plot. - - Args: - x (Any): - y (Any): - negative (Any): - positive (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - contribute_to_bounds (bool, optional): - horizontal (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_error_series(x, y, negative, positive, **kwargs) - -def add_file_dialog(**kwargs): - """ Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_path (str, optional): Path that the file dialog will default to when opened. - default_filename (str, optional): Default name that will show in the file name input. - file_count (int, optional): Number of visible files in the dialog. - modal (bool, optional): Forces user interaction with the file selector. - directory_selector (bool, optional): Shows only directory/paths as options. Allows selection of directory/paths only. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - cancel_callback (Callable, optional): Callback called when cancel button is clicked. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_file_dialog(**kwargs) - -def add_file_extension(extension, **kwargs): - """ Creates a file extension filter option in the file dialog. - - Args: - extension (str): Extension that will show as an when the parent is a file dialog. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - custom_text (str, optional): Replaces the displayed text in the drop down for this extension. - color (Union[List[int], Tuple[int, ...]], optional): Color for the text that will be shown with specified extensions. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_file_extension(extension, **kwargs) - -def add_filter_set(**kwargs): - """ Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc]) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_filter_set(**kwargs) - -def add_float4_value(**kwargs): - """ Adds a float4 value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_float4_value(**kwargs) - -def add_float_value(**kwargs): - """ Adds a float value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (float, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_float_value(**kwargs) - -def add_float_vect_value(**kwargs): - """ Adds a float vect value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_float_vect_value(**kwargs) - -def add_font(file, size, **kwargs): - """ Adds font to a font registry. - - Args: - file (str): - size (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - pixel_snapH (bool, optional): Align every glyph to pixel boundary in horizontal direction. Useful if you are rendering text piece-by-piece (e.g. for coloring). - pixel_snapV (bool, optional): Align scaled GlyphOffset.y to pixel boundaries in ImGui. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - default_font (bool, optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_font(file, size, **kwargs) - -def add_font_registry(**kwargs): - """ Adds a font registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_font_registry(**kwargs) - -def add_group(**kwargs): - """ Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. -Enable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - horizontal (bool, optional): Forces child widgets to be added in a horizontal layout. - horizontal_spacing (float, optional): Spacing for the horizontal layout. - xoffset (float, optional): Offset from containing window x item location within group. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_group(**kwargs) - -def add_handler_registry(**kwargs): - """ Adds a handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_handler_registry(**kwargs) - -def add_heat_series(x, rows, cols, **kwargs): - """ Adds a heat series to a plot. - - Args: - x (Any): - rows (int): - cols (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - scale_min (float, optional): Sets the color scale min. Typically paired with the color scale widget scale_min. - scale_max (float, optional): Sets the color scale max. Typically paired with the color scale widget scale_max. - bounds_min (Any, optional): - bounds_max (Any, optional): - format (str, optional): - contribute_to_bounds (bool, optional): - col_major (bool, optional): data will be read in column major order - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_heat_series(x, rows, cols, **kwargs) - -def add_histogram_series(x, **kwargs): - """ Adds a histogram series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - bins (int, optional): - bar_scale (float, optional): - min_range (float, optional): set the min range value, the values under this min will be ignored - max_range (float, optional): set the max range value, the values over this max will be ignored. If both min and max are 0.0, then the values will be the min and max values of the series - cumulative (bool, optional): each bin will contain its count plus the counts of all previous bins - density (bool, optional): counts will be normalized, i.e. the PDF will be visualized, or the CDF will be visualized if Cumulative is also set - outliers (bool, optional): exclude values outside the specifed histogram range from the count toward normalizing and cumulative counts - horizontal (bool, optional): histogram bars will be rendered horizontally - contribute_to_bounds (bool, optional): - id (Union[int, str], optional): (deprecated) - cumlative (bool, optional): (deprecated)Deprecated because of typo - Returns: - Union[int, str] - """ - - return internal_dpg.add_histogram_series(x, **kwargs) - -def add_image(texture_tag, **kwargs): - """ Adds an image from a specified texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) for texture coordinates will generally display the entire texture. - - Args: - texture_tag (Union[int, str]): The texture_tag should come from a texture that was added to a texture registry. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - tint_color (Union[List[float], Tuple[float, ...]], optional): Applies a color tint to the entire texture. - border_color (Union[List[float], Tuple[float, ...]], optional): Displays a border of the specified color around the texture. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates min point. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates max point. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_image(texture_tag, **kwargs) - -def add_image_button(texture_tag, **kwargs): - """ Adds an button with a texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) texture coordinates will generally display the entire texture - - Args: - texture_tag (Union[int, str]): The texture_tag should come from a texture that was added to a texture registry. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - tint_color (Union[List[float], Tuple[float, ...]], optional): Applies a color tint to the entire texture. - background_color (Union[List[float], Tuple[float, ...]], optional): Displays a border of the specified color around the texture. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates min point. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates max point. - id (Union[int, str], optional): (deprecated) - frame_padding (int, optional): (deprecated)Empty space around the outside of the texture. Button will show around the texture. - Returns: - Union[int, str] - """ - - return internal_dpg.add_image_button(texture_tag, **kwargs) - -def add_image_series(texture_tag, bounds_min, bounds_max, **kwargs): - """ Adds an image series to a plot. - - Args: - texture_tag (Union[int, str]): - bounds_min (Any): - bounds_max (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - uv_min (Union[List[float], Tuple[float, ...]], optional): normalized texture coordinates - uv_max (Union[List[float], Tuple[float, ...]], optional): normalized texture coordinates - tint_color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_image_series(texture_tag, bounds_min, bounds_max, **kwargs) - -def add_inf_line_series(x, **kwargs): - """ Adds an infinite line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - horizontal (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs) - -def add_input_double(**kwargs): - """ Adds input for an double. Useful when input float is not accurate enough. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (float, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (float, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (float, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_double(**kwargs) - -def add_input_doublex(**kwargs): - """ Adds multi double input for up to 4 double values. Useful when input float mulit is not accurate enough. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (float, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_doublex(**kwargs) - -def add_input_float(**kwargs): - """ Adds input for an float. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (float, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (float, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (float, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_float(**kwargs) - -def add_input_floatx(**kwargs): - """ Adds multi float input for up to 4 float values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (float, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_floatx(**kwargs) - -def add_input_int(**kwargs): - """ Adds input for an int. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - min_value (int, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (int, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (int, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (int, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_int(**kwargs) - -def add_input_intx(**kwargs): - """ Adds multi int input for up to 4 integer values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - min_value (int, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (int, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_intx(**kwargs) - -def add_input_text(**kwargs): - """ Adds input for text. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): - hint (str, optional): Displayed only when value is an empty string. Will reappear if input value is set to empty string. Will not show if default value is anything other than default empty string. - multiline (bool, optional): Allows for multiline text input. - no_spaces (bool, optional): Filter out spaces and tabs. - uppercase (bool, optional): Automatically make all inputs uppercase. - tab_input (bool, optional): Allows tabs to be input into the string value instead of changing item focus. - decimal (bool, optional): Only allow characters 0123456789.+-*/ - hexadecimal (bool, optional): Only allow characters 0123456789ABCDEFabcdef - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - password (bool, optional): Display all input characters as '*'. - scientific (bool, optional): Only allow characters 0123456789.+-*/eE (Scientific notation input) - on_enter (bool, optional): Only runs callback on enter key press. - auto_select_all (bool, optional): Select entire text when first taking mouse focus - ctrl_enter_for_new_line (bool, optional): In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). - no_horizontal_scroll (bool, optional): Disable following the cursor horizontally - always_overwrite (bool, optional): Overwrite mode - no_undo_redo (bool, optional): Disable undo/redo. - escape_clears_all (bool, optional): Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) - elide_left (bool, optional): When text doesn't fit an inactive input field, clip it on the left side and ensure the right side stays visible. Useful for path/filenames. Single-line inputs only. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_input_text(**kwargs) - -def add_int4_value(**kwargs): - """ Adds a int4 value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[int], Tuple[int, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_int4_value(**kwargs) - -def add_int_value(**kwargs): - """ Adds a int value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (int, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_int_value(**kwargs) - -def add_item_activated_handler(**kwargs): - """ Adds a activated handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_activated_handler(**kwargs) - -def add_item_active_handler(**kwargs): - """ Adds a active handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_active_handler(**kwargs) - -def add_item_clicked_handler(button=-1, **kwargs): - """ Adds a clicked handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_clicked_handler(button, **kwargs) - -def add_item_deactivated_after_edit_handler(**kwargs): - """ Adds a deactivated after edit handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_deactivated_after_edit_handler(**kwargs) - -def add_item_deactivated_handler(**kwargs): - """ Adds a deactivated handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_deactivated_handler(**kwargs) - -def add_item_double_clicked_handler(button=-1, **kwargs): - """ Adds a double click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_double_clicked_handler(button, **kwargs) - -def add_item_edited_handler(**kwargs): - """ Adds an edited handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_edited_handler(**kwargs) - -def add_item_focus_handler(**kwargs): - """ Adds a focus handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - event_type (int, optional): What kind of events to track: just got focus (mvEventType_Enter), currently having focus (mvEventType_On), lost focus (mvEventType_Leave). Can be a combination of these flags. Defaults to mvEventType_On. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_focus_handler(**kwargs) - -def add_item_handler_registry(**kwargs): - """ Adds an item handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_handler_registry(**kwargs) - -def add_item_hover_handler(**kwargs): - """ Adds a hover handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - event_type (int, optional): What kind of events to track: mouse-in (mvEventType_Enter), mouse-over (mvEventType_On), mouse-out (mvEventType_Leave). Can be a combination of these flags. Defaults to mouse-over. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_hover_handler(**kwargs) - -def add_item_resize_handler(**kwargs): - """ Adds a resize handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_resize_handler(**kwargs) - -def add_item_scroll_handler(**kwargs): - """ Adds a scroll handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_scroll_handler(**kwargs) - -def add_item_toggled_open_handler(**kwargs): - """ Adds a togged open handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - two_way (bool, optional): Trigger on both 'opened' and 'closed' events, i.e. when the 'opened' state is toggled between the two values. If False, some containers will trigger it only on the 'opened' event. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_toggled_open_handler(**kwargs) - -def add_item_visible_handler(**kwargs): - """ Adds a visible handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_item_visible_handler(**kwargs) - -def add_key_down_handler(key=internal_dpg.mvKey_None, **kwargs): - """ Adds a key down handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_key_down_handler(key, **kwargs) - -def add_key_press_handler(key=internal_dpg.mvKey_None, **kwargs): - """ Adds a key press handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_key_press_handler(key, **kwargs) - -def add_key_release_handler(key=internal_dpg.mvKey_None, **kwargs): - """ Adds a key release handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_key_release_handler(key, **kwargs) - -def add_knob_float(**kwargs): - """ Adds a knob that rotates based on change in x mouse position. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - min_value (float, optional): Applies lower limit to value. - max_value (float, optional): Applies upper limit to value. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_knob_float(**kwargs) - -def add_line_series(x, y, **kwargs): - """ Adds a line series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - segments (bool, optional): a line segment will be rendered from every two consecutive points - loop (bool, optional): the last and first point will be connected to form a closed loop - skip_nan (bool, optional): NaNs values will be skipped instead of rendered as missing data - no_clip (bool, optional): markers (if displayed) on the edge of a plot will not be clipped - shaded (bool, optional): a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_line_series(x, y, **kwargs) - -def add_listbox(items=(), **kwargs): - """ Adds a listbox. If height is not large enough to show all items a scroll bar will appear. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown in the listbox. Can consist of any combination of types. All items will be displayed as strings. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): String value of the item that will be selected by default. - num_items (int, optional): Expands the height of the listbox to show specified number of items. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_listbox(items, **kwargs) - -def add_loading_indicator(**kwargs): - """ Adds a rotating animated loading symbol. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - style (int, optional): mvLoadInd_DottedCircle is rotating dots style, mvLoadInd_Ring is rotating bar style. - circle_count (int, optional): DottedCircle style: number of dots to show. - speed (float, optional): Speed with which the animation will rotate. - radius (float, optional): Scale factor for the loading indicator radius. The size of the indicator is determined by font size and this scale factor. - thickness (float, optional): Ring style: scale factor of line thickness; thickness=1 corresponds to line width being 1/8 of the ring diameter. - color (Union[List[int], Tuple[int, ...]], optional): Main color of the indicator. If omitted, the color for mvThemeCol_Button will be used. - secondary_color (Union[List[int], Tuple[int, ...]], optional): DottedCircle style: color of 'inactive' dots. If omitted, the color for mvThemeCol_ButtonHovered will be used. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_loading_indicator(**kwargs) - -def add_menu(**kwargs): - """ Adds a menu to an existing menu bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_menu(**kwargs) - -def add_menu_bar(**kwargs): - """ Adds a menu bar to a window. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_menu_bar(**kwargs) - -def add_menu_item(**kwargs): - """ Adds a menu item to an existing menu. Menu items act similar to selectables and has a bool value. When placed in a menu the checkmark will reflect its value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): This value also controls the checkmark when shown. - shortcut (str, optional): Displays text on the menu item. Typically used to show a shortcut key command. - check (bool, optional): Displays a checkmark on the menu item when it is selected and placed in a menu. - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_menu_item(**kwargs) - -def add_mouse_click_handler(button=-1, **kwargs): - """ Adds a mouse click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_click_handler(button, **kwargs) - -def add_mouse_double_click_handler(button=-1, **kwargs): - """ Adds a mouse double click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_double_click_handler(button, **kwargs) - -def add_mouse_down_handler(button=-1, **kwargs): - """ Adds a mouse down handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_down_handler(button, **kwargs) - -def add_mouse_drag_handler(button=-1, threshold=10.0, **kwargs): - """ Adds a mouse drag handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - threshold (float, optional): The threshold the mouse must be dragged before the callback is ran - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_drag_handler(button, threshold, **kwargs) - -def add_mouse_move_handler(**kwargs): - """ Adds a mouse move handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_move_handler(**kwargs) - -def add_mouse_release_handler(button=-1, **kwargs): - """ Adds a mouse release handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_release_handler(button, **kwargs) - -def add_mouse_wheel_handler(**kwargs): - """ Adds a mouse wheel handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_mouse_wheel_handler(**kwargs) - -def add_node(**kwargs): - """ Adds a node to a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - draggable (bool, optional): Allow node to be draggable. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_node(**kwargs) - -def add_node_attribute(**kwargs): - """ Adds a node attribute to a node. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - attribute_type (int, optional): mvNode_Attr_Input, mvNode_Attr_Output, or mvNode_Attr_Static. - shape (int, optional): Pin shape. - category (str, optional): Category - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_node_attribute(**kwargs) - -def add_node_editor(**kwargs): - """ Adds a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - delink_callback (Callable, optional): Callback ran when a link is detached. - menubar (bool, optional): Shows or hides the menubar. - minimap (bool, optional): Shows or hides the Minimap. New in 1.6. - minimap_location (int, optional): mvNodeMiniMap_Location_* constants. New in 1.6. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_node_editor(**kwargs) - -def add_node_link(attr_1, attr_2, **kwargs): - """ Adds a node link between 2 node attributes. - - Args: - attr_1 (Union[int, str]): - attr_2 (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_node_link(attr_1, attr_2, **kwargs) - -def add_pie_series(x, y, radius, values, labels, **kwargs): - """ Adds an pie series to a plot. - - Args: - x (float): - y (float): - radius (float): - values (Any): - labels (Union[List[str], Tuple[str, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - format (str, optional): - angle (float, optional): - normalize (bool, optional): force normalization of pie chart values (i.e. always make a full circle if sum < 0) - ignore_hidden (bool, optional): ignore hidden slices when drawing the pie chart (as if they were not there) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_pie_series(x, y, radius, values, labels, **kwargs) - -def add_plot(**kwargs): - """ Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_title (bool, optional): the plot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_box_select (bool, optional): the user will not be able to box-select with right-click drag - no_mouse_pos (bool, optional): the text of mouse position, in plot coordinates, will not be displayed inside of the plot - query (bool, optional): the user will be able to draw query rects with CTRL + right-click drag - query_color (Union[List[float], Tuple[float, ...]], optional): Color of the query rectangles. - min_query_rects (int, optional): The minimum number of query rects that can be in the plot. If there are less rects than this value, it won't be possible to delete them. - max_query_rects (int, optional): The maximum number of query rects that can be in the plot. If the number is reached any rect added will replace the latest one. (0 means unlimited) - crosshairs (bool, optional): the default mouse cursor will be replaced with a crosshair when hovered - equal_aspects (bool, optional): primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes) - no_inputs (bool, optional): the user will not be able to interact with the plot - no_frame (bool, optional): the ImGui frame will not be rendered - use_local_time (bool, optional): axis labels will be formatted for your timezone when - use_ISO8601 (bool, optional): dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.) - use_24hour_clock (bool, optional): times will be formatted using a 24 hour clock - pan_button (int, optional): mouse button that enables panning when held - pan_mod (int, optional): optional modifier that must be held for panning - context_menu_button (int, optional): opens context menus (if enabled) when clicked - fit_button (int, optional): fits visible data when double clicked - box_select_button (int, optional): begins box selection when pressed and confirms selection when released - box_select_mod (int, optional): begins box selection when pressed and confirms selection when released - box_select_cancel_button (int, optional): cancels active box selection when pressed - query_toggle_mod (int, optional): when held, active box selections turn into queries - horizontal_mod (int, optional): expands active box selection/query horizontally to plot edge when held - vertical_mod (int, optional): expands active box selection/query vertically to plot edge when held - override_mod (int, optional): when held, all input is ignored; used to enable axis/plots as DND sources - zoom_mod (int, optional): optional modifier that must be held for scroll wheel zooming - zoom_rate (int, optional): zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - no_highlight (bool, optional): (deprecated)Removed because not supported from the backend anymore. To control the highlighting of series use the same argument in `add_plot_legend` - no_child (bool, optional): (deprecated)a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications) - anti_aliased (bool, optional): (deprecated)This feature was deprecated in ImPlot. To enable/disable anti_aliasing use `dpg.configure_app()` with the `anti_aliasing` parameters. - query_button (int, optional): (deprecated)This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - query_mod (int, optional): (deprecated)This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - Returns: - Union[int, str] - """ - - return internal_dpg.add_plot(**kwargs) - -def add_plot_annotation(**kwargs): - """ Adds an annotation to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): - offset (Union[List[float], Tuple[float, ...]], optional): - color (Union[List[int], Tuple[int, ...]], optional): - clamped (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_plot_annotation(**kwargs) - -def add_plot_axis(axis, **kwargs): - """ Adds an axis to a plot. - - Args: - axis (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - no_label (bool, optional): the axis label will not be displayed - no_gridlines (bool, optional): no grid lines will be displayed - no_tick_marks (bool, optional): no tick marks will be displayed - no_tick_labels (bool, optional): no text labels will be displayed - no_initial_fit (bool, optional): axis will not be initially fit to data extents on the first rendered frame - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_side_switch (bool, optional): the user will not be able to switch the axis side by dragging it - no_highlight (bool, optional): the axis will not have its background highlighted when hovered or held - opposite (bool, optional): axis ticks and labels will be rendered on the conventionally opposite side (i.e, right or top) - foreground_grid (bool, optional): grid lines will be displayed in the foreground (i.e. on top of data) instead of the background - tick_format (str, optional): Sets a custom tick label formatter - scale (int, optional): Sets the axis' scale. Can have only mvPlotScale_ values - invert (bool, optional): the axis values will be inverted (i.e. growing from right to left) - auto_fit (bool, optional): axis will be auto-fitting to data extents - range_fit (bool, optional): axis will only fit points if the point is in the visible range of the **orthogonal** axis - pan_stretch (bool, optional): panning in a locked or constrained state will cause the axis to stretch if possible - lock_min (bool, optional): the axis minimum value will be locked when panning/zooming - lock_max (bool, optional): the axis maximum value will be locked when panning/zooming - id (Union[int, str], optional): (deprecated) - log_scale (bool, optional): (deprecated)Old way to set log scale in the axis. Use 'scale' argument instead. - time (bool, optional): (deprecated)Old way to set time scale in the axis. Use 'scale' argument instead. - Returns: - Union[int, str] - """ - - return internal_dpg.add_plot_axis(axis, **kwargs) - -def add_plot_legend(**kwargs): - """ Adds a plot legend to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - location (int, optional): location, mvPlot_Location_* - horizontal (bool, optional): legend entries will be displayed horizontally - sort (bool, optional): legend entries will be displayed in alphabetical order - outside (bool, optional): legend will be rendered outside of the plot area - no_highlight_item (bool, optional): plot items will not be highlighted when their legend entry is hovered - no_highlight_axis (bool, optional): axes will not be highlighted when legend entries are hovered (only relevant if x/y-axis count > 1) - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_buttons (bool, optional): legend icons will not function as hide/show buttons - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_plot_legend(**kwargs) - -def add_progress_bar(**kwargs): - """ Adds a progress bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - overlay (str, optional): Overlayed text onto the bar that typically used to display the value of the progress. - default_value (float, optional): Normalized value to fill the bar from 0.0 to 1.0. Put a negative value to show an indeterminate progress bar. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_progress_bar(**kwargs) - -def add_radio_button(items=(), **kwargs): - """ Adds a set of radio buttons. If items keyword is empty, nothing will be shown. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown as radio options. Can consist of any combination of types. All types will be shown as strings. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): Default selected radio option. Set by using the string value of the item. - horizontal (bool, optional): Displays the radio options horizontally. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_radio_button(items, **kwargs) - -def add_raw_texture(width, height, default_value, **kwargs): - """ Adds a raw texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - format (int, optional): Data format. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_raw_texture(width, height, default_value, **kwargs) - -def add_scatter_series(x, y, **kwargs): - """ Adds a scatter series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - no_clip (bool, optional): markers on the edge of a plot will not be clipped - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_scatter_series(x, y, **kwargs) - -def add_selectable(**kwargs): - """ Adds a selectable. Similar to a button but can indicate its selected state. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): - span_columns (bool, optional): Forces the selectable to span the width of all columns if placed in a table. - disable_popup_close (bool, optional): Disable closing a modal or popup window. - select_on_nav (bool, optional): Auto-select when moved into with keyboard navigation, unless Ctrl is held. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_selectable(**kwargs) - -def add_separator(**kwargs): - """ Adds a horizontal line separator. Use 'label' parameter to add text and mvStyleVar_SeparatorText* elements to style it. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_separator(**kwargs) - -def add_series_value(**kwargs): - """ Adds a plot series value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Any, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_series_value(**kwargs) - -def add_shade_series(x, y1, **kwargs): - """ Adds a shade series to a plot. - - Args: - x (Any): - y1 (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - y2 (Any, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_shade_series(x, y1, **kwargs) - -def add_simple_plot(**kwargs): - """ Adds a simple plot for visualization of a 1 dimensional set of values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - overlay (str, optional): overlays text (similar to a plot title) - histogram (bool, optional): - autosize (bool, optional): - min_scale (float, optional): - max_scale (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_simple_plot(**kwargs) - -def add_slider_double(**kwargs): - """ Adds slider for a single double value. Useful when slider float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_double(**kwargs) - -def add_slider_doublex(**kwargs): - """ Adds multi slider for up to 4 double values. Usueful for when multi slide float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - size (int, optional): Number of doubles to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_doublex(**kwargs) - -def add_slider_float(**kwargs): - """ Adds slider for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_float(**kwargs) - -def add_slider_floatx(**kwargs): - """ Adds multi slider for up to 4 float values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - size (int, optional): Number of floats to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_floatx(**kwargs) - -def add_slider_int(**kwargs): - """ Adds slider for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (int, optional): Applies a limit only to sliding entry only. - max_value (int, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_int(**kwargs) - -def add_slider_intx(**kwargs): - """ Adds multi slider for up to 4 int values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - size (int, optional): Number of ints to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (int, optional): Applies a limit only to sliding entry only. - max_value (int, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_slider_intx(**kwargs) - -def add_spacer(**kwargs): - """ Adds a spacer item that can be used to help with layouts or can be used as a placeholder item. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_spacer(**kwargs) - -def add_stage(**kwargs): - """ Adds a stage. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_stage(**kwargs) - -def add_stair_series(x, y, **kwargs): - """ Adds a stair series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - pre_step (bool, optional): the y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i] - shaded (bool, optional): a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_stair_series(x, y, **kwargs) - -def add_static_texture(width, height, default_value, **kwargs): - """ Adds a static texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_static_texture(width, height, default_value, **kwargs) - -def add_stem_series(x, y, **kwargs): - """ Adds a stem series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - horizontal (bool, optional): stems will be rendered horizontally on the current y-axis - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_stem_series(x, y, **kwargs) - -def add_string_value(**kwargs): - """ Adds a string value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (str, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_string_value(**kwargs) - -def add_subplots(rows, columns, **kwargs): - """ Adds a collection of plots. - - Args: - rows (int): - columns (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - row_ratios (Union[List[float], Tuple[float, ...]], optional): - column_ratios (Union[List[float], Tuple[float, ...]], optional): - no_title (bool, optional): the subplot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_resize (bool, optional): resize splitters between subplot cells will be not be provided - no_align (bool, optional): subplot edges will not be aligned vertically or horizontally - share_series (bool, optional): when set to True, series from all sub-plots will be shared to some extent, using a single common color set and showing them in a single legend in the subplots item. Otherwise each plot will be independent from others and will have its own legend - link_rows (bool, optional): link the y-axis limits of all plots in each row (does not apply auxiliary y-axes) - link_columns (bool, optional): link the x-axis limits of all plots in each column - link_all_x (bool, optional): link the x-axis limits in every plot in the subplot - link_all_y (bool, optional): link the y-axis limits in every plot in the subplot (does not apply to auxiliary y-axes) - column_major (bool, optional): subplots are added in column major order instead of the default row major order - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_subplots(rows, columns, **kwargs) - -def add_synced_tables(**kwargs): - """ Links all tables that are immediate children of this container so that they share their state (mostly column sizes). Other children are rendered as is. This is an experimental feature, use with caution. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_synced_tables(**kwargs) - -def add_tab(**kwargs): - """ Adds a tab to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Creates a button on the tab that can hide the tab. - no_tooltip (bool, optional): Disable tooltip for the given tab. - order_mode (int, optional): set using a constant: mvTabOrder_Reorderable: allows reordering, mvTabOrder_Fixed: fixed ordering, mvTabOrder_Leading: adds tab to front, mvTabOrder_Trailing: adds tab to back - unsaved_document (bool, optional): Display a dot next to the title. - no_close_with_middle_click (bool, optional): Disable closing this tab (if closable==True) by clicking with middle mouse button. - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_tab(**kwargs) - -def add_tab_bar(**kwargs): - """ Adds a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - reorderable (bool, optional): Allows for the user to change the order of the tabs. - tab_list_popup_button (bool, optional): Show a button to select active tab from a dropdown list. - no_close_with_middle_click (bool, optional): Disable closing tabs (that have closable=True) by clicking with middle mouse button. - no_scrolling_buttons (bool, optional): Disable left/right scrolling buttons when tab buttons don't fit the container width. - no_tooltip (bool, optional): Disable tooltips when hovering a tab with a long name. - draw_selected_overline (bool, optional): Draw selected overline markers over selected tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_tab_bar(**kwargs) - -def add_tab_button(**kwargs): - """ Adds a tab button to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. Fixes the position of this tab in relation to the order of neighboring tabs at start. - leading (bool, optional): Enforce the tab position to the left of the tab bar (after the tab list popup button). - trailing (bool, optional): Enforce the tab position to the right of the tab bar (before the scrolling buttons). - no_tooltip (bool, optional): Disable tooltip for the given tab. - unsaved_document (bool, optional): Display a dot next to the title. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_tab_button(**kwargs) - -def add_table(**kwargs): - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - header_row (bool, optional): show headers at the top of the columns - clipper (bool, optional): Use clipper (rows must be same height). - inner_width (int, optional): - policy (int, optional): - freeze_rows (int, optional): - freeze_columns (int, optional): - sort_multi (bool, optional): Hold shift when clicking headers to sort on multiple column. - sort_tristate (bool, optional): Allow no sorting, disable default sorting. - resizable (bool, optional): Enable resizing columns - reorderable (bool, optional): Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - hideable (bool, optional): Enable hiding/disabling columns in context menu. - sortable (bool, optional): Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - context_menu_in_body (bool, optional): Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - row_background (bool, optional): Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - borders_innerH (bool, optional): Draw horizontal borders between rows. - borders_outerH (bool, optional): Draw horizontal borders at the top and bottom. - borders_innerV (bool, optional): Draw vertical borders between columns. - borders_outerV (bool, optional): Draw vertical borders on the left and right sides. - no_host_extendX (bool, optional): Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - no_host_extendY (bool, optional): Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - no_keep_columns_visible (bool, optional): Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - precise_widths (bool, optional): Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - no_clip (bool, optional): Disable clipping rectangle for every individual columns. - pad_outerX (bool, optional): Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. - no_pad_outerX (bool, optional): Default if BordersOuterV is off. Disable outer-most padding. - no_pad_innerX (bool, optional): Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - scrollX (bool, optional): Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - scrollY (bool, optional): Enable vertical scrolling. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_table(**kwargs) - -def add_table_cell(**kwargs): - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_table_cell(**kwargs) - -def add_table_column(**kwargs): - """ Adds a table column. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - init_width_or_weight (float, optional): - default_hide (bool, optional): Default as a hidden/disabled column. - default_sort (bool, optional): Default as a sorting column. - width_stretch (bool, optional): Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). - width_fixed (bool, optional): Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). - no_resize (bool, optional): Disable manual resizing. - no_reorder (bool, optional): Disable manual reordering this column, this will also prevent other columns from crossing over this column. - no_hide (bool, optional): Disable ability to hide/disable this column. - no_clip (bool, optional): Disable clipping for this column (all NoClip columns will render in a same draw command). - no_sort (bool, optional): Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). - no_sort_ascending (bool, optional): Disable ability to sort in the ascending direction. - no_sort_descending (bool, optional): Disable ability to sort in the descending direction. - no_header_width (bool, optional): Disable header text width contribution to automatic column width. - prefer_sort_ascending (bool, optional): Make the initial sort direction Ascending when first sorting on this column (default). - prefer_sort_descending (bool, optional): Make the initial sort direction Descending when first sorting on this column. - indent_enable (bool, optional): Use current Indent value when entering cell (default for column 0). - indent_disable (bool, optional): Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. - angled_header (bool, optional): Set this parameter to True to display the header text for this column in an angled (diagonal) orientation. This will add an additional row to accommodate the angled text. - no_header_label (bool, optional): Disable horizontal label for this column. Name will still appear in context menu or in angled headers. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_table_column(**kwargs) - -def add_table_row(**kwargs): - """ Adds a table row. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_table_row(**kwargs) - -def add_template_registry(**kwargs): - """ Adds a template registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_template_registry(**kwargs) - -def add_text(default_value='', **kwargs): - """ Adds text. Text can have an optional label that will display to the right of the text. - - Args: - default_value (str, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - wrap (int, optional): Number of pixels from the start of the item until wrapping starts. - bullet (bool, optional): Places a bullet to the left of the text. - color (Union[List[int], Tuple[int, ...]], optional): Color of the text (rgba). - show_label (bool, optional): Displays the label to the right of the text. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_text(default_value, **kwargs) - -def add_text_point(x, y, **kwargs): - """ Adds a label series to a plot. x and y can only have one elements each. - - Args: - x (float): - y (float): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - offset (Union[List[float], Tuple[float, ...]], optional): Offset of the label, in pixels, relative to the coordinates. - vertical (bool, optional): - id (Union[int, str], optional): (deprecated) - x_offset (int, optional): (deprecated)Old way to set x offset of the label. Use `offset` argument instead. - y_offset (int, optional): (deprecated)Old way to set y offset of the label. Use `offset` argument instead. - Returns: - Union[int, str] - """ - - return internal_dpg.add_text_point(x, y, **kwargs) - -def add_texture_registry(**kwargs): - """ Adds a dynamic texture. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_texture_registry(**kwargs) - -def add_theme(**kwargs): - """ Adds a theme. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - default_theme (bool, optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_theme(**kwargs) - -def add_theme_color(target=0, value=(0, 0, 0, 255), **kwargs): - """ Adds a theme color. - - Args: - target (int, optional): - value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - category (int, optional): Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_theme_color(target, value, **kwargs) - -def add_theme_component(item_type=0, **kwargs): - """ Adds a theme component. - - Args: - item_type (int, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - enabled_state (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_theme_component(item_type, **kwargs) - -def add_theme_style(target=0, x=1.0, y=-1.0, **kwargs): - """ Adds a theme style. - - Args: - target (int, optional): - x (float, optional): - y (float, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - category (int, optional): Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_theme_style(target, x, y, **kwargs) - -def add_time_picker(**kwargs): - """ Adds a time picker. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (dict, optional): - hour24 (bool, optional): Show 24 hour clock instead of 12 hour. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_time_picker(**kwargs) - -def add_tooltip(parent, **kwargs): - """ Adds a tooltip window. - - Args: - parent (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - delay (float, optional): Activation delay: time, in seconds, during which the mouse should stay still in order to display the tooltip. May be zero for instant activation. - hide_on_activity (bool, optional): Hide the tooltip if the user has moved the mouse. If False, the tooltip will follow mouse pointer. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_tooltip(parent, **kwargs) - -def add_tree_node(**kwargs): - """ Adds a tree node to add items to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_open (bool, optional): Sets the tree node open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - selectable (bool, optional): Makes the tree selectable. - span_text_width (bool, optional): Makes hitbox and highlight only cover the label. - span_full_width (bool, optional): Extend hit box to the left-most and right-most edges (cover the indent area). - catch_nav_left (bool, optional): Keyboard navigation: left arrow within this node's children, if unhandled, moves focus to this node. When setting it to True on a node, better set it on all children nodes in the subtree as well, otherwise it might give unexpected navigation jumps. - lines (int, optional): Experimental. Draw lines connecting tree_node hierarchy. One of dpg.mvTreeLines constants. To work correctly, must be configured the same way in every tree node. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_tree_node(**kwargs) - -def add_value_registry(**kwargs): - """ Adds a value registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_value_registry(**kwargs) - -def add_viewport_drawlist(**kwargs): - """ A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - front (bool, optional): Draws to the front of the view port instead of the back. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_viewport_drawlist(**kwargs) - -def add_viewport_menu_bar(**kwargs): - """ Adds a menubar to the viewport. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_viewport_menu_bar(**kwargs) - -def add_window(**kwargs): - """ Creates a new window for following items to be added to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - menubar (bool, optional): Shows or hides the menubar. - collapsed (bool, optional): Collapse the window. - autosize (bool, optional): Autosized the window to fit it's items. - no_resize (bool, optional): Allows for the window size to be changed or fixed. - unsaved_document (bool, optional): Show a special marker if the document is not saved. - no_title_bar (bool, optional): Title name for the title bar of the window. - no_move (bool, optional): Allows for the window's position to be changed or fixed. - no_scrollbar (bool, optional): Disable scrollbars. (window can still scroll with mouse or programmatically) - no_collapse (bool, optional): Disable user collapsing window by double-clicking on it. - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear. (off by default) - no_focus_on_appearing (bool, optional): Disable taking focus when transitioning from hidden to visible state. - no_bring_to_front_on_focus (bool, optional): Disable bringing window to front when taking focus. (e.g. clicking on it or programmatically giving it focus) - no_close (bool, optional): Disable user closing the window by removing the close button. - no_background (bool, optional): Sets Background and border alpha to transparent. - modal (bool, optional): Fills area behind window according to the theme and disables user ability to interact with anything except the window. - popup (bool, optional): Fills area behind window according to the theme, removes title bar, collapse and close. Window can be closed by selecting area in the background behind the window. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - no_open_over_existing_popup (bool, optional): Don't open if there's already a popup - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - no_docking (bool, optional): Disable docking of this window - copy_contents_shortcut (bool, optional): Experimental. If True, window contents can be copied to clipboard by pressing Ctrl+C. Might be useful for message boxes. - on_close (Callable, optional): Callback ran when window is closed. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated)This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - return internal_dpg.add_window(**kwargs) - -def apply_transform(item, transform): - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - item (Union[int, str]): Drawing node to apply transform to. - transform (Any): Transformation matrix. - Returns: - None - """ - - return internal_dpg.apply_transform(item, transform) - -def bind_colormap(item, source): - """ Sets the color map for widgets that accept it. - - Args: - item (Union[int, str]): item that the color map will be applied to - source (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - Returns: - None - """ - - return internal_dpg.bind_colormap(item, source) - -def bind_font(font): - """ Binds a global font. - - Args: - font (Union[int, str]): - Returns: - Union[int, str] - """ - - return internal_dpg.bind_font(font) - -def bind_item_font(item, font): - """ Sets an item's font. - - Args: - item (Union[int, str]): - font (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_font(item, font) - -def bind_item_handler_registry(item, handler_registry): - """ Binds an item handler registry to an item. - - Args: - item (Union[int, str]): - handler_registry (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_handler_registry(item, handler_registry) - -def bind_item_theme(item, theme): - """ Binds a theme to an item. - - Args: - item (Union[int, str]): - theme (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_theme(item, theme) - -def bind_theme(theme): - """ Binds a global theme. - - Args: - theme (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_theme(theme) - -def capture_next_item(callback, **kwargs): - """ Captures the next item. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - None - """ - - return internal_dpg.capture_next_item(callback, **kwargs) - -def clear_selected_links(node_editor): - """ Clears a node editor's selected links. - - Args: - node_editor (Union[int, str]): - Returns: - None - """ - - return internal_dpg.clear_selected_links(node_editor) - -def clear_selected_nodes(node_editor): - """ Clears a node editor's selected nodes. - - Args: - node_editor (Union[int, str]): - Returns: - None - """ - - return internal_dpg.clear_selected_nodes(node_editor) - -def create_context(): - """ Creates the Dear PyGui context. - - Args: - Returns: - None - """ - - return internal_dpg.create_context() - -def create_fps_matrix(eye, pitch, yaw): - """ New in 1.1. Create a 'first person shooter' matrix. - - Args: - eye (Union[List[float], Tuple[float, ...]]): eye position - pitch (float): pitch (in radians) - yaw (float): yaw (in radians) - Returns: - Any - """ - - return internal_dpg.create_fps_matrix(eye, pitch, yaw) - -def create_lookat_matrix(eye, target, up): - """ New in 1.1. Creates a 'Look at matrix'. - - Args: - eye (Union[List[float], Tuple[float, ...]]): eye position - target (Union[List[float], Tuple[float, ...]]): target position - up (Union[List[float], Tuple[float, ...]]): up vector - Returns: - Any - """ - - return internal_dpg.create_lookat_matrix(eye, target, up) - -def create_orthographic_matrix(left, right, bottom, top, zNear, zFar): - """ New in 1.1. Creates an orthographic matrix. - - Args: - left (float): left plane - right (float): right plane - bottom (float): bottom plane - top (float): top plane - zNear (float): Near clipping plane. - zFar (float): Far clipping plane. - Returns: - Any - """ - - return internal_dpg.create_orthographic_matrix(left, right, bottom, top, zNear, zFar) - -def create_perspective_matrix(fov, aspect, zNear, zFar): - """ New in 1.1. Creates a perspective matrix. - - Args: - fov (float): Field of view (in radians) - aspect (float): Aspect ratio (width/height) - zNear (float): Near clipping plane. - zFar (float): Far clipping plane. - Returns: - Any - """ - - return internal_dpg.create_perspective_matrix(fov, aspect, zNear, zFar) - -def create_rotation_matrix(angle, axis): - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - angle (float): angle to rotate - axis (Union[List[float], Tuple[float, ...]]): axis to rotate around - Returns: - Any - """ - - return internal_dpg.create_rotation_matrix(angle, axis) - -def create_scale_matrix(scales): - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - scales (Union[List[float], Tuple[float, ...]]): scale values per axis - Returns: - Any - """ - - return internal_dpg.create_scale_matrix(scales) - -def create_translation_matrix(translation): - """ New in 1.1. Creates a translation matrix. - - Args: - translation (Union[List[float], Tuple[float, ...]]): translation vector - Returns: - Any - """ - - return internal_dpg.create_translation_matrix(translation) - -def create_viewport(**kwargs): - """ Creates a viewport. Viewports are required. - - Args: - title (str, optional): Sets the title of the viewport. - small_icon (str, optional): Sets the small icon that is found in the viewport's decorator bar. Must be ***.ico on windows and either ***.ico or ***.png on mac. - large_icon (str, optional): Sets the large icon that is found in the task bar while the app is running. Must be ***.ico on windows and either ***.ico or ***.png on mac. - width (int, optional): Sets the width of the drawable space on the viewport. Does not inclue the border. - height (int, optional): Sets the height of the drawable space on the viewport. Does not inclue the border or decorator bar. - x_pos (int, optional): Sets x position the viewport will be drawn in screen coordinates. - y_pos (int, optional): Sets y position the viewport will be drawn in screen coordinates. - min_width (int, optional): Applies a minimuim limit to the width of the viewport. - max_width (int, optional): Applies a maximum limit to the width of the viewport. - min_height (int, optional): Applies a minimuim limit to the height of the viewport. - max_height (int, optional): Applies a maximum limit to the height of the viewport. - resizable (bool, optional): Enables and Disables user ability to resize the viewport. - vsync (bool, optional): Enables and Disables the renderloop vsync limit. vsync frame value is set by refresh rate of display. - always_on_top (bool, optional): Forces the viewport to always be drawn ontop of all other viewports. - decorated (bool, optional): Enabled and disabled the decorator bar at the top of the viewport. - clear_color (Union[List[float], Tuple[float, ...]], optional): Sets the color of the back of the viewport. - disable_close (bool, optional): Disables the viewport close button. can be used with set_exit_callback - Returns: - None - """ - - return internal_dpg.create_viewport(**kwargs) - -def delete_item(item, **kwargs): - """ Deletes an item.. - - Args: - item (Union[int, str]): - children_only (bool, optional): - slot (int, optional): - Returns: - None - """ - - return internal_dpg.delete_item(item, **kwargs) - -def destroy_context(): - """ Destroys the Dear PyGui context. - - Args: - Returns: - None - """ - - return internal_dpg.destroy_context() - -def does_alias_exist(alias): - """ Checks if an alias exist. - - Args: - alias (str): - Returns: - bool - """ - - return internal_dpg.does_alias_exist(alias) - -def does_item_exist(item): - """ Checks if an item exist.. - - Args: - item (Union[int, str]): - Returns: - bool - """ - - return internal_dpg.does_item_exist(item) - -def draw_arrow(p1, p2, **kwargs): - """ Adds an arrow. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): Arrow tip. - p2 (Union[List[float], Tuple[float, ...]]): Arrow tail. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - size (int, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_arrow(p1, p2, **kwargs) - -def draw_bezier_cubic(p1, p2, p3, p4, **kwargs): - """ Adds a cubic bezier curve. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): First point in curve. - p2 (Union[List[float], Tuple[float, ...]]): Second point in curve. - p3 (Union[List[float], Tuple[float, ...]]): Third point in curve. - p4 (Union[List[float], Tuple[float, ...]]): Fourth point in curve. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_bezier_cubic(p1, p2, p3, p4, **kwargs) - -def draw_bezier_quadratic(p1, p2, p3, **kwargs): - """ Adds a quadratic bezier curve. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): First point in curve. - p2 (Union[List[float], Tuple[float, ...]]): Second point in curve. - p3 (Union[List[float], Tuple[float, ...]]): Third point in curve. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_bezier_quadratic(p1, p2, p3, **kwargs) - -def draw_circle(center, radius, **kwargs): - """ Adds a circle - - Args: - center (Union[List[float], Tuple[float, ...]]): - radius (float): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate circle. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_circle(center, radius, **kwargs) - -def draw_ellipse(pmin, pmax, **kwargs): - """ Adds an ellipse. - - Args: - pmin (Union[List[float], Tuple[float, ...]]): Min point of bounding rectangle. - pmax (Union[List[float], Tuple[float, ...]]): Max point of bounding rectangle. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_ellipse(pmin, pmax, **kwargs) - -def draw_image(texture_tag, pmin, pmax, **kwargs): - """ Adds an image (for a drawing). - - Args: - texture_tag (Union[int, str]): - pmin (Union[List[float], Tuple[float, ...]]): Point of to start drawing texture. - pmax (Union[List[float], Tuple[float, ...]]): Point to complete drawing texture. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_image(texture_tag, pmin, pmax, **kwargs) - -def draw_image_quad(texture_tag, p1, p2, p3, p4, **kwargs): - """ Adds an image (for a drawing). - - Args: - texture_tag (Union[int, str]): - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - p4 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - uv1 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv2 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv3 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv4 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_image_quad(texture_tag, p1, p2, p3, p4, **kwargs) - -def draw_line(p1, p2, **kwargs): - """ Adds a line. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): Start of line. - p2 (Union[List[float], Tuple[float, ...]]): End of line. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_line(p1, p2, **kwargs) - -def draw_polygon(points, **kwargs): - """ Adds a polygon. - - Args: - points (List[List[float]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_polygon(points, **kwargs) - -def draw_polyline(points, **kwargs): - """ Adds a polyline. - - Args: - points (List[List[float]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - closed (bool, optional): Will close the polyline by returning to the first point. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_polyline(points, **kwargs) - -def draw_quad(p1, p2, p3, p4, **kwargs): - """ Adds a quad. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - p4 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_quad(p1, p2, p3, p4, **kwargs) - -def draw_rectangle(pmin, pmax, **kwargs): - """ Adds a rectangle. - - Args: - pmin (Union[List[float], Tuple[float, ...]]): Min point of bounding rectangle. - pmax (Union[List[float], Tuple[float, ...]]): Max point of bounding rectangle. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - multicolor (bool, optional): - rounding (float, optional): Number of pixels of the radius that will round the corners of the rectangle. Note: doesn't work with multicolor - thickness (float, optional): - corner_colors (Any, optional): Corner colors in a list, starting with upper-left and going clockwise: (upper-left, upper-right, bottom-right, bottom-left). 'multicolor' must be set to 'True'. - id (Union[int, str], optional): (deprecated) - color_upper_left (Union[List[int], Tuple[int, ...]], optional): (deprecated)Use corner_colors instead - color_upper_right (Union[List[int], Tuple[int, ...]], optional): (deprecated)Use corner_colors instead - color_bottom_right (Union[List[int], Tuple[int, ...]], optional): (deprecated)Use corner_colors instead - color_bottom_left (Union[List[int], Tuple[int, ...]], optional): (deprecated)Use corner_colors instead - Returns: - Union[int, str] - """ - - return internal_dpg.draw_rectangle(pmin, pmax, **kwargs) - -def draw_text(pos, text, **kwargs): - """ Adds text (drawlist). - - Args: - pos (Union[List[float], Tuple[float, ...]]): Top left point of bounding text rectangle. - text (str): Text to draw. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - size (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_text(pos, text, **kwargs) - -def draw_triangle(p1, p2, p3, **kwargs): - """ Adds a triangle. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.draw_triangle(p1, p2, p3, **kwargs) - -def empty_container_stack(): - """ Emptyes the container stack. - - Args: - Returns: - None - """ - - return internal_dpg.empty_container_stack() - -def fit_axis_data(axis): - """ Sets the axis boundaries max/min in the data series currently on the plot. - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.fit_axis_data(axis) - -def focus_item(item): - """ Focuses an item. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.focus_item(item) - -def generate_uuid(): - """ Generate a new UUID. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.generate_uuid() - -def get_active_window(): - """ Returns the active window. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.get_active_window() - -def get_alias_id(alias): - """ Returns the ID associated with an alias. - - Args: - alias (str): - Returns: - Union[int, str] - """ - - return internal_dpg.get_alias_id(alias) - -def get_aliases(): - """ Returns all aliases. - - Args: - Returns: - Union[List[str], Tuple[str, ...]] - """ - - return internal_dpg.get_aliases() - -def get_all_items(): - """ Returns all items. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_all_items() - -def get_app_configuration(): - """ Returns app configuration. - - Args: - Returns: - dict - """ - - return internal_dpg.get_app_configuration() - -def get_axis_limits(axis): - """ Get the specified axis limits. - - Args: - axis (Union[int, str]): - Returns: - Union[List[float], Tuple[float, ...]] - """ - - return internal_dpg.get_axis_limits(axis) - -def get_callback_queue(): - """ New in 1.2. Returns and clears callback queue. - - Args: - Returns: - Any - """ - - return internal_dpg.get_callback_queue() - -def get_clipboard_text(): - """ New in 1.3. Gets the clipboard text. - - Args: - Returns: - str - """ - - return internal_dpg.get_clipboard_text() - -def get_colormap_color(colormap, index): - """ Returns a color from a colormap given an index >= 0. (ex. 0 will be the first color in the color list of the color map) Modulo will be performed against the number of items in the color list. - - Args: - colormap (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - index (int): Desired position of the color in the colors list value of the colormap being quiered - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_colormap_color(colormap, index) - -def get_delta_time(): - """ Returns time since last frame. - - Args: - Returns: - float - """ - - return internal_dpg.get_delta_time() - -def get_drawing_mouse_pos(): - """ Returns mouse position in drawing. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_drawing_mouse_pos() - -def get_file_dialog_info(file_dialog): - """ Returns information related to the file dialog. Typically used while the file dialog is in use to query data about the state or info related to the file dialog. - - Args: - file_dialog (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_file_dialog_info(file_dialog) - -def get_focused_item(): - """ Returns the item currently having focus. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.get_focused_item() - -def get_frame_count(): - """ Returns frame count. - - Args: - Returns: - int - """ - - return internal_dpg.get_frame_count() - -def get_frame_rate(): - """ Returns the average frame rate across 120 frames. - - Args: - Returns: - float - """ - - return internal_dpg.get_frame_rate() - -def get_global_font_scale(): - """ Returns global font scale. - - Args: - Returns: - float - """ - - return internal_dpg.get_global_font_scale() - -def get_item_alias(item): - """ Returns an item's alias. - - Args: - item (Union[int, str]): - Returns: - str - """ - - return internal_dpg.get_item_alias(item) - -def get_item_configuration(item): - """ Returns an item's configuration. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_configuration(item) - -def get_item_info(item): - """ Returns an item's information. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_info(item) - -def get_item_state(item): - """ Returns an item's state. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_state(item) - -def get_item_types(): - """ Returns an item types. - - Args: - Returns: - dict - """ - - return internal_dpg.get_item_types() - -def get_mouse_drag_delta(): - """ Returns mouse drag delta. - - Args: - Returns: - float - """ - - return internal_dpg.get_mouse_drag_delta() - -def get_mouse_pos(**kwargs): - """ Returns mouse position. - - Args: - local (bool, optional): - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_mouse_pos(**kwargs) - -def get_platform(): - """ New in 1.6. Returns platform constant. - - Args: - Returns: - int - """ - - return internal_dpg.get_platform() - -def get_plot_mouse_pos(): - """ Returns mouse position in plot. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_plot_mouse_pos() - -def get_plot_query_rects(plot): - """ Returns the query rects of the plot. Returns an array of array containing the top-left coordinates and bottom-right coordinates of the plot area. - - Args: - plot (Union[int, str]): - Returns: - List[List[float]] - """ - - return internal_dpg.get_plot_query_rects(plot) - -def get_selected_links(node_editor): - """ Returns a node editor's selected links. - - Args: - node_editor (Union[int, str]): - Returns: - List[List[str]] - """ - - return internal_dpg.get_selected_links(node_editor) - -def get_selected_nodes(node_editor): - """ Returns a node editor's selected nodes. - - Args: - node_editor (Union[int, str]): - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_selected_nodes(node_editor) - -def get_text_size(text, **kwargs): - """ Returns width/height of text with specified font (must occur after 1st frame). - - Args: - text (str): - wrap_width (float, optional): Wrap width to use (-1.0 turns wrap off). - font (Union[int, str], optional): Font to use. - Returns: - Union[List[float], Tuple[float, ...]] - """ - - return internal_dpg.get_text_size(text, **kwargs) - -def get_total_time(): - """ Returns total time since Dear PyGui has started. - - Args: - Returns: - float - """ - - return internal_dpg.get_total_time() - -def get_value(item): - """ Returns an item's value. - - Args: - item (Union[int, str]): - Returns: - Any - """ - - return internal_dpg.get_value(item) - -def get_values(items): - """ Returns values of a list of items. - - Args: - items (Union[List[int], Tuple[int, ...]]): - Returns: - Any - """ - - return internal_dpg.get_values(items) - -def get_viewport_configuration(item): - """ Returns a viewport's configuration. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_viewport_configuration(item) - -def get_windows(): - """ Returns all windows. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_windows() - -def get_x_scroll(item): - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_x_scroll(item) - -def get_x_scroll_max(item): - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_x_scroll_max(item) - -def get_y_scroll(item): - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_y_scroll(item) - -def get_y_scroll_max(item): - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_y_scroll_max(item) - -def highlight_table_cell(table, row, column, color): - """ Highlight specified table cell. - - Args: - table (Union[int, str]): - row (int): - column (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_cell(table, row, column, color) - -def highlight_table_column(table, column, color): - """ Highlight specified table column. - - Args: - table (Union[int, str]): - column (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_column(table, column, color) - -def highlight_table_row(table, row, color): - """ Highlight specified table row. - - Args: - table (Union[int, str]): - row (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_row(table, row, color) - -def is_dearpygui_running(): - """ Checks if Dear PyGui is running - - Args: - Returns: - bool - """ - - return internal_dpg.is_dearpygui_running() - -def is_key_down(key): - """ Checks if key is down. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_down(key) - -def is_key_pressed(key): - """ Checks if key is pressed. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_pressed(key) - -def is_key_released(key): - """ Checks if key is released. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_released(key) - -def is_mouse_button_clicked(button): - """ Checks if mouse button is clicked. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_clicked(button) - -def is_mouse_button_double_clicked(button): - """ Checks if mouse button is double clicked. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_double_clicked(button) - -def is_mouse_button_down(button): - """ Checks if mouse button is down. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_down(button) - -def is_mouse_button_dragging(button, threshold): - """ Checks if mouse button is down and dragging. - - Args: - button (int): - threshold (float): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_dragging(button, threshold) - -def is_mouse_button_released(button): - """ Checks if mouse button is released. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_released(button) - -def is_table_cell_highlighted(table, row, column): - """ Checks if a table cell is highlighted. - - Args: - table (Union[int, str]): - row (int): - column (int): - Returns: - bool - """ - - return internal_dpg.is_table_cell_highlighted(table, row, column) - -def is_table_column_highlighted(table, column): - """ Checks if a table column is highlighted. - - Args: - table (Union[int, str]): - column (int): - Returns: - bool - """ - - return internal_dpg.is_table_column_highlighted(table, column) - -def is_table_row_highlighted(table, row): - """ Checks if a table row is highlighted. - - Args: - table (Union[int, str]): - row (int): - Returns: - bool - """ - - return internal_dpg.is_table_row_highlighted(table, row) - -def is_viewport_ok(): - """ Checks if a viewport has been created and shown. - - Args: - Returns: - bool - """ - - return internal_dpg.is_viewport_ok() - -def last_container(): - """ Returns the last container item added. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_container() - -def last_item(): - """ Returns the last item added. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_item() - -def last_root(): - """ Returns the last root added (registry or window). - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_root() - -def load_image(file, **kwargs): - """ Loads an image. Returns width, height, channels, mvBuffer - - Args: - file (str): - gamma (float, optional): Gamma correction factor. (default is 1.0 to avoid automatic gamma correction on loading. - gamma_scale_factor (float, optional): Gamma scale factor. - Returns: - Any - """ - - return internal_dpg.load_image(file, **kwargs) - -def lock_mutex(): - """ Locks render thread mutex. - - Args: - Returns: - None - """ - - return internal_dpg.lock_mutex() - -def maximize_viewport(): - """ Maximizes the viewport. - - Args: - Returns: - None - """ - - return internal_dpg.maximize_viewport() - -def minimize_viewport(): - """ Minimizes a viewport. - - Args: - Returns: - None - """ - - return internal_dpg.minimize_viewport() - -def move_item(item, **kwargs): - """ Moves an item to a new location. - - Args: - item (Union[int, str]): - parent (Union[int, str], optional): - before (Union[int, str], optional): - Returns: - None - """ - - return internal_dpg.move_item(item, **kwargs) - -def move_item_down(item): - """ Moves an item down. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.move_item_down(item) - -def move_item_up(item): - """ Moves an item up. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.move_item_up(item) - -def output_frame_buffer(file='', **kwargs): - """ Outputs frame buffer as a png if file is specified or through the second argument of a callback if specified. Render loop must have been started. - - Args: - file (str, optional): - callback (Callable, optional): Callback will return framebuffer as an array through the second arg. - Returns: - Any - """ - - return internal_dpg.output_frame_buffer(file, **kwargs) - -def pop_container_stack(): - """ Pops the top item off the parent stack and return its ID. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.pop_container_stack() - -def push_container_stack(item): - """ Pushes an item onto the container stack. - - Args: - item (Union[int, str]): - Returns: - bool - """ - - return internal_dpg.push_container_stack(item) - -def remove_alias(alias): - """ Removes an alias. - - Args: - alias (str): - Returns: - None - """ - - return internal_dpg.remove_alias(alias) - -def render_dearpygui_frame(): - """ Render a single Dear PyGui frame. - - Args: - Returns: - None - """ - - return internal_dpg.render_dearpygui_frame() - -def reorder_items(container, slot, new_order): - """ Reorders an item's children. - - Args: - container (Union[int, str]): - slot (int): - new_order (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.reorder_items(container, slot, new_order) - -def reset_axis_limits_constraints(axis): - """ Remove an axis' limits constraints - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_limits_constraints(axis) - -def reset_axis_ticks(axis): - """ Removes the manually set axis ticks and applies the default axis ticks - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_ticks(axis) - -def reset_axis_zoom_constraints(axis): - """ Remove an axis' zoom constraints - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_zoom_constraints(axis) - -def reset_pos(item): - """ Resets an item's position after using 'set_item_pos'. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_pos(item) - -def sample_colormap(colormap, t): - """ Returns a color from a colormap given t between 0.0-1.0. - - Args: - colormap (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - t (float): Value of the colormap to sample between 0.0-1.0 - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.sample_colormap(colormap, t) - -def save_image(file, width, height, data, **kwargs): - """ Saves an image. Possible formats: png, bmp, tga, hdr, jpg. - - Args: - file (str): - width (int): - height (int): - data (Any): - components (int, optional): Number of components (1-4). Default of 4. - quality (int, optional): Stride in bytes (only used for jpg). - Returns: - None - """ - - return internal_dpg.save_image(file, width, height, data, **kwargs) - -def save_init_file(file): - """ Save dpg.ini file. - - Args: - file (str): - Returns: - None - """ - - return internal_dpg.save_init_file(file) - -def set_axis_limits(axis, ymin, ymax): - """ Sets limits on the axis for pan and zoom. - - Args: - axis (Union[int, str]): - ymin (float): - ymax (float): - Returns: - None - """ - - return internal_dpg.set_axis_limits(axis, ymin, ymax) - -def set_axis_limits_auto(axis): - """ Removes all limits on specified axis. - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.set_axis_limits_auto(axis) - -def set_axis_limits_constraints(axis, vmin, vmax): - """ Sets an axis' limits constraints so that users can't pan beyond a min or max value - - Args: - axis (Union[int, str]): - vmin (float): - vmax (float): - Returns: - None - """ - - return internal_dpg.set_axis_limits_constraints(axis, vmin, vmax) - -def set_axis_ticks(axis, label_pairs): - """ Replaces axis ticks with 'label_pairs' argument. - - Args: - axis (Union[int, str]): - label_pairs (Any): Tuples of label and value in the form '((label, axis_value), (label, axis_value), ...)' - Returns: - None - """ - - return internal_dpg.set_axis_ticks(axis, label_pairs) - -def set_axis_zoom_constraints(axis, vmin, vmax): - """ Sets an axis' zoom constraints so that users can't zoom beyond a min or max value - - Args: - axis (Union[int, str]): - vmin (float): - vmax (float): - Returns: - None - """ - - return internal_dpg.set_axis_zoom_constraints(axis, vmin, vmax) - -def set_clip_space(item, top_left_x, top_left_y, width, height, min_depth, max_depth): - """ New in 1.1. Set the clip space for depth clipping and 'viewport' transformation. - - Args: - item (Union[int, str]): draw layer to set clip space - top_left_x (float): angle to rotate - top_left_y (float): angle to rotate - width (float): angle to rotate - height (float): angle to rotate - min_depth (float): angle to rotate - max_depth (float): angle to rotate - Returns: - None - """ - - return internal_dpg.set_clip_space(item, top_left_x, top_left_y, width, height, min_depth, max_depth) - -def set_clipboard_text(text): - """ New in 1.3. Sets the clipboard text. - - Args: - text (str): - Returns: - None - """ - - return internal_dpg.set_clipboard_text(text) - -def set_exit_callback(callback, **kwargs): - """ Sets a callback to run on last frame. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_exit_callback(callback, **kwargs) - -def set_frame_callback(frame, callback, **kwargs): - """ Sets a callback to run on first frame. - - Args: - frame (int): - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_frame_callback(frame, callback, **kwargs) - -def set_global_font_scale(scale): - """ Sets global font scale. - - Args: - scale (float): - Returns: - None - """ - - return internal_dpg.set_global_font_scale(scale) - -def set_item_alias(item, alias): - """ Sets an item's alias. - - Args: - item (Union[int, str]): - alias (str): - Returns: - None - """ - - return internal_dpg.set_item_alias(item, alias) - -def set_item_children(item, source, slot): - """ Sets an item's children. - - Args: - item (Union[int, str]): - source (Union[int, str]): - slot (int): - Returns: - None - """ - - return internal_dpg.set_item_children(item, source, slot) - -def set_primary_window(window, value=True): - """ Sets the primary window. - - Args: - window (Union[int, str]): - value (bool, optional): True to select this window as primary, False to make it a regular window (without any primary window). Only one window at a time can be primary. - Returns: - None - """ - - return internal_dpg.set_primary_window(window, value) - -def set_table_row_color(table, row, color): - """ Set table row color. - - Args: - table (Union[int, str]): - row (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.set_table_row_color(table, row, color) - -def set_value(item, value): - """ Set's an item's value. - - Args: - item (Union[int, str]): - value (Any): - Returns: - None - """ - - return internal_dpg.set_value(item, value) - -def set_viewport_resize_callback(callback, **kwargs): - """ Sets a callback to run on viewport resize. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_viewport_resize_callback(callback, **kwargs) - -def set_x_scroll(item, value, **kwargs): - """ Sets horizontal scroll position. - - Args: - item (Union[int, str]): - value (float): Scroll position - when (int, optional): Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used to set the position twice. - Returns: - None - """ - - return internal_dpg.set_x_scroll(item, value, **kwargs) - -def set_y_scroll(item, value, **kwargs): - """ Sets vertical scroll position. - - Args: - item (Union[int, str]): - value (float): Scroll position - when (int, optional): Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used to set the position twice. - Returns: - None - """ - - return internal_dpg.set_y_scroll(item, value, **kwargs) - -def setup_dearpygui(): - """ Sets up Dear PyGui - - Args: - viewport (Union[int, str], optional): (deprecated) - Returns: - None - """ - - return internal_dpg.setup_dearpygui() - -def show_imgui_demo(): - """ Shows the imgui demo. - - Args: - Returns: - None - """ - - return internal_dpg.show_imgui_demo() - -def show_implot_demo(): - """ Shows the implot demo. - - Args: - Returns: - None - """ - - return internal_dpg.show_implot_demo() - -def show_item_debug(item): - """ Shows an item's debug window - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.show_item_debug(item) - -def show_tool(tool): - """ Shows a built in tool. - - Args: - tool (Union[int, str]): - Returns: - str - """ - - return internal_dpg.show_tool(tool) - -def show_viewport(**kwargs): - """ Shows the main viewport. - - Args: - minimized (bool, optional): Sets the state of the viewport to minimized - maximized (bool, optional): Sets the state of the viewport to maximized - viewport (Union[int, str], optional): (deprecated) - Returns: - None - """ - - return internal_dpg.show_viewport(**kwargs) - -def split_frame(): - """ Waits one frame. - - Args: - delay (int, optional): (deprecated)Do not use it anymore, it has no effect. - Returns: - None - """ - - return internal_dpg.split_frame() - -def stop_dearpygui(): - """ Stops Dear PyGui - - Args: - Returns: - None - """ - - return internal_dpg.stop_dearpygui() - -def toggle_viewport_fullscreen(): - """ Toggle viewport fullscreen mode.. - - Args: - Returns: - None - """ - - return internal_dpg.toggle_viewport_fullscreen() - -def top_container_stack(): - """ Returns the item on the top of the container stack. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.top_container_stack() - -def unhighlight_table_cell(table, row, column): - """ Unhighlight specified table cell. - - Args: - table (Union[int, str]): - row (int): - column (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_cell(table, row, column) - -def unhighlight_table_column(table, column): - """ Unhighlight specified table column. - - Args: - table (Union[int, str]): - column (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_column(table, column) - -def unhighlight_table_row(table, row): - """ Unhighlight specified table row. - - Args: - table (Union[int, str]): - row (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_row(table, row) - -def unlock_mutex(): - """ Unlocks render thread mutex - - Args: - Returns: - None - """ - - return internal_dpg.unlock_mutex() - -def unset_table_row_color(table, row): - """ Remove user set table row color. - - Args: - table (Union[int, str]): - row (int): - Returns: - None - """ - - return internal_dpg.unset_table_row_color(table, row) - -def unstage(item): - """ Unstages an item. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.unstage(item) - - -########################################################## -# Constants # -########################################################## - -mvGraphicsBackend_D3D11=internal_dpg.mvGraphicsBackend_D3D11 -mvGraphicsBackend_D3D12=internal_dpg.mvGraphicsBackend_D3D12 -mvGraphicsBackend_VULKAN=internal_dpg.mvGraphicsBackend_VULKAN -mvGraphicsBackend_METAL=internal_dpg.mvGraphicsBackend_METAL -mvGraphicsBackend_OPENGL=internal_dpg.mvGraphicsBackend_OPENGL -mvMouseButton_Left=internal_dpg.mvMouseButton_Left -mvMouseButton_Right=internal_dpg.mvMouseButton_Right -mvMouseButton_Middle=internal_dpg.mvMouseButton_Middle -mvMouseButton_X1=internal_dpg.mvMouseButton_X1 -mvMouseButton_X2=internal_dpg.mvMouseButton_X2 -mvKey_ModDisabled=internal_dpg.mvKey_ModDisabled -mvKey_None=internal_dpg.mvKey_None -mvKey_0=internal_dpg.mvKey_0 -mvKey_1=internal_dpg.mvKey_1 -mvKey_2=internal_dpg.mvKey_2 -mvKey_3=internal_dpg.mvKey_3 -mvKey_4=internal_dpg.mvKey_4 -mvKey_5=internal_dpg.mvKey_5 -mvKey_6=internal_dpg.mvKey_6 -mvKey_7=internal_dpg.mvKey_7 -mvKey_8=internal_dpg.mvKey_8 -mvKey_9=internal_dpg.mvKey_9 -mvKey_A=internal_dpg.mvKey_A -mvKey_B=internal_dpg.mvKey_B -mvKey_C=internal_dpg.mvKey_C -mvKey_D=internal_dpg.mvKey_D -mvKey_E=internal_dpg.mvKey_E -mvKey_F=internal_dpg.mvKey_F -mvKey_G=internal_dpg.mvKey_G -mvKey_H=internal_dpg.mvKey_H -mvKey_I=internal_dpg.mvKey_I -mvKey_J=internal_dpg.mvKey_J -mvKey_K=internal_dpg.mvKey_K -mvKey_L=internal_dpg.mvKey_L -mvKey_M=internal_dpg.mvKey_M -mvKey_N=internal_dpg.mvKey_N -mvKey_O=internal_dpg.mvKey_O -mvKey_P=internal_dpg.mvKey_P -mvKey_Q=internal_dpg.mvKey_Q -mvKey_R=internal_dpg.mvKey_R -mvKey_S=internal_dpg.mvKey_S -mvKey_T=internal_dpg.mvKey_T -mvKey_U=internal_dpg.mvKey_U -mvKey_V=internal_dpg.mvKey_V -mvKey_W=internal_dpg.mvKey_W -mvKey_X=internal_dpg.mvKey_X -mvKey_Y=internal_dpg.mvKey_Y -mvKey_Z=internal_dpg.mvKey_Z -mvKey_Back=internal_dpg.mvKey_Back -mvKey_Tab=internal_dpg.mvKey_Tab -mvKey_Return=internal_dpg.mvKey_Return -mvKey_LShift=internal_dpg.mvKey_LShift -mvKey_RShift=internal_dpg.mvKey_RShift -mvKey_LControl=internal_dpg.mvKey_LControl -mvKey_RControl=internal_dpg.mvKey_RControl -mvKey_LAlt=internal_dpg.mvKey_LAlt -mvKey_RAlt=internal_dpg.mvKey_RAlt -mvKey_Pause=internal_dpg.mvKey_Pause -mvKey_CapsLock=internal_dpg.mvKey_CapsLock -mvKey_Escape=internal_dpg.mvKey_Escape -mvKey_Spacebar=internal_dpg.mvKey_Spacebar -mvKey_End=internal_dpg.mvKey_End -mvKey_Home=internal_dpg.mvKey_Home -mvKey_Left=internal_dpg.mvKey_Left -mvKey_Up=internal_dpg.mvKey_Up -mvKey_Right=internal_dpg.mvKey_Right -mvKey_Down=internal_dpg.mvKey_Down -mvKey_Print=internal_dpg.mvKey_Print -mvKey_Insert=internal_dpg.mvKey_Insert -mvKey_Delete=internal_dpg.mvKey_Delete -mvKey_NumPad0=internal_dpg.mvKey_NumPad0 -mvKey_NumPad1=internal_dpg.mvKey_NumPad1 -mvKey_NumPad2=internal_dpg.mvKey_NumPad2 -mvKey_NumPad3=internal_dpg.mvKey_NumPad3 -mvKey_NumPad4=internal_dpg.mvKey_NumPad4 -mvKey_NumPad5=internal_dpg.mvKey_NumPad5 -mvKey_NumPad6=internal_dpg.mvKey_NumPad6 -mvKey_NumPad7=internal_dpg.mvKey_NumPad7 -mvKey_NumPad8=internal_dpg.mvKey_NumPad8 -mvKey_NumPad9=internal_dpg.mvKey_NumPad9 -mvKey_NumPadEnter=internal_dpg.mvKey_NumPadEnter -mvKey_NumPadEqual=internal_dpg.mvKey_NumPadEqual -mvKey_Subtract=internal_dpg.mvKey_Subtract -mvKey_Decimal=internal_dpg.mvKey_Decimal -mvKey_Divide=internal_dpg.mvKey_Divide -mvKey_Multiply=internal_dpg.mvKey_Multiply -mvKey_Add=internal_dpg.mvKey_Add -mvKey_F1=internal_dpg.mvKey_F1 -mvKey_F2=internal_dpg.mvKey_F2 -mvKey_F3=internal_dpg.mvKey_F3 -mvKey_F4=internal_dpg.mvKey_F4 -mvKey_F5=internal_dpg.mvKey_F5 -mvKey_F6=internal_dpg.mvKey_F6 -mvKey_F7=internal_dpg.mvKey_F7 -mvKey_F8=internal_dpg.mvKey_F8 -mvKey_F9=internal_dpg.mvKey_F9 -mvKey_F10=internal_dpg.mvKey_F10 -mvKey_F11=internal_dpg.mvKey_F11 -mvKey_F12=internal_dpg.mvKey_F12 -mvKey_F13=internal_dpg.mvKey_F13 -mvKey_F14=internal_dpg.mvKey_F14 -mvKey_F15=internal_dpg.mvKey_F15 -mvKey_F16=internal_dpg.mvKey_F16 -mvKey_F17=internal_dpg.mvKey_F17 -mvKey_F18=internal_dpg.mvKey_F18 -mvKey_F19=internal_dpg.mvKey_F19 -mvKey_F20=internal_dpg.mvKey_F20 -mvKey_F21=internal_dpg.mvKey_F21 -mvKey_F22=internal_dpg.mvKey_F22 -mvKey_F23=internal_dpg.mvKey_F23 -mvKey_F24=internal_dpg.mvKey_F24 -mvKey_NumLock=internal_dpg.mvKey_NumLock -mvKey_ScrollLock=internal_dpg.mvKey_ScrollLock -mvKey_Period=internal_dpg.mvKey_Period -mvKey_Slash=internal_dpg.mvKey_Slash -mvKey_Backslash=internal_dpg.mvKey_Backslash -mvKey_Open_Brace=internal_dpg.mvKey_Open_Brace -mvKey_Close_Brace=internal_dpg.mvKey_Close_Brace -mvKey_Browser_Back=internal_dpg.mvKey_Browser_Back -mvKey_Browser_Forward=internal_dpg.mvKey_Browser_Forward -mvKey_Comma=internal_dpg.mvKey_Comma -mvKey_Minus=internal_dpg.mvKey_Minus -mvKey_Menu=internal_dpg.mvKey_Menu -mvKey_ModSuper=internal_dpg.mvKey_ModSuper -mvKey_ModShift=internal_dpg.mvKey_ModShift -mvKey_ModAlt=internal_dpg.mvKey_ModAlt -mvKey_ModCtrl=internal_dpg.mvKey_ModCtrl -mvKey_Clear=internal_dpg.mvKey_Clear -mvKey_Prior=internal_dpg.mvKey_Prior -mvKey_Next=internal_dpg.mvKey_Next -mvKey_Select=internal_dpg.mvKey_Select -mvKey_Execute=internal_dpg.mvKey_Execute -mvKey_LWin=internal_dpg.mvKey_LWin -mvKey_RWin=internal_dpg.mvKey_RWin -mvKey_Apps=internal_dpg.mvKey_Apps -mvKey_Sleep=internal_dpg.mvKey_Sleep -mvKey_Help=internal_dpg.mvKey_Help -mvKey_Browser_Refresh=internal_dpg.mvKey_Browser_Refresh -mvKey_Browser_Stop=internal_dpg.mvKey_Browser_Stop -mvKey_Browser_Search=internal_dpg.mvKey_Browser_Search -mvKey_Browser_Favorites=internal_dpg.mvKey_Browser_Favorites -mvKey_Browser_Home=internal_dpg.mvKey_Browser_Home -mvKey_Volume_Mute=internal_dpg.mvKey_Volume_Mute -mvKey_Volume_Down=internal_dpg.mvKey_Volume_Down -mvKey_Volume_Up=internal_dpg.mvKey_Volume_Up -mvKey_Media_Next_Track=internal_dpg.mvKey_Media_Next_Track -mvKey_Media_Prev_Track=internal_dpg.mvKey_Media_Prev_Track -mvKey_Media_Stop=internal_dpg.mvKey_Media_Stop -mvKey_Media_Play_Pause=internal_dpg.mvKey_Media_Play_Pause -mvKey_Launch_Mail=internal_dpg.mvKey_Launch_Mail -mvKey_Launch_Media_Select=internal_dpg.mvKey_Launch_Media_Select -mvKey_Launch_App1=internal_dpg.mvKey_Launch_App1 -mvKey_Launch_App2=internal_dpg.mvKey_Launch_App2 -mvKey_Colon=internal_dpg.mvKey_Colon -mvKey_Plus=internal_dpg.mvKey_Plus -mvKey_Tilde=internal_dpg.mvKey_Tilde -mvKey_Quote=internal_dpg.mvKey_Quote -mvKey_F25=internal_dpg.mvKey_F25 -mvAll=internal_dpg.mvAll -mvTool_About=internal_dpg.mvTool_About -mvTool_Debug=internal_dpg.mvTool_Debug -mvTool_Doc=internal_dpg.mvTool_Doc -mvTool_ItemRegistry=internal_dpg.mvTool_ItemRegistry -mvTool_Metrics=internal_dpg.mvTool_Metrics -mvTool_Stack=internal_dpg.mvTool_Stack -mvTool_Style=internal_dpg.mvTool_Style -mvTool_Font=internal_dpg.mvTool_Font -mvFontAtlas=internal_dpg.mvFontAtlas -mvAppUUID=internal_dpg.mvAppUUID -mvInvalidUUID=internal_dpg.mvInvalidUUID -mvDir_None=internal_dpg.mvDir_None -mvDir_Left=internal_dpg.mvDir_Left -mvDir_Right=internal_dpg.mvDir_Right -mvDir_Up=internal_dpg.mvDir_Up -mvDir_Down=internal_dpg.mvDir_Down -mvComboHeight_Small=internal_dpg.mvComboHeight_Small -mvComboHeight_Regular=internal_dpg.mvComboHeight_Regular -mvComboHeight_Large=internal_dpg.mvComboHeight_Large -mvComboHeight_Largest=internal_dpg.mvComboHeight_Largest -mvEventType_Off=internal_dpg.mvEventType_Off -mvEventType_Enter=internal_dpg.mvEventType_Enter -mvEventType_On=internal_dpg.mvEventType_On -mvEventType_Leave=internal_dpg.mvEventType_Leave -mvSetScrollFlags_Now=internal_dpg.mvSetScrollFlags_Now -mvSetScrollFlags_Delayed=internal_dpg.mvSetScrollFlags_Delayed -mvSetScrollFlags_Both=internal_dpg.mvSetScrollFlags_Both -mvScrollDirection_XAxis=internal_dpg.mvScrollDirection_XAxis -mvScrollDirection_YAxis=internal_dpg.mvScrollDirection_YAxis -mvScrollDirection_Horizontal=internal_dpg.mvScrollDirection_Horizontal -mvScrollDirection_Vertical=internal_dpg.mvScrollDirection_Vertical -mvLoadInd_DottedCircle=internal_dpg.mvLoadInd_DottedCircle -mvLoadInd_Ring=internal_dpg.mvLoadInd_Ring -mvPlatform_Windows=internal_dpg.mvPlatform_Windows -mvPlatform_Apple=internal_dpg.mvPlatform_Apple -mvPlatform_Linux=internal_dpg.mvPlatform_Linux -mvColorEdit_AlphaPreviewNone=internal_dpg.mvColorEdit_AlphaPreviewNone -mvColorEdit_AlphaPreview=internal_dpg.mvColorEdit_AlphaPreview -mvColorEdit_AlphaPreviewHalf=internal_dpg.mvColorEdit_AlphaPreviewHalf -mvColorEdit_uint8=internal_dpg.mvColorEdit_uint8 -mvColorEdit_float=internal_dpg.mvColorEdit_float -mvColorEdit_rgb=internal_dpg.mvColorEdit_rgb -mvColorEdit_hsv=internal_dpg.mvColorEdit_hsv -mvColorEdit_hex=internal_dpg.mvColorEdit_hex -mvColorEdit_input_rgb=internal_dpg.mvColorEdit_input_rgb -mvColorEdit_input_hsv=internal_dpg.mvColorEdit_input_hsv -mvPlotColormap_Default=internal_dpg.mvPlotColormap_Default -mvPlotColormap_Deep=internal_dpg.mvPlotColormap_Deep -mvPlotColormap_Dark=internal_dpg.mvPlotColormap_Dark -mvPlotColormap_Pastel=internal_dpg.mvPlotColormap_Pastel -mvPlotColormap_Paired=internal_dpg.mvPlotColormap_Paired -mvPlotColormap_Viridis=internal_dpg.mvPlotColormap_Viridis -mvPlotColormap_Plasma=internal_dpg.mvPlotColormap_Plasma -mvPlotColormap_Hot=internal_dpg.mvPlotColormap_Hot -mvPlotColormap_Cool=internal_dpg.mvPlotColormap_Cool -mvPlotColormap_Pink=internal_dpg.mvPlotColormap_Pink -mvPlotColormap_Jet=internal_dpg.mvPlotColormap_Jet -mvPlotColormap_Twilight=internal_dpg.mvPlotColormap_Twilight -mvPlotColormap_RdBu=internal_dpg.mvPlotColormap_RdBu -mvPlotColormap_BrBG=internal_dpg.mvPlotColormap_BrBG -mvPlotColormap_PiYG=internal_dpg.mvPlotColormap_PiYG -mvPlotColormap_Spectral=internal_dpg.mvPlotColormap_Spectral -mvPlotColormap_Greys=internal_dpg.mvPlotColormap_Greys -mvColorPicker_bar=internal_dpg.mvColorPicker_bar -mvColorPicker_wheel=internal_dpg.mvColorPicker_wheel -mvTabOrder_Reorderable=internal_dpg.mvTabOrder_Reorderable -mvTabOrder_Fixed=internal_dpg.mvTabOrder_Fixed -mvTabOrder_Leading=internal_dpg.mvTabOrder_Leading -mvTabOrder_Trailing=internal_dpg.mvTabOrder_Trailing -mvTimeUnit_Us=internal_dpg.mvTimeUnit_Us -mvTimeUnit_Ms=internal_dpg.mvTimeUnit_Ms -mvTimeUnit_S=internal_dpg.mvTimeUnit_S -mvTimeUnit_Min=internal_dpg.mvTimeUnit_Min -mvTimeUnit_Hr=internal_dpg.mvTimeUnit_Hr -mvTimeUnit_Day=internal_dpg.mvTimeUnit_Day -mvTimeUnit_Mo=internal_dpg.mvTimeUnit_Mo -mvTimeUnit_Yr=internal_dpg.mvTimeUnit_Yr -mvDatePickerLevel_Day=internal_dpg.mvDatePickerLevel_Day -mvDatePickerLevel_Month=internal_dpg.mvDatePickerLevel_Month -mvDatePickerLevel_Year=internal_dpg.mvDatePickerLevel_Year -mvCullMode_None=internal_dpg.mvCullMode_None -mvCullMode_Back=internal_dpg.mvCullMode_Back -mvCullMode_Front=internal_dpg.mvCullMode_Front -mvFontRangeHint_Default=internal_dpg.mvFontRangeHint_Default -mvFontRangeHint_Japanese=internal_dpg.mvFontRangeHint_Japanese -mvFontRangeHint_Korean=internal_dpg.mvFontRangeHint_Korean -mvFontRangeHint_Chinese_Full=internal_dpg.mvFontRangeHint_Chinese_Full -mvFontRangeHint_Chinese_Simplified_Common=internal_dpg.mvFontRangeHint_Chinese_Simplified_Common -mvFontRangeHint_Cyrillic=internal_dpg.mvFontRangeHint_Cyrillic -mvFontRangeHint_Thai=internal_dpg.mvFontRangeHint_Thai -mvFontRangeHint_Vietnamese=internal_dpg.mvFontRangeHint_Vietnamese -mvNode_PinShape_Circle=internal_dpg.mvNode_PinShape_Circle -mvNode_PinShape_CircleFilled=internal_dpg.mvNode_PinShape_CircleFilled -mvNode_PinShape_Triangle=internal_dpg.mvNode_PinShape_Triangle -mvNode_PinShape_TriangleFilled=internal_dpg.mvNode_PinShape_TriangleFilled -mvNode_PinShape_Quad=internal_dpg.mvNode_PinShape_Quad -mvNode_PinShape_QuadFilled=internal_dpg.mvNode_PinShape_QuadFilled -mvNode_Attr_Input=internal_dpg.mvNode_Attr_Input -mvNode_Attr_Output=internal_dpg.mvNode_Attr_Output -mvNode_Attr_Static=internal_dpg.mvNode_Attr_Static -mvPlotBin_Sqrt=internal_dpg.mvPlotBin_Sqrt -mvPlotBin_Sturges=internal_dpg.mvPlotBin_Sturges -mvPlotBin_Rice=internal_dpg.mvPlotBin_Rice -mvPlotBin_Scott=internal_dpg.mvPlotBin_Scott -mvXAxis=internal_dpg.mvXAxis -mvXAxis2=internal_dpg.mvXAxis2 -mvXAxis3=internal_dpg.mvXAxis3 -mvYAxis=internal_dpg.mvYAxis -mvYAxis2=internal_dpg.mvYAxis2 -mvYAxis3=internal_dpg.mvYAxis3 -mvPlotScale_Linear=internal_dpg.mvPlotScale_Linear -mvPlotScale_Time=internal_dpg.mvPlotScale_Time -mvPlotScale_Log10=internal_dpg.mvPlotScale_Log10 -mvPlotScale_SymLog=internal_dpg.mvPlotScale_SymLog -mvPlotMarker_None=internal_dpg.mvPlotMarker_None -mvPlotMarker_Circle=internal_dpg.mvPlotMarker_Circle -mvPlotMarker_Square=internal_dpg.mvPlotMarker_Square -mvPlotMarker_Diamond=internal_dpg.mvPlotMarker_Diamond -mvPlotMarker_Up=internal_dpg.mvPlotMarker_Up -mvPlotMarker_Down=internal_dpg.mvPlotMarker_Down -mvPlotMarker_Left=internal_dpg.mvPlotMarker_Left -mvPlotMarker_Right=internal_dpg.mvPlotMarker_Right -mvPlotMarker_Cross=internal_dpg.mvPlotMarker_Cross -mvPlotMarker_Plus=internal_dpg.mvPlotMarker_Plus -mvPlotMarker_Asterisk=internal_dpg.mvPlotMarker_Asterisk -mvPlot_Location_Center=internal_dpg.mvPlot_Location_Center -mvPlot_Location_North=internal_dpg.mvPlot_Location_North -mvPlot_Location_South=internal_dpg.mvPlot_Location_South -mvPlot_Location_West=internal_dpg.mvPlot_Location_West -mvPlot_Location_East=internal_dpg.mvPlot_Location_East -mvPlot_Location_NorthWest=internal_dpg.mvPlot_Location_NorthWest -mvPlot_Location_NorthEast=internal_dpg.mvPlot_Location_NorthEast -mvPlot_Location_SouthWest=internal_dpg.mvPlot_Location_SouthWest -mvPlot_Location_SouthEast=internal_dpg.mvPlot_Location_SouthEast -mvNodeMiniMap_Location_BottomLeft=internal_dpg.mvNodeMiniMap_Location_BottomLeft -mvNodeMiniMap_Location_BottomRight=internal_dpg.mvNodeMiniMap_Location_BottomRight -mvNodeMiniMap_Location_TopLeft=internal_dpg.mvNodeMiniMap_Location_TopLeft -mvNodeMiniMap_Location_TopRight=internal_dpg.mvNodeMiniMap_Location_TopRight -mvTable_SizingFixedFit=internal_dpg.mvTable_SizingFixedFit -mvTable_SizingFixedSame=internal_dpg.mvTable_SizingFixedSame -mvTable_SizingStretchProp=internal_dpg.mvTable_SizingStretchProp -mvTable_SizingStretchSame=internal_dpg.mvTable_SizingStretchSame -mvTreeLines_None=internal_dpg.mvTreeLines_None -mvTreeLines_Full=internal_dpg.mvTreeLines_Full -mvTreeLines_ToNodes=internal_dpg.mvTreeLines_ToNodes -mvFormat_Float_rgba=internal_dpg.mvFormat_Float_rgba -mvFormat_Float_rgb=internal_dpg.mvFormat_Float_rgb -mvThemeCat_Core=internal_dpg.mvThemeCat_Core -mvThemeCat_Plots=internal_dpg.mvThemeCat_Plots -mvThemeCat_Nodes=internal_dpg.mvThemeCat_Nodes -mvThemeCol_Text=internal_dpg.mvThemeCol_Text -mvThemeCol_TextDisabled=internal_dpg.mvThemeCol_TextDisabled -mvThemeCol_WindowBg=internal_dpg.mvThemeCol_WindowBg -mvThemeCol_ChildBg=internal_dpg.mvThemeCol_ChildBg -mvThemeCol_PopupBg=internal_dpg.mvThemeCol_PopupBg -mvThemeCol_Border=internal_dpg.mvThemeCol_Border -mvThemeCol_BorderShadow=internal_dpg.mvThemeCol_BorderShadow -mvThemeCol_FrameBg=internal_dpg.mvThemeCol_FrameBg -mvThemeCol_FrameBgHovered=internal_dpg.mvThemeCol_FrameBgHovered -mvThemeCol_FrameBgActive=internal_dpg.mvThemeCol_FrameBgActive -mvThemeCol_TitleBg=internal_dpg.mvThemeCol_TitleBg -mvThemeCol_TitleBgActive=internal_dpg.mvThemeCol_TitleBgActive -mvThemeCol_TitleBgCollapsed=internal_dpg.mvThemeCol_TitleBgCollapsed -mvThemeCol_MenuBarBg=internal_dpg.mvThemeCol_MenuBarBg -mvThemeCol_ScrollbarBg=internal_dpg.mvThemeCol_ScrollbarBg -mvThemeCol_ScrollbarGrab=internal_dpg.mvThemeCol_ScrollbarGrab -mvThemeCol_ScrollbarGrabHovered=internal_dpg.mvThemeCol_ScrollbarGrabHovered -mvThemeCol_ScrollbarGrabActive=internal_dpg.mvThemeCol_ScrollbarGrabActive -mvThemeCol_CheckMark=internal_dpg.mvThemeCol_CheckMark -mvThemeCol_SliderGrab=internal_dpg.mvThemeCol_SliderGrab -mvThemeCol_SliderGrabActive=internal_dpg.mvThemeCol_SliderGrabActive -mvThemeCol_Button=internal_dpg.mvThemeCol_Button -mvThemeCol_ButtonHovered=internal_dpg.mvThemeCol_ButtonHovered -mvThemeCol_ButtonActive=internal_dpg.mvThemeCol_ButtonActive -mvThemeCol_Header=internal_dpg.mvThemeCol_Header -mvThemeCol_HeaderHovered=internal_dpg.mvThemeCol_HeaderHovered -mvThemeCol_HeaderActive=internal_dpg.mvThemeCol_HeaderActive -mvThemeCol_Separator=internal_dpg.mvThemeCol_Separator -mvThemeCol_SeparatorHovered=internal_dpg.mvThemeCol_SeparatorHovered -mvThemeCol_SeparatorActive=internal_dpg.mvThemeCol_SeparatorActive -mvThemeCol_ResizeGrip=internal_dpg.mvThemeCol_ResizeGrip -mvThemeCol_ResizeGripHovered=internal_dpg.mvThemeCol_ResizeGripHovered -mvThemeCol_ResizeGripActive=internal_dpg.mvThemeCol_ResizeGripActive -mvThemeCol_InputTextCursor=internal_dpg.mvThemeCol_InputTextCursor -mvThemeCol_TabHovered=internal_dpg.mvThemeCol_TabHovered -mvThemeCol_Tab=internal_dpg.mvThemeCol_Tab -mvThemeCol_TabSelected=internal_dpg.mvThemeCol_TabSelected -mvThemeCol_TabSelectedOverline=internal_dpg.mvThemeCol_TabSelectedOverline -mvThemeCol_TabDimmed=internal_dpg.mvThemeCol_TabDimmed -mvThemeCol_TabDimmedSelected=internal_dpg.mvThemeCol_TabDimmedSelected -mvThemeCol_TabDimmedSelectedOverline=internal_dpg.mvThemeCol_TabDimmedSelectedOverline -mvThemeCol_DockingPreview=internal_dpg.mvThemeCol_DockingPreview -mvThemeCol_DockingEmptyBg=internal_dpg.mvThemeCol_DockingEmptyBg -mvThemeCol_PlotLines=internal_dpg.mvThemeCol_PlotLines -mvThemeCol_PlotLinesHovered=internal_dpg.mvThemeCol_PlotLinesHovered -mvThemeCol_PlotHistogram=internal_dpg.mvThemeCol_PlotHistogram -mvThemeCol_PlotHistogramHovered=internal_dpg.mvThemeCol_PlotHistogramHovered -mvThemeCol_TableHeaderBg=internal_dpg.mvThemeCol_TableHeaderBg -mvThemeCol_TableBorderStrong=internal_dpg.mvThemeCol_TableBorderStrong -mvThemeCol_TableBorderLight=internal_dpg.mvThemeCol_TableBorderLight -mvThemeCol_TableRowBg=internal_dpg.mvThemeCol_TableRowBg -mvThemeCol_TableRowBgAlt=internal_dpg.mvThemeCol_TableRowBgAlt -mvThemeCol_TextSelectedBg=internal_dpg.mvThemeCol_TextSelectedBg -mvThemeCol_TreeLines=internal_dpg.mvThemeCol_TreeLines -mvThemeCol_DragDropTarget=internal_dpg.mvThemeCol_DragDropTarget -mvThemeCol_DragDropTargetBg=internal_dpg.mvThemeCol_DragDropTargetBg -mvThemeCol_UnsavedMarker=internal_dpg.mvThemeCol_UnsavedMarker -mvThemeCol_NavCursor=internal_dpg.mvThemeCol_NavCursor -mvThemeCol_NavWindowingHighlight=internal_dpg.mvThemeCol_NavWindowingHighlight -mvThemeCol_NavWindowingDimBg=internal_dpg.mvThemeCol_NavWindowingDimBg -mvThemeCol_ModalWindowDimBg=internal_dpg.mvThemeCol_ModalWindowDimBg -mvThemeCol_TabActive=internal_dpg.mvThemeCol_TabActive -mvThemeCol_TabUnfocused=internal_dpg.mvThemeCol_TabUnfocused -mvThemeCol_TabUnfocusedActive=internal_dpg.mvThemeCol_TabUnfocusedActive -mvThemeCol_NavHighlight=internal_dpg.mvThemeCol_NavHighlight -mvPlotCol_Line=internal_dpg.mvPlotCol_Line -mvPlotCol_Fill=internal_dpg.mvPlotCol_Fill -mvPlotCol_MarkerOutline=internal_dpg.mvPlotCol_MarkerOutline -mvPlotCol_MarkerFill=internal_dpg.mvPlotCol_MarkerFill -mvPlotCol_ErrorBar=internal_dpg.mvPlotCol_ErrorBar -mvPlotCol_FrameBg=internal_dpg.mvPlotCol_FrameBg -mvPlotCol_PlotBg=internal_dpg.mvPlotCol_PlotBg -mvPlotCol_PlotBorder=internal_dpg.mvPlotCol_PlotBorder -mvPlotCol_LegendBg=internal_dpg.mvPlotCol_LegendBg -mvPlotCol_LegendBorder=internal_dpg.mvPlotCol_LegendBorder -mvPlotCol_LegendText=internal_dpg.mvPlotCol_LegendText -mvPlotCol_TitleText=internal_dpg.mvPlotCol_TitleText -mvPlotCol_InlayText=internal_dpg.mvPlotCol_InlayText -mvPlotCol_AxisText=internal_dpg.mvPlotCol_AxisText -mvPlotCol_AxisGrid=internal_dpg.mvPlotCol_AxisGrid -mvPlotCol_AxisTick=internal_dpg.mvPlotCol_AxisTick -mvPlotCol_AxisBg=internal_dpg.mvPlotCol_AxisBg -mvPlotCol_AxisBgHovered=internal_dpg.mvPlotCol_AxisBgHovered -mvPlotCol_AxisBgActive=internal_dpg.mvPlotCol_AxisBgActive -mvPlotCol_Selection=internal_dpg.mvPlotCol_Selection -mvPlotCol_Crosshairs=internal_dpg.mvPlotCol_Crosshairs -mvNodeCol_NodeBackground=internal_dpg.mvNodeCol_NodeBackground -mvNodeCol_NodeBackgroundHovered=internal_dpg.mvNodeCol_NodeBackgroundHovered -mvNodeCol_NodeBackgroundSelected=internal_dpg.mvNodeCol_NodeBackgroundSelected -mvNodeCol_NodeOutline=internal_dpg.mvNodeCol_NodeOutline -mvNodeCol_TitleBar=internal_dpg.mvNodeCol_TitleBar -mvNodeCol_TitleBarHovered=internal_dpg.mvNodeCol_TitleBarHovered -mvNodeCol_TitleBarSelected=internal_dpg.mvNodeCol_TitleBarSelected -mvNodeCol_Link=internal_dpg.mvNodeCol_Link -mvNodeCol_LinkHovered=internal_dpg.mvNodeCol_LinkHovered -mvNodeCol_LinkSelected=internal_dpg.mvNodeCol_LinkSelected -mvNodeCol_Pin=internal_dpg.mvNodeCol_Pin -mvNodeCol_PinHovered=internal_dpg.mvNodeCol_PinHovered -mvNodeCol_BoxSelector=internal_dpg.mvNodeCol_BoxSelector -mvNodeCol_BoxSelectorOutline=internal_dpg.mvNodeCol_BoxSelectorOutline -mvNodeCol_GridBackground=internal_dpg.mvNodeCol_GridBackground -mvNodeCol_GridLine=internal_dpg.mvNodeCol_GridLine -mvNodesCol_GridLinePrimary=internal_dpg.mvNodesCol_GridLinePrimary -mvNodesCol_MiniMapBackground=internal_dpg.mvNodesCol_MiniMapBackground -mvNodesCol_MiniMapBackgroundHovered=internal_dpg.mvNodesCol_MiniMapBackgroundHovered -mvNodesCol_MiniMapOutline=internal_dpg.mvNodesCol_MiniMapOutline -mvNodesCol_MiniMapOutlineHovered=internal_dpg.mvNodesCol_MiniMapOutlineHovered -mvNodesCol_MiniMapNodeBackground=internal_dpg.mvNodesCol_MiniMapNodeBackground -mvNodesCol_MiniMapNodeBackgroundHovered=internal_dpg.mvNodesCol_MiniMapNodeBackgroundHovered -mvNodesCol_MiniMapNodeBackgroundSelected=internal_dpg.mvNodesCol_MiniMapNodeBackgroundSelected -mvNodesCol_MiniMapNodeOutline=internal_dpg.mvNodesCol_MiniMapNodeOutline -mvNodesCol_MiniMapLink=internal_dpg.mvNodesCol_MiniMapLink -mvNodesCol_MiniMapLinkSelected=internal_dpg.mvNodesCol_MiniMapLinkSelected -mvNodesCol_MiniMapCanvas=internal_dpg.mvNodesCol_MiniMapCanvas -mvNodesCol_MiniMapCanvasOutline=internal_dpg.mvNodesCol_MiniMapCanvasOutline -mvStyleVar_Alpha=internal_dpg.mvStyleVar_Alpha -mvStyleVar_DisabledAlpha=internal_dpg.mvStyleVar_DisabledAlpha -mvStyleVar_WindowPadding=internal_dpg.mvStyleVar_WindowPadding -mvStyleVar_WindowRounding=internal_dpg.mvStyleVar_WindowRounding -mvStyleVar_WindowBorderSize=internal_dpg.mvStyleVar_WindowBorderSize -mvStyleVar_WindowMinSize=internal_dpg.mvStyleVar_WindowMinSize -mvStyleVar_WindowTitleAlign=internal_dpg.mvStyleVar_WindowTitleAlign -mvStyleVar_ChildRounding=internal_dpg.mvStyleVar_ChildRounding -mvStyleVar_ChildBorderSize=internal_dpg.mvStyleVar_ChildBorderSize -mvStyleVar_PopupRounding=internal_dpg.mvStyleVar_PopupRounding -mvStyleVar_PopupBorderSize=internal_dpg.mvStyleVar_PopupBorderSize -mvStyleVar_FramePadding=internal_dpg.mvStyleVar_FramePadding -mvStyleVar_FrameRounding=internal_dpg.mvStyleVar_FrameRounding -mvStyleVar_FrameBorderSize=internal_dpg.mvStyleVar_FrameBorderSize -mvStyleVar_ItemSpacing=internal_dpg.mvStyleVar_ItemSpacing -mvStyleVar_ItemInnerSpacing=internal_dpg.mvStyleVar_ItemInnerSpacing -mvStyleVar_IndentSpacing=internal_dpg.mvStyleVar_IndentSpacing -mvStyleVar_CellPadding=internal_dpg.mvStyleVar_CellPadding -mvStyleVar_ScrollbarSize=internal_dpg.mvStyleVar_ScrollbarSize -mvStyleVar_ScrollbarRounding=internal_dpg.mvStyleVar_ScrollbarRounding -mvStyleVar_ScrollbarPadding=internal_dpg.mvStyleVar_ScrollbarPadding -mvStyleVar_GrabMinSize=internal_dpg.mvStyleVar_GrabMinSize -mvStyleVar_GrabRounding=internal_dpg.mvStyleVar_GrabRounding -mvStyleVar_ImageBorderSize=internal_dpg.mvStyleVar_ImageBorderSize -mvStyleVar_TabRounding=internal_dpg.mvStyleVar_TabRounding -mvStyleVar_TabBorderSize=internal_dpg.mvStyleVar_TabBorderSize -mvStyleVar_TabMinWidthBase=internal_dpg.mvStyleVar_TabMinWidthBase -mvStyleVar_TabMinWidthShrink=internal_dpg.mvStyleVar_TabMinWidthShrink -mvStyleVar_TabBarBorderSize=internal_dpg.mvStyleVar_TabBarBorderSize -mvStyleVar_TabBarOverlineSize=internal_dpg.mvStyleVar_TabBarOverlineSize -mvStyleVar_TableAngledHeadersAngle=internal_dpg.mvStyleVar_TableAngledHeadersAngle -mvStyleVar_TableAngledHeadersTextAlign=internal_dpg.mvStyleVar_TableAngledHeadersTextAlign -mvStyleVar_TreeLinesSize=internal_dpg.mvStyleVar_TreeLinesSize -mvStyleVar_TreeLinesRounding=internal_dpg.mvStyleVar_TreeLinesRounding -mvStyleVar_ButtonTextAlign=internal_dpg.mvStyleVar_ButtonTextAlign -mvStyleVar_SelectableTextAlign=internal_dpg.mvStyleVar_SelectableTextAlign -mvStyleVar_SeparatorTextBorderSize=internal_dpg.mvStyleVar_SeparatorTextBorderSize -mvStyleVar_SeparatorTextAlign=internal_dpg.mvStyleVar_SeparatorTextAlign -mvStyleVar_SeparatorTextPadding=internal_dpg.mvStyleVar_SeparatorTextPadding -mvStyleVar_DockingSeparatorSize=internal_dpg.mvStyleVar_DockingSeparatorSize -mvPlotStyleVar_LineWeight=internal_dpg.mvPlotStyleVar_LineWeight -mvPlotStyleVar_Marker=internal_dpg.mvPlotStyleVar_Marker -mvPlotStyleVar_MarkerSize=internal_dpg.mvPlotStyleVar_MarkerSize -mvPlotStyleVar_MarkerWeight=internal_dpg.mvPlotStyleVar_MarkerWeight -mvPlotStyleVar_FillAlpha=internal_dpg.mvPlotStyleVar_FillAlpha -mvPlotStyleVar_ErrorBarSize=internal_dpg.mvPlotStyleVar_ErrorBarSize -mvPlotStyleVar_ErrorBarWeight=internal_dpg.mvPlotStyleVar_ErrorBarWeight -mvPlotStyleVar_DigitalBitHeight=internal_dpg.mvPlotStyleVar_DigitalBitHeight -mvPlotStyleVar_DigitalBitGap=internal_dpg.mvPlotStyleVar_DigitalBitGap -mvPlotStyleVar_PlotBorderSize=internal_dpg.mvPlotStyleVar_PlotBorderSize -mvPlotStyleVar_MinorAlpha=internal_dpg.mvPlotStyleVar_MinorAlpha -mvPlotStyleVar_MajorTickLen=internal_dpg.mvPlotStyleVar_MajorTickLen -mvPlotStyleVar_MinorTickLen=internal_dpg.mvPlotStyleVar_MinorTickLen -mvPlotStyleVar_MajorTickSize=internal_dpg.mvPlotStyleVar_MajorTickSize -mvPlotStyleVar_MinorTickSize=internal_dpg.mvPlotStyleVar_MinorTickSize -mvPlotStyleVar_MajorGridSize=internal_dpg.mvPlotStyleVar_MajorGridSize -mvPlotStyleVar_MinorGridSize=internal_dpg.mvPlotStyleVar_MinorGridSize -mvPlotStyleVar_PlotPadding=internal_dpg.mvPlotStyleVar_PlotPadding -mvPlotStyleVar_LabelPadding=internal_dpg.mvPlotStyleVar_LabelPadding -mvPlotStyleVar_LegendPadding=internal_dpg.mvPlotStyleVar_LegendPadding -mvPlotStyleVar_LegendInnerPadding=internal_dpg.mvPlotStyleVar_LegendInnerPadding -mvPlotStyleVar_LegendSpacing=internal_dpg.mvPlotStyleVar_LegendSpacing -mvPlotStyleVar_MousePosPadding=internal_dpg.mvPlotStyleVar_MousePosPadding -mvPlotStyleVar_AnnotationPadding=internal_dpg.mvPlotStyleVar_AnnotationPadding -mvPlotStyleVar_FitPadding=internal_dpg.mvPlotStyleVar_FitPadding -mvPlotStyleVar_PlotDefaultSize=internal_dpg.mvPlotStyleVar_PlotDefaultSize -mvPlotStyleVar_PlotMinSize=internal_dpg.mvPlotStyleVar_PlotMinSize -mvNodeStyleVar_GridSpacing=internal_dpg.mvNodeStyleVar_GridSpacing -mvNodeStyleVar_NodeCornerRounding=internal_dpg.mvNodeStyleVar_NodeCornerRounding -mvNodeStyleVar_NodePadding=internal_dpg.mvNodeStyleVar_NodePadding -mvNodeStyleVar_NodeBorderThickness=internal_dpg.mvNodeStyleVar_NodeBorderThickness -mvNodeStyleVar_LinkThickness=internal_dpg.mvNodeStyleVar_LinkThickness -mvNodeStyleVar_LinkLineSegmentsPerLength=internal_dpg.mvNodeStyleVar_LinkLineSegmentsPerLength -mvNodeStyleVar_LinkHoverDistance=internal_dpg.mvNodeStyleVar_LinkHoverDistance -mvNodeStyleVar_PinCircleRadius=internal_dpg.mvNodeStyleVar_PinCircleRadius -mvNodeStyleVar_PinQuadSideLength=internal_dpg.mvNodeStyleVar_PinQuadSideLength -mvNodeStyleVar_PinTriangleSideLength=internal_dpg.mvNodeStyleVar_PinTriangleSideLength -mvNodeStyleVar_PinLineThickness=internal_dpg.mvNodeStyleVar_PinLineThickness -mvNodeStyleVar_PinHoverRadius=internal_dpg.mvNodeStyleVar_PinHoverRadius -mvNodeStyleVar_PinOffset=internal_dpg.mvNodeStyleVar_PinOffset -mvNodesStyleVar_MiniMapPadding=internal_dpg.mvNodesStyleVar_MiniMapPadding -mvNodesStyleVar_MiniMapOffset=internal_dpg.mvNodesStyleVar_MiniMapOffset -mvInputText=internal_dpg.mvInputText -mvButton=internal_dpg.mvButton -mvRadioButton=internal_dpg.mvRadioButton -mvTabBar=internal_dpg.mvTabBar -mvTab=internal_dpg.mvTab -mvImage=internal_dpg.mvImage -mvMenuBar=internal_dpg.mvMenuBar -mvViewportMenuBar=internal_dpg.mvViewportMenuBar -mvMenu=internal_dpg.mvMenu -mvMenuItem=internal_dpg.mvMenuItem -mvChildWindow=internal_dpg.mvChildWindow -mvGroup=internal_dpg.mvGroup -mvSliderFloat=internal_dpg.mvSliderFloat -mvSliderInt=internal_dpg.mvSliderInt -mvFilterSet=internal_dpg.mvFilterSet -mvDragFloat=internal_dpg.mvDragFloat -mvDragInt=internal_dpg.mvDragInt -mvInputFloat=internal_dpg.mvInputFloat -mvInputInt=internal_dpg.mvInputInt -mvColorEdit=internal_dpg.mvColorEdit -mvClipper=internal_dpg.mvClipper -mvColorPicker=internal_dpg.mvColorPicker -mvTooltip=internal_dpg.mvTooltip -mvCollapsingHeader=internal_dpg.mvCollapsingHeader -mvSeparator=internal_dpg.mvSeparator -mvCheckbox=internal_dpg.mvCheckbox -mvListbox=internal_dpg.mvListbox -mvText=internal_dpg.mvText -mvCombo=internal_dpg.mvCombo -mvPlot=internal_dpg.mvPlot -mvSimplePlot=internal_dpg.mvSimplePlot -mvDrawlist=internal_dpg.mvDrawlist -mvWindowAppItem=internal_dpg.mvWindowAppItem -mvSelectable=internal_dpg.mvSelectable -mvTreeNode=internal_dpg.mvTreeNode -mvProgressBar=internal_dpg.mvProgressBar -mvSpacer=internal_dpg.mvSpacer -mvImageButton=internal_dpg.mvImageButton -mvTimePicker=internal_dpg.mvTimePicker -mvDatePicker=internal_dpg.mvDatePicker -mvColorButton=internal_dpg.mvColorButton -mvFileDialog=internal_dpg.mvFileDialog -mvTabButton=internal_dpg.mvTabButton -mvDrawNode=internal_dpg.mvDrawNode -mvNodeEditor=internal_dpg.mvNodeEditor -mvNode=internal_dpg.mvNode -mvNodeAttribute=internal_dpg.mvNodeAttribute -mvTable=internal_dpg.mvTable -mvTableColumn=internal_dpg.mvTableColumn -mvTableRow=internal_dpg.mvTableRow -mvSyncedTables=internal_dpg.mvSyncedTables -mvDrawLine=internal_dpg.mvDrawLine -mvDrawArrow=internal_dpg.mvDrawArrow -mvDrawTriangle=internal_dpg.mvDrawTriangle -mvDrawImageQuad=internal_dpg.mvDrawImageQuad -mvDrawCircle=internal_dpg.mvDrawCircle -mvDrawEllipse=internal_dpg.mvDrawEllipse -mvDrawBezierCubic=internal_dpg.mvDrawBezierCubic -mvDrawBezierQuadratic=internal_dpg.mvDrawBezierQuadratic -mvDrawQuad=internal_dpg.mvDrawQuad -mvDrawRect=internal_dpg.mvDrawRect -mvDrawText=internal_dpg.mvDrawText -mvDrawPolygon=internal_dpg.mvDrawPolygon -mvDrawPolyline=internal_dpg.mvDrawPolyline -mvDrawImage=internal_dpg.mvDrawImage -mvDragFloatMulti=internal_dpg.mvDragFloatMulti -mvDragIntMulti=internal_dpg.mvDragIntMulti -mvSliderFloatMulti=internal_dpg.mvSliderFloatMulti -mvSliderIntMulti=internal_dpg.mvSliderIntMulti -mvInputIntMulti=internal_dpg.mvInputIntMulti -mvInputFloatMulti=internal_dpg.mvInputFloatMulti -mvDragPoint=internal_dpg.mvDragPoint -mvDragLine=internal_dpg.mvDragLine -mvDragRect=internal_dpg.mvDragRect -mvAnnotation=internal_dpg.mvAnnotation -mvAxisTag=internal_dpg.mvAxisTag -mvLineSeries=internal_dpg.mvLineSeries -mvScatterSeries=internal_dpg.mvScatterSeries -mvStemSeries=internal_dpg.mvStemSeries -mvStairSeries=internal_dpg.mvStairSeries -mvBarSeries=internal_dpg.mvBarSeries -mvBarGroupSeries=internal_dpg.mvBarGroupSeries -mvErrorSeries=internal_dpg.mvErrorSeries -mvInfLineSeries=internal_dpg.mvInfLineSeries -mvHeatSeries=internal_dpg.mvHeatSeries -mvImageSeries=internal_dpg.mvImageSeries -mvPieSeries=internal_dpg.mvPieSeries -mvShadeSeries=internal_dpg.mvShadeSeries -mvLabelSeries=internal_dpg.mvLabelSeries -mvHistogramSeries=internal_dpg.mvHistogramSeries -mvDigitalSeries=internal_dpg.mvDigitalSeries -mv2dHistogramSeries=internal_dpg.mv2dHistogramSeries -mvCandleSeries=internal_dpg.mvCandleSeries -mvAreaSeries=internal_dpg.mvAreaSeries -mvColorMapScale=internal_dpg.mvColorMapScale -mvSlider3D=internal_dpg.mvSlider3D -mvKnobFloat=internal_dpg.mvKnobFloat -mvLoadingIndicator=internal_dpg.mvLoadingIndicator -mvNodeLink=internal_dpg.mvNodeLink -mvTextureRegistry=internal_dpg.mvTextureRegistry -mvStaticTexture=internal_dpg.mvStaticTexture -mvDynamicTexture=internal_dpg.mvDynamicTexture -mvStage=internal_dpg.mvStage -mvDrawLayer=internal_dpg.mvDrawLayer -mvViewportDrawlist=internal_dpg.mvViewportDrawlist -mvFileExtension=internal_dpg.mvFileExtension -mvPlotLegend=internal_dpg.mvPlotLegend -mvPlotAxis=internal_dpg.mvPlotAxis -mvHandlerRegistry=internal_dpg.mvHandlerRegistry -mvKeyDownHandler=internal_dpg.mvKeyDownHandler -mvKeyPressHandler=internal_dpg.mvKeyPressHandler -mvKeyReleaseHandler=internal_dpg.mvKeyReleaseHandler -mvMouseMoveHandler=internal_dpg.mvMouseMoveHandler -mvMouseWheelHandler=internal_dpg.mvMouseWheelHandler -mvMouseClickHandler=internal_dpg.mvMouseClickHandler -mvMouseDoubleClickHandler=internal_dpg.mvMouseDoubleClickHandler -mvMouseDownHandler=internal_dpg.mvMouseDownHandler -mvMouseReleaseHandler=internal_dpg.mvMouseReleaseHandler -mvMouseDragHandler=internal_dpg.mvMouseDragHandler -mvHoverHandler=internal_dpg.mvHoverHandler -mvActiveHandler=internal_dpg.mvActiveHandler -mvFocusHandler=internal_dpg.mvFocusHandler -mvVisibleHandler=internal_dpg.mvVisibleHandler -mvEditedHandler=internal_dpg.mvEditedHandler -mvActivatedHandler=internal_dpg.mvActivatedHandler -mvDeactivatedHandler=internal_dpg.mvDeactivatedHandler -mvDeactivatedAfterEditHandler=internal_dpg.mvDeactivatedAfterEditHandler -mvToggledOpenHandler=internal_dpg.mvToggledOpenHandler -mvClickedHandler=internal_dpg.mvClickedHandler -mvDoubleClickedHandler=internal_dpg.mvDoubleClickedHandler -mvScrollHandler=internal_dpg.mvScrollHandler -mvDragPayload=internal_dpg.mvDragPayload -mvResizeHandler=internal_dpg.mvResizeHandler -mvFont=internal_dpg.mvFont -mvFontRegistry=internal_dpg.mvFontRegistry -mvTheme=internal_dpg.mvTheme -mvThemeColor=internal_dpg.mvThemeColor -mvThemeStyle=internal_dpg.mvThemeStyle -mvThemeComponent=internal_dpg.mvThemeComponent -mvCharRemap=internal_dpg.mvCharRemap -mvValueRegistry=internal_dpg.mvValueRegistry -mvIntValue=internal_dpg.mvIntValue -mvFloatValue=internal_dpg.mvFloatValue -mvFloat4Value=internal_dpg.mvFloat4Value -mvInt4Value=internal_dpg.mvInt4Value -mvBoolValue=internal_dpg.mvBoolValue -mvStringValue=internal_dpg.mvStringValue -mvDoubleValue=internal_dpg.mvDoubleValue -mvDouble4Value=internal_dpg.mvDouble4Value -mvColorValue=internal_dpg.mvColorValue -mvFloatVectValue=internal_dpg.mvFloatVectValue -mvSeriesValue=internal_dpg.mvSeriesValue -mvRawTexture=internal_dpg.mvRawTexture -mvSubPlots=internal_dpg.mvSubPlots -mvColorMap=internal_dpg.mvColorMap -mvColorMapRegistry=internal_dpg.mvColorMapRegistry -mvColorMapButton=internal_dpg.mvColorMapButton -mvColorMapSlider=internal_dpg.mvColorMapSlider -mvTemplateRegistry=internal_dpg.mvTemplateRegistry -mvTableCell=internal_dpg.mvTableCell -mvItemHandlerRegistry=internal_dpg.mvItemHandlerRegistry -mvInputDouble=internal_dpg.mvInputDouble -mvInputDoubleMulti=internal_dpg.mvInputDoubleMulti -mvDragDouble=internal_dpg.mvDragDouble -mvDragDoubleMulti=internal_dpg.mvDragDoubleMulti -mvSliderDouble=internal_dpg.mvSliderDouble -mvSliderDoubleMulti=internal_dpg.mvSliderDoubleMulti -mvCustomSeries=internal_dpg.mvCustomSeries -mvReservedUUID_0=internal_dpg.mvReservedUUID_0 -mvReservedUUID_1=internal_dpg.mvReservedUUID_1 -mvReservedUUID_2=internal_dpg.mvReservedUUID_2 -mvReservedUUID_3=internal_dpg.mvReservedUUID_3 -mvReservedUUID_4=internal_dpg.mvReservedUUID_4 -mvReservedUUID_5=internal_dpg.mvReservedUUID_5 -mvReservedUUID_6=internal_dpg.mvReservedUUID_6 -mvReservedUUID_7=internal_dpg.mvReservedUUID_7 -mvReservedUUID_8=internal_dpg.mvReservedUUID_8 -mvReservedUUID_9=internal_dpg.mvReservedUUID_9 -mvReservedUUID_10=internal_dpg.mvReservedUUID_10 diff --git a/dearpygui/_deprecated.py b/dearpygui/_deprecated.py deleted file mode 100644 index a59110f87..000000000 --- a/dearpygui/_deprecated.py +++ /dev/null @@ -1,477 +0,0 @@ - -from typing import Union - - -def deprecated(reason): - - string_types = (type(b''), type(u'')) - - if isinstance(reason, string_types): - - def decorator(func1): - - fmt1 = "Call to deprecated function {name} ({reason})." - - @functools.wraps(func1) - def new_func1(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt1.format(name=func1.__name__, reason=reason), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func1(*args, **kwargs) - - return new_func1 - - return decorator - - elif inspect.isfunction(reason): - - func2 = reason - fmt2 = "Call to deprecated function {name}." - - @functools.wraps(func2) - def new_func2(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt2.format(name=func2.__name__), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func2(*args, **kwargs) - - return new_func2 - -@deprecated("Use 'configure_app(init_file=file)'.") -def set_init_file(file="dpg.ini"): - """ deprecated function """ - internal_dpg.configure_app(init_file=file) - -@deprecated("Use 'configure_app(init_file=file, load_init_file=True)'.") -def load_init_file(file): - """ deprecated function """ - internal_dpg.configure_app(init_file=file, load_init_file=True) - -@deprecated("Use: `is_viewport_ok(...)`") -def is_viewport_created(): - """ deprecated function """ - return internal_dpg.is_viewport_ok() - -@deprecated("Use: \ncreate_viewport()\nsetup_dearpygui()\nshow_viewport()") -def setup_viewport(): - """ deprecated function """ - internal_dpg.create_viewport() - internal_dpg.setup_dearpygui() - internal_dpg.show_viewport() - -@deprecated("Use: `bind_item_theme(...)`") -def set_item_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_theme(item, theme) - -@deprecated("Use: `bind_item_type_disabled_theme(...)`") -def set_item_type_disabled_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_disabled_theme(item, theme) - -@deprecated("Use: `bind_item_type_theme(...)`") -def set_item_type_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_theme(item, theme) - -@deprecated("Use: `bind_item_font(...)`") -def set_item_font(item, font): - """ deprecated function """ - return internal_dpg.bind_item_font(item, font) - -@deprecated("Use: `add_item_activated_handler(...)`") -def add_activated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_activated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_active_handler(...)`") -def add_active_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_active_handler(parent, **kwargs) - -@deprecated("Use: `add_item_clicked_handler(...)`") -def add_clicked_handler(parent, button=-1, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_clicked_handler(parent, button, **kwargs) - -@deprecated("Use: `add_item_deactived_after_edit_handler(...)`") -def add_deactivated_after_edit_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_after_edit_handler(parent, **kwargs) - -@deprecated("Use: `add_item_deactivated_handler(...)`") -def add_deactivated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_edited_handler(...)`") -def add_edited_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_edited_handler(parent, **kwargs) - -@deprecated("Use: `add_item_focus_handler(...)`") -def add_focus_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_focus_handler(parent, **kwargs) - -@deprecated("Use: `add_item_hover_handler(...)`") -def add_hover_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_hover_handler(parent, **kwargs) - -@deprecated("Use: `add_item_resize_handler(...)`") -def add_resize_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_resize_handler(parent, **kwargs) - -@deprecated("Use: `add_item_toggled_open_handler(...)`") -def add_toggled_open_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_toggled_open_handler(parent, **kwargs) - -@deprecated("Use: `add_item_visible_handler(...)`") -def add_visible_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_visible_handler(parent, **kwargs) - -@deprecated("Use: `bind_colormap(...)`") -def set_colormap(item, source): - """ deprecated function """ - return internal_dpg.bind_colormap(item, source) - -@deprecated("Use: `bind_theme(0)`") -def reset_default_theme(item, source): - """ deprecated function """ - return internal_dpg.bind_theme(item, source) - -@deprecated -def set_staging_mode(mode): - """ deprecated function """ - pass - -@deprecated -def add_table_next_column(**kwargs): - """ deprecated function """ - pass - -@deprecated("Use: add_stage") -def add_staging_container(**kwargs): - """ deprecated function """ - return internal_dpg.add_stage(**kwargs) - -@deprecated("Use: stage") -@contextmanager -def staging_container(**kwargs): - """ - deprecated function - Args: - **label (str): Overrides 'name' as label. - **user_data (Any): User data for callbacks. - **use_internal_label (bool): Use generated internal label instead of user specified (appends ### uuid). - **id (Union[int, str]): Unique id used to programmatically refer to the item.If label is unused this will be the label. - Yields: - Union[int, str] - """ - try: - warnings.warn("'staging_container' is deprecated and was changed to 'stage'", DeprecationWarning, 2) - widget = internal_dpg.add_stage_container(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: add_spacer(...)") -def add_spacing(**kwargs): - """ (deprecated function) Adds vertical spacing. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - count (int, optional): Number of spacings to add the size is dependant on the curret style. - Returns: - Union[int, str] - """ - - if 'count' in kwargs.keys(): - count = kwargs["count"] - kwargs.pop("count", None) - internal_dpg.add_group(**kwargs) - internal_dpg.push_container_stack(internal_dpg.last_container()) - for i in range(count): - internal_dpg.add_spacer() - result_id = internal_dpg.pop_container_stack() - else: - result_id = internal_dpg.add_spacer(**kwargs) - return result_id - -@deprecated("Use: add_spacer(...)") -def add_dummy(**kwargs): - """ (deprecated function) Adds a spacer or 'dummy' object. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - Returns: - Union[int, str] - """ - - return internal_dpg.add_spacer(**kwargs) - -@deprecated("Use: `destroy_context()`") -def cleanup_dearpygui(): - """ deprecated function """ - return internal_dpg.destroy_context() - -@deprecated("Use: group(horizontal=True)") -def add_same_line(**kwargs): - """ deprecated function """ - - last_item = internal_dpg.last_item() - group = internal_dpg.add_group(horizontal=True, **kwargs) - internal_dpg.move_item(last_item, parent=group) - internal_dpg.capture_next_item(lambda s: internal_dpg.move_item(s, parent=group)) - return group - -@deprecated("Use: `get_plot_query_rects()`") -def is_plot_queried(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns true if the plot is currently being queried. - - Args: - plot (Union[int, str]): - Returns: - bool - """ - - return len(internal_dpg.get_plot_query_rects(plot, **kwargs)) > 0 - -@deprecated("Use: `get_plot_query_rects()`") -def get_plot_query_area(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns the last/current query area of the plot. If no area is available [0, 0, 0, 0] will be returned. - - Args: - plot (Union[int, str]): - Returns: - Union[List[float], Tuple[float, ...]] - """ - - if rects := internal_dpg.get_plot_query_rects(plot, **kwargs): - return rects[0] - else: - return [0, 0, 0, 0] - -@deprecated("Use: `add_inf_line_series(horizontal=True)`") -def add_hline_series(x, **kwargs): - """ (deprecated function) Adds an infinite horizontal line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs, horizontal=True) - - -@deprecated("Use: `add_inf_line_series()`") -def add_vline_series(x, **kwargs): - """ (deprecated function) Adds an infinite vertical line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs) - - -@deprecated("Use: `add_child_window()`") -def add_child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Returns: - Union[int, str] - """ - - return internal_dpg.add_child_window(**kwargs) - - -@deprecated("Use: `child_window()`") -@contextmanager -def child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_child_window(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: Just not recommended") -def setup_registries() -> None: - """Adds default registries for fonts, handlers, textures, colormaps, and values.""" - internal_dpg.add_font_registry(tag=internal_dpg.mvReservedUUID_0) - internal_dpg.add_handler_registry(tag=internal_dpg.mvReservedUUID_1) - internal_dpg.add_texture_registry(tag=internal_dpg.mvReservedUUID_2) - internal_dpg.add_value_registry(tag=internal_dpg.mvReservedUUID_3) - internal_dpg.add_colormap_registry(tag=internal_dpg.mvReservedUUID_4) - -@deprecated("Useless and doesn't work anyway") -def is_item_search_delayed(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is search delayed. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["delay_search"] - -@deprecated("Use: `set_frame_callback()`") -def set_start_callback(callback): - """ deprecated function """ - return internal_dpg.set_frame_callback(3, callback) - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_chars(chars : Union[List[int], Tuple[int, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds specific font characters to a font. - - Args: - chars (Union[List[int], Tuple[int, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range(first_char : int, last_char : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters to a font. - - Args: - first_char (int): - last_char (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range_hint(hint : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters (mvFontRangeHint_ constants). - - Args: - hint (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass diff --git a/dearpygui/_header.py b/dearpygui/_header.py deleted file mode 100644 index 5bcbfff51..000000000 --- a/dearpygui/_header.py +++ /dev/null @@ -1,1102 +0,0 @@ -from typing import List, Any, Callable, Union, Tuple -from contextlib import contextmanager -import warnings -import functools -import inspect -import dearpygui._dearpygui as internal_dpg -from dearpygui._dearpygui import mvBuffer -from dearpygui._dearpygui import mvVec4 -from dearpygui._dearpygui import mvMat4 - -######################################################################################################################## -# User API Index -# -# * Sections -# - Helper Commands -# - Tool Commands -# - Information Commands -# - Configuration Getter Commands -# - Configuration Setter Commands -# - State Commands -# - Viewport Setter Commands -# - Viewport Getter Commands -# - Deprecated Commands -# - Container Context Managers -# - Public _dearpygui Wrappings -# - Constants -# -######################################################################################################################## - -######################################################################################################################## -# Helper Commands -######################################################################################################################## - -def run_callbacks(jobs): - """ New in 1.2. Runs callbacks from the callback queue and checks arguments. """ - - if jobs is None: - pass - else: - for job in jobs: - if job[0] is None: - pass - else: - sig = inspect.signature(job[0]) - args = [] - for arg in range(len(sig.parameters)): - args.append(job[arg+1]) - job[0](*args) - -def get_major_version(): - """ return Dear PyGui Major Version """ - return internal_dpg.get_app_configuration()["major_version"] - -def get_minor_version(): - """ return Dear PyGui Minor Version """ - return internal_dpg.get_app_configuration()["minor_version"] - -def get_dearpygui_version(): - """ return Dear PyGui Version """ - return internal_dpg.get_app_configuration()["version"] - -def configure_item(item : Union[int, str], **kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_item(item, **kwargs) - -def configure_app(**kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_app(**kwargs) - -def configure_viewport(item : Union[int, str], **kwargs) -> None: - """Configures a viewport after creation.""" - internal_dpg.configure_viewport(item, **kwargs) - -def start_dearpygui(): - """Prepares viewport (if not done already). sets up, cleans up, and runs main event loop. - - Returns: - None - """ - - if not internal_dpg.is_viewport_ok(): - raise RuntimeError("Viewport was not created and shown.") - - while(internal_dpg.is_dearpygui_running()): - internal_dpg.render_dearpygui_frame() - - -@contextmanager -def mutex(): - """ Handles locking/unlocking render thread mutex. """ - try: - yield internal_dpg.lock_mutex() - finally: - internal_dpg.unlock_mutex() - - -@contextmanager -def popup(parent: Union[int, str], mousebutton: int = internal_dpg.mvMouseButton_Right, modal: bool=False, tag:Union[int, str]=0, min_size:Union[List[int], Tuple[int, ...]]=[100,100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], no_move: bool=False, no_background: bool=False) -> int: - """A window that will be displayed when a parent item is hovered and the corresponding mouse button has been clicked. By default a popup will shrink fit the items it contains. - This is useful for context windows, and simple modal window popups. - When popups are used a modal they have more avaliable settings (i.e. title, resize, width, height) These - can be set by using configure item. - This is a light wrapper over window. For more control over a modal|popup window use a normal window with the modal|popup keyword - and set the item handler and mouse events manually. - - Args: - parent: The UI item that will need to be hovered. - **mousebutton: The mouse button that will trigger the window to popup. - **modal: Will force the user to interact with the popup. - **min_size: New in 1.4. Minimum window size. - **max_size: New in 1.4. Maximum window size. - **no_move: New in 1.4. Prevents the window from moving based on user input. - **no_background: New in 1.4. Sets Background and border alpha to transparent. - - Returns: - item's uuid - """ - try: - if tag == 0: - _internal_popup_id = internal_dpg.generate_uuid() - else: - _internal_popup_id = tag - _handler_reg_id = internal_dpg.add_item_handler_registry() - internal_dpg.add_item_clicked_handler(mousebutton, parent=internal_dpg.last_item(), callback=lambda: internal_dpg.configure_item(_internal_popup_id, show=True)) - internal_dpg.bind_item_handler_registry(parent, _handler_reg_id) - if modal: - internal_dpg.add_window(modal=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - else: - internal_dpg.add_window(popup=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - internal_dpg.push_container_stack(internal_dpg.last_container()) - yield _internal_popup_id - - finally: - internal_dpg.pop_container_stack() - - -######################################################################################################################## -# Tool Commands -######################################################################################################################## - -def show_style_editor() -> None: - """Shows the standard style editor window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Style) - - -def show_metrics() -> None: - """Shows the standard metrics window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Metrics) - - -def show_about() -> None: - """Shows the standard about window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_About) - - -def show_debug() -> None: - """Shows the standard debug window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Debug) - - -def show_documentation() -> None: - """Shows the standard documentation window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Doc) - - -def show_font_manager() -> None: - """Shows a debug tool for the font manager - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Font) - - -def show_item_registry() -> None: - """Shows the item hierarchy of your application - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_ItemRegistry) - - -######################################################################################################################## -# Information Commands -######################################################################################################################## - -def get_item_slot(item: Union[int, str]) -> Union[int, None]: - """Returns an item's target slot. - - Returns: - slot as a int - """ - return internal_dpg.get_item_info(item)["target"] - - -def is_item_container(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is a container. - - Returns: - status as a bool - """ - return internal_dpg.get_item_info(item)["container"] - - -def get_item_parent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's parent. - - Returns: - parent as a int or None - """ - return internal_dpg.get_item_info(item)["parent"] - - -def get_item_children(item: Union[int, str] , slot: int = -1) -> Union[dict, List[int], None]: - """Provides access to the item's children slots. - - Returns: - A 2-D tuple of children slots ex. ((child_slot_1),(child_slot_2),(child_slot_3),...) or a single slot if slot is used. - """ - if slot < 0 or slot > 4: - return internal_dpg.get_item_info(item)["children"] - return internal_dpg.get_item_info(item)["children"][slot] - - -def get_item_type(item: Union[int, str]) -> Union[str]: - """Gets the item's type. - - Returns: - type as a string or None - """ - return internal_dpg.get_item_info(item)["type"] - - -def get_item_theme(item: Union[int, str]) -> int: - """Gets the item's theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["theme"] - - -def get_item_font(item: Union[int, str]) -> int: - """Gets the item's font. - - Returns: - font's uuid - """ - return internal_dpg.get_item_info(item)["font"] - - -def get_item_disabled_theme(item: Union[int, str]) -> int: - """Gets the item's disabled theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["disabled_theme"] - - -######################################################################################################################## -# Configuration Setter Commands -######################################################################################################################## - -def enable_item(item: Union[int, str]): - """Enables the item. - - Args: - **item: Item to enable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=True) - - -def disable_item(item: Union[int, str]): - """Disables the item. - - Args: - **item: Item to disable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=False) - - -def set_item_label(item: Union[int, str], label: str): - """Sets the item's displayed label, anything after the characters "##" in the name will not be shown. - - Args: - item: Item label will be applied to. - label: Displayed name to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, label=label) - - -def set_item_source(item: Union[int, str], source: Union[int, str]): - """Sets the item's value, to the source's value. Widget's value will now be "linked" to source's value. - - Args: - item: Item to me linked. - source: Source to link to. - - Returns: - None - """ - internal_dpg.configure_item(item, source=source) - - -def set_item_pos(item: Union[int, str], pos: List[float]): - """Sets the item's position. - - Args: - item: Item the absolute position will be applied to. - pos: X and Y positions relative to parent of the item. - - Returns: - None - """ - internal_dpg.configure_item(item, pos=pos) - - -def set_item_width(item: Union[int, str], width: int): - """Sets the item's width. - - Args: - item: Item the Width will be applied to. - width: Width to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, width=width) - - -def set_item_height(item: Union[int, str], height: int): - """Sets the item's height. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, height=height) - - -def set_item_indent(item: Union[int, str], indent: int): - """Sets the item's indent. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, indent=indent) - - -def set_item_track_offset(item: Union[int, str], offset: float): - """Sets the item's track offset. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, track_offset=offset) - - -def set_item_payload_type(item: Union[int, str], payload_type: str): - """Sets the item's payload type. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, payload_type=str) - - -def set_item_callback(item: Union[int, str], callback: Callable): - """Sets the item's callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, callback=callback) - - -def set_item_drag_callback(item: Union[int, str], callback: Callable): - """Sets the item's drag callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drag_callback=callback) - - -def set_item_drop_callback(item: Union[int, str], callback: Callable): - """Sets the item's drop callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drop_callback=callback) - - -def track_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=True) - - -def untrack_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=False) - - -def set_item_user_data(item: Union[int, str], user_data: Any): - """Sets the item's callack_data to any python object. - - Args: - item: Item the callback will be applied to. - user_data: Callback_data to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, user_data=user_data) - - -def show_item(item: Union[int, str]): - """Shows the item. - - Args: - item: Item to show. - - Returns: - None - """ - internal_dpg.configure_item(item, show=True) - - -def hide_item(item: Union[int, str], *, children_only: bool = False): - """Hides the item. - - Args: - **item: Item to hide. - - Returns: - None - """ - if children_only: - children = get_item_children(item) - for child in children: - internal_dpg.configure_item(child, show=False) - else: - internal_dpg.configure_item(item, show=False) - - -######################################################################################################################## -# Configuration Getter Commands -######################################################################################################################## - -def get_item_label(item: Union[int, str]) -> Union[str, None]: - """Gets the item's label. - - Returns: - label as a string or None - """ - return internal_dpg.get_item_configuration(item)["label"] - - -def get_item_filter_key(item: Union[int, str]) -> Union[str, None]: - """Gets the item's filter key. - - Returns: - filter key as a string or None - """ - return internal_dpg.get_item_configuration(item)["filter_key"] - - -def is_item_tracked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is tracked. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["tracked"] - - -def get_item_indent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's indent. - - Returns: - indent as a int or None - """ - return internal_dpg.get_item_configuration(item)["indent"] - - -def get_item_track_offset(item: Union[int, str]) -> Union[float, None]: - """Gets the item's track offset. - - Returns: - track offset as a int or None - """ - return internal_dpg.get_item_configuration(item)["track_offset"] - - -def get_item_width(item: Union[int, str]) -> Union[int, None]: - """Gets the item's width. - - Returns: - width as a int or None - """ - return internal_dpg.get_item_configuration(item)["width"] - - -def get_item_height(item: Union[int, str]) -> Union[int, None]: - """Gets the item's height. - - Returns: - height as a int or None - """ - return internal_dpg.get_item_configuration(item)["height"] - - -def get_item_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["callback"] - - -def get_item_drag_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drag callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drag_callback"] - - -def get_item_drop_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drop callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drop_callback"] - - -def get_item_user_data(item: Union[int, str]) -> Union[Any, None]: - """Gets the item's callback data. - - Returns: - callback data as a python object or None - """ - return internal_dpg.get_item_configuration(item)["user_data"] - - -def get_item_source(item: Union[int, str]) -> Union[str, None]: - """Gets the item's source. - - Returns: - source as a string or None - """ - return internal_dpg.get_item_configuration(item)["source"] - - -######################################################################################################################## -# State Commands -######################################################################################################################## - -def is_item_hovered(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is hovered. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["hovered"] - - -def is_item_active(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is active. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["active"] - - -def is_item_focused(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is focused. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["focused"] - - -def is_item_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["clicked"] - - -def is_item_left_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is left clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["left_clicked"] - - -def is_item_right_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is right clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["right_clicked"] - - -def is_item_middle_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is middle clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["middle_clicked"] - - -def is_item_visible(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is visible. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["visible"] - - -def is_item_edited(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is edited. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["edited"] - - -def is_item_activated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is activated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["activated"] - - -def is_item_deactivated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated"] - - -def is_item_deactivated_after_edit(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated_after_edit. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated_after_edit"] - - -def is_item_toggled_open(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is toggled_open. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["toggled_open"] - - -def is_item_ok(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is ok and can be used. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["ok"] - - -def is_item_shown(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is shown. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["show"] - - -def is_item_enabled(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is enabled. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["enabled"] - - -def get_item_pos(item: Union[int, str]) -> List[int]: - """Returns item's position. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["pos"] - - -def get_available_content_region(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["content_region_avail"] - - -def get_item_rect_size(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_size"] - - -def get_item_rect_min(item: Union[int, str]) -> List[int]: - """Returns item's minimum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_min"] - - -def get_item_rect_max(item: Union[int, str]) -> List[int]: - """Returns item's maximum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_max"] - - -######################################################################################################################## -# Viewport Setter Commands -######################################################################################################################## - -def set_viewport_clear_color(color: List[int]): - """Sets the viewport's clear color. - - Returns: - None - """ - internal_dpg.configure_viewport(0, clear_color=color) - - -def set_viewport_small_icon(icon: str): - """Sets the viewport's small icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, small_icon=icon) - - -def set_viewport_large_icon(icon: str): - """Sets the viewport's large icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, large_icon=icon) - - -def set_viewport_pos(pos: List[float]): - """Sets the viewport's position. - - Returns: - None - """ - internal_dpg.configure_viewport(0, x_pos=pos[0], y_pos=pos[1]) - - -def set_viewport_width(width: int): - """Sets the viewport's width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, width=width) - - -def set_viewport_height(height: int): - """Sets the viewport's height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, height=height) - - -def set_viewport_min_width(width: int): - """Sets the viewport's minimum width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_width=width) - - -def set_viewport_max_width(width: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_width=width) - - -def set_viewport_min_height(height: int): - """Sets the viewport's minimum height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_height=height) - - -def set_viewport_max_height(height: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_height=height) - - -def set_viewport_title(title: str): - """Sets the viewport's title. - - Returns: - None - """ - internal_dpg.configure_viewport(0, title=title) - - -def set_viewport_always_top(value: bool): - """Sets the viewport always on top. - - Returns: - None - """ - internal_dpg.configure_viewport(0, always_on_top=value) - - -def set_viewport_resizable(value: bool): - """Sets the viewport resizable. - - Returns: - None - """ - internal_dpg.configure_viewport(0, resizable=value) - -def set_viewport_vsync(value: bool): - """Sets the viewport vsync. - - Returns: - None - """ - internal_dpg.configure_viewport(0, vsync=value) - - -def set_viewport_decorated(value: bool): - """Sets the viewport to be decorated. - - Returns: - None - """ - internal_dpg.configure_viewport(0, decorated=value) - -######################################################################################################################## -# Viewport Getter Commands -######################################################################################################################## - -def get_viewport_clear_color() ->List[int]: - """Gets the viewport's clear color. - - Returns: - List[int] - """ - return internal_dpg.get_viewport_configuration()["clear_color"] - - -def get_viewport_pos() ->List[float]: - """Gets the viewport's position. - - Returns: - viewport position. - """ - config = internal_dpg.get_viewport_configuration() - x_pos = config["x_pos"] - y_pos = config["y_pos"] - return [x_pos, y_pos] - - -def get_viewport_width() -> int: - """Gets the viewport's width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["width"] - - -def get_viewport_client_width() -> int: - """Gets the viewport's client width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_width"] - - -def get_viewport_client_height() -> int: - """Gets the viewport's client height. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_height"] - - -def get_viewport_height() -> int: - """Gets the viewport's height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["height"] - - -def get_viewport_min_width() -> int: - """Gets the viewport's minimum width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_width"] - - -def get_viewport_max_width() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_width"] - - -def get_viewport_min_height() -> int: - """Gets the viewport's minimum height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_height"] - - -def get_viewport_max_height() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_height"] - - -def get_viewport_title() -> str: - """Gets the viewport's title. - - Returns: - str - """ - return internal_dpg.get_viewport_configuration()["title"] - - -def is_viewport_always_top() -> bool: - """Checks the viewport always on top flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["always_on_top"] - - -def is_viewport_resizable() -> bool: - """Checks the viewport resizable flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["resizable"] - - -def is_viewport_vsync_on() -> bool: - """Checks the viewport vsync flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["vsync"] - - -def is_viewport_decorated() -> bool: - """Checks if the viewport is docorated. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["decorated"] diff --git a/dearpygui/dearpygui.py b/dearpygui/dearpygui.py deleted file mode 100644 index 9345a9b52..000000000 --- a/dearpygui/dearpygui.py +++ /dev/null @@ -1,10692 +0,0 @@ - -########################################################## -# Dear PyGui User Interface -# ~ Version: master -# -# Notes: -# * This file is automatically generated. -# -# Resources: -# * FAQ: https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq -# * Homepage: https://github.com/hoffstadt/DearPyGui -# * Wiki: https://github.com/hoffstadt/DearPyGui/wiki -# * Issues: https://github.com/hoffstadt/DearPyGui/issues -# * Discussions: https://github.com/hoffstadt/DearPyGui/discussions -########################################################## - -from typing import List, Any, Callable, Union, Tuple -from contextlib import contextmanager -import warnings -import functools -import inspect -import dearpygui._dearpygui as internal_dpg -from dearpygui._dearpygui import mvBuffer -from dearpygui._dearpygui import mvVec4 -from dearpygui._dearpygui import mvMat4 - -######################################################################################################################## -# User API Index -# -# * Sections -# - Helper Commands -# - Tool Commands -# - Information Commands -# - Configuration Getter Commands -# - Configuration Setter Commands -# - State Commands -# - Viewport Setter Commands -# - Viewport Getter Commands -# - Deprecated Commands -# - Container Context Managers -# - Public _dearpygui Wrappings -# - Constants -# -######################################################################################################################## - -######################################################################################################################## -# Helper Commands -######################################################################################################################## - -def run_callbacks(jobs): - """ New in 1.2. Runs callbacks from the callback queue and checks arguments. """ - - if jobs is None: - pass - else: - for job in jobs: - if job[0] is None: - pass - else: - sig = inspect.signature(job[0]) - args = [] - for arg in range(len(sig.parameters)): - args.append(job[arg+1]) - job[0](*args) - -def get_major_version(): - """ return Dear PyGui Major Version """ - return internal_dpg.get_app_configuration()["major_version"] - -def get_minor_version(): - """ return Dear PyGui Minor Version """ - return internal_dpg.get_app_configuration()["minor_version"] - -def get_dearpygui_version(): - """ return Dear PyGui Version """ - return internal_dpg.get_app_configuration()["version"] - -def configure_item(item : Union[int, str], **kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_item(item, **kwargs) - -def configure_app(**kwargs) -> None: - """Configures an item after creation.""" - internal_dpg.configure_app(**kwargs) - -def configure_viewport(item : Union[int, str], **kwargs) -> None: - """Configures a viewport after creation.""" - internal_dpg.configure_viewport(item, **kwargs) - -def start_dearpygui(): - """Prepares viewport (if not done already). sets up, cleans up, and runs main event loop. - - Returns: - None - """ - - if not internal_dpg.is_viewport_ok(): - raise RuntimeError("Viewport was not created and shown.") - - while(internal_dpg.is_dearpygui_running()): - internal_dpg.render_dearpygui_frame() - - -@contextmanager -def mutex(): - """ Handles locking/unlocking render thread mutex. """ - try: - yield internal_dpg.lock_mutex() - finally: - internal_dpg.unlock_mutex() - - -@contextmanager -def popup(parent: Union[int, str], mousebutton: int = internal_dpg.mvMouseButton_Right, modal: bool=False, tag:Union[int, str]=0, min_size:Union[List[int], Tuple[int, ...]]=[100,100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], no_move: bool=False, no_background: bool=False) -> int: - """A window that will be displayed when a parent item is hovered and the corresponding mouse button has been clicked. By default a popup will shrink fit the items it contains. - This is useful for context windows, and simple modal window popups. - When popups are used a modal they have more avaliable settings (i.e. title, resize, width, height) These - can be set by using configure item. - This is a light wrapper over window. For more control over a modal|popup window use a normal window with the modal|popup keyword - and set the item handler and mouse events manually. - - Args: - parent: The UI item that will need to be hovered. - **mousebutton: The mouse button that will trigger the window to popup. - **modal: Will force the user to interact with the popup. - **min_size: New in 1.4. Minimum window size. - **max_size: New in 1.4. Maximum window size. - **no_move: New in 1.4. Prevents the window from moving based on user input. - **no_background: New in 1.4. Sets Background and border alpha to transparent. - - Returns: - item's uuid - """ - try: - if tag == 0: - _internal_popup_id = internal_dpg.generate_uuid() - else: - _internal_popup_id = tag - _handler_reg_id = internal_dpg.add_item_handler_registry() - internal_dpg.add_item_clicked_handler(mousebutton, parent=internal_dpg.last_item(), callback=lambda: internal_dpg.configure_item(_internal_popup_id, show=True)) - internal_dpg.bind_item_handler_registry(parent, _handler_reg_id) - if modal: - internal_dpg.add_window(modal=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - else: - internal_dpg.add_window(popup=True, show=False, tag=_internal_popup_id, autosize=True, min_size=min_size, max_size=max_size, no_move=no_move, no_background=no_background) - internal_dpg.push_container_stack(internal_dpg.last_container()) - yield _internal_popup_id - - finally: - internal_dpg.pop_container_stack() - - -######################################################################################################################## -# Tool Commands -######################################################################################################################## - -def show_style_editor() -> None: - """Shows the standard style editor window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Style) - - -def show_metrics() -> None: - """Shows the standard metrics window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Metrics) - - -def show_about() -> None: - """Shows the standard about window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_About) - - -def show_debug() -> None: - """Shows the standard debug window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Debug) - - -def show_documentation() -> None: - """Shows the standard documentation window - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Doc) - - -def show_font_manager() -> None: - """Shows a debug tool for the font manager - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_Font) - - -def show_item_registry() -> None: - """Shows the item hierarchy of your application - - Returns: - None - """ - internal_dpg.show_tool(internal_dpg.mvTool_ItemRegistry) - - -######################################################################################################################## -# Information Commands -######################################################################################################################## - -def get_item_slot(item: Union[int, str]) -> Union[int, None]: - """Returns an item's target slot. - - Returns: - slot as a int - """ - return internal_dpg.get_item_info(item)["target"] - - -def is_item_container(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is a container. - - Returns: - status as a bool - """ - return internal_dpg.get_item_info(item)["container"] - - -def get_item_parent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's parent. - - Returns: - parent as a int or None - """ - return internal_dpg.get_item_info(item)["parent"] - - -def get_item_children(item: Union[int, str] , slot: int = -1) -> Union[dict, List[int], None]: - """Provides access to the item's children slots. - - Returns: - A 2-D tuple of children slots ex. ((child_slot_1),(child_slot_2),(child_slot_3),...) or a single slot if slot is used. - """ - if slot < 0 or slot > 4: - return internal_dpg.get_item_info(item)["children"] - return internal_dpg.get_item_info(item)["children"][slot] - - -def get_item_type(item: Union[int, str]) -> Union[str]: - """Gets the item's type. - - Returns: - type as a string or None - """ - return internal_dpg.get_item_info(item)["type"] - - -def get_item_theme(item: Union[int, str]) -> int: - """Gets the item's theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["theme"] - - -def get_item_font(item: Union[int, str]) -> int: - """Gets the item's font. - - Returns: - font's uuid - """ - return internal_dpg.get_item_info(item)["font"] - - -def get_item_disabled_theme(item: Union[int, str]) -> int: - """Gets the item's disabled theme. - - Returns: - theme's uuid - """ - return internal_dpg.get_item_info(item)["disabled_theme"] - - -######################################################################################################################## -# Configuration Setter Commands -######################################################################################################################## - -def enable_item(item: Union[int, str]): - """Enables the item. - - Args: - **item: Item to enable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=True) - - -def disable_item(item: Union[int, str]): - """Disables the item. - - Args: - **item: Item to disable. - - Returns: - None - """ - internal_dpg.configure_item(item, enabled=False) - - -def set_item_label(item: Union[int, str], label: str): - """Sets the item's displayed label, anything after the characters "##" in the name will not be shown. - - Args: - item: Item label will be applied to. - label: Displayed name to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, label=label) - - -def set_item_source(item: Union[int, str], source: Union[int, str]): - """Sets the item's value, to the source's value. Widget's value will now be "linked" to source's value. - - Args: - item: Item to me linked. - source: Source to link to. - - Returns: - None - """ - internal_dpg.configure_item(item, source=source) - - -def set_item_pos(item: Union[int, str], pos: List[float]): - """Sets the item's position. - - Args: - item: Item the absolute position will be applied to. - pos: X and Y positions relative to parent of the item. - - Returns: - None - """ - internal_dpg.configure_item(item, pos=pos) - - -def set_item_width(item: Union[int, str], width: int): - """Sets the item's width. - - Args: - item: Item the Width will be applied to. - width: Width to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, width=width) - - -def set_item_height(item: Union[int, str], height: int): - """Sets the item's height. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, height=height) - - -def set_item_indent(item: Union[int, str], indent: int): - """Sets the item's indent. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, indent=indent) - - -def set_item_track_offset(item: Union[int, str], offset: float): - """Sets the item's track offset. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, track_offset=offset) - - -def set_item_payload_type(item: Union[int, str], payload_type: str): - """Sets the item's payload type. - - Args: - item: Item the Height will be applied to. - height: Height to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, payload_type=str) - - -def set_item_callback(item: Union[int, str], callback: Callable): - """Sets the item's callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, callback=callback) - - -def set_item_drag_callback(item: Union[int, str], callback: Callable): - """Sets the item's drag callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drag_callback=callback) - - -def set_item_drop_callback(item: Union[int, str], callback: Callable): - """Sets the item's drop callack. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, drop_callback=callback) - - -def track_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=True) - - -def untrack_item(item: Union[int, str]): - """Track item in scroll region. - - Args: - item: Item the callback will be applied to. - callback: Callback to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, tracked=False) - - -def set_item_user_data(item: Union[int, str], user_data: Any): - """Sets the item's callack_data to any python object. - - Args: - item: Item the callback will be applied to. - user_data: Callback_data to be applied. - - Returns: - None - """ - internal_dpg.configure_item(item, user_data=user_data) - - -def show_item(item: Union[int, str]): - """Shows the item. - - Args: - item: Item to show. - - Returns: - None - """ - internal_dpg.configure_item(item, show=True) - - -def hide_item(item: Union[int, str], *, children_only: bool = False): - """Hides the item. - - Args: - **item: Item to hide. - - Returns: - None - """ - if children_only: - children = get_item_children(item) - for child in children: - internal_dpg.configure_item(child, show=False) - else: - internal_dpg.configure_item(item, show=False) - - -######################################################################################################################## -# Configuration Getter Commands -######################################################################################################################## - -def get_item_label(item: Union[int, str]) -> Union[str, None]: - """Gets the item's label. - - Returns: - label as a string or None - """ - return internal_dpg.get_item_configuration(item)["label"] - - -def get_item_filter_key(item: Union[int, str]) -> Union[str, None]: - """Gets the item's filter key. - - Returns: - filter key as a string or None - """ - return internal_dpg.get_item_configuration(item)["filter_key"] - - -def is_item_tracked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is tracked. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["tracked"] - - -def get_item_indent(item: Union[int, str]) -> Union[int, None]: - """Gets the item's indent. - - Returns: - indent as a int or None - """ - return internal_dpg.get_item_configuration(item)["indent"] - - -def get_item_track_offset(item: Union[int, str]) -> Union[float, None]: - """Gets the item's track offset. - - Returns: - track offset as a int or None - """ - return internal_dpg.get_item_configuration(item)["track_offset"] - - -def get_item_width(item: Union[int, str]) -> Union[int, None]: - """Gets the item's width. - - Returns: - width as a int or None - """ - return internal_dpg.get_item_configuration(item)["width"] - - -def get_item_height(item: Union[int, str]) -> Union[int, None]: - """Gets the item's height. - - Returns: - height as a int or None - """ - return internal_dpg.get_item_configuration(item)["height"] - - -def get_item_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["callback"] - - -def get_item_drag_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drag callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drag_callback"] - - -def get_item_drop_callback(item: Union[int, str]) -> Union[Callable, None]: - """Gets the item's drop callback. - - Returns: - callback as a callable or None - """ - return internal_dpg.get_item_configuration(item)["drop_callback"] - - -def get_item_user_data(item: Union[int, str]) -> Union[Any, None]: - """Gets the item's callback data. - - Returns: - callback data as a python object or None - """ - return internal_dpg.get_item_configuration(item)["user_data"] - - -def get_item_source(item: Union[int, str]) -> Union[str, None]: - """Gets the item's source. - - Returns: - source as a string or None - """ - return internal_dpg.get_item_configuration(item)["source"] - - -######################################################################################################################## -# State Commands -######################################################################################################################## - -def is_item_hovered(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is hovered. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["hovered"] - - -def is_item_active(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is active. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["active"] - - -def is_item_focused(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is focused. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["focused"] - - -def is_item_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["clicked"] - - -def is_item_left_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is left clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["left_clicked"] - - -def is_item_right_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is right clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["right_clicked"] - - -def is_item_middle_clicked(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is middle clicked. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["middle_clicked"] - - -def is_item_visible(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is visible. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["visible"] - - -def is_item_edited(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is edited. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["edited"] - - -def is_item_activated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is activated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["activated"] - - -def is_item_deactivated(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated"] - - -def is_item_deactivated_after_edit(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is deactivated_after_edit. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["deactivated_after_edit"] - - -def is_item_toggled_open(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is toggled_open. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["toggled_open"] - - -def is_item_ok(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is ok and can be used. - - Returns: - status as a bool - """ - return internal_dpg.get_item_state(item)["ok"] - - -def is_item_shown(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is shown. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["show"] - - -def is_item_enabled(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is enabled. - - Returns: - status as a bool - """ - return internal_dpg.get_item_configuration(item)["enabled"] - - -def get_item_pos(item: Union[int, str]) -> List[int]: - """Returns item's position. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["pos"] - - -def get_available_content_region(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["content_region_avail"] - - -def get_item_rect_size(item: Union[int, str]) -> List[int]: - """Returns item's available content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_size"] - - -def get_item_rect_min(item: Union[int, str]) -> List[int]: - """Returns item's minimum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_min"] - - -def get_item_rect_max(item: Union[int, str]) -> List[int]: - """Returns item's maximum content region. - - Returns: - position - """ - return internal_dpg.get_item_state(item)["rect_max"] - - -######################################################################################################################## -# Viewport Setter Commands -######################################################################################################################## - -def set_viewport_clear_color(color: List[int]): - """Sets the viewport's clear color. - - Returns: - None - """ - internal_dpg.configure_viewport(0, clear_color=color) - - -def set_viewport_small_icon(icon: str): - """Sets the viewport's small icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, small_icon=icon) - - -def set_viewport_large_icon(icon: str): - """Sets the viewport's large icon. Must be ico for windows. - - Returns: - None - """ - internal_dpg.configure_viewport(0, large_icon=icon) - - -def set_viewport_pos(pos: List[float]): - """Sets the viewport's position. - - Returns: - None - """ - internal_dpg.configure_viewport(0, x_pos=pos[0], y_pos=pos[1]) - - -def set_viewport_width(width: int): - """Sets the viewport's width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, width=width) - - -def set_viewport_height(height: int): - """Sets the viewport's height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, height=height) - - -def set_viewport_min_width(width: int): - """Sets the viewport's minimum width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_width=width) - - -def set_viewport_max_width(width: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_width=width) - - -def set_viewport_min_height(height: int): - """Sets the viewport's minimum height. - - Returns: - None - """ - internal_dpg.configure_viewport(0, min_height=height) - - -def set_viewport_max_height(height: int): - """Sets the viewport's max width. - - Returns: - None - """ - internal_dpg.configure_viewport(0, max_height=height) - - -def set_viewport_title(title: str): - """Sets the viewport's title. - - Returns: - None - """ - internal_dpg.configure_viewport(0, title=title) - - -def set_viewport_always_top(value: bool): - """Sets the viewport always on top. - - Returns: - None - """ - internal_dpg.configure_viewport(0, always_on_top=value) - - -def set_viewport_resizable(value: bool): - """Sets the viewport resizable. - - Returns: - None - """ - internal_dpg.configure_viewport(0, resizable=value) - -def set_viewport_vsync(value: bool): - """Sets the viewport vsync. - - Returns: - None - """ - internal_dpg.configure_viewport(0, vsync=value) - - -def set_viewport_decorated(value: bool): - """Sets the viewport to be decorated. - - Returns: - None - """ - internal_dpg.configure_viewport(0, decorated=value) - -######################################################################################################################## -# Viewport Getter Commands -######################################################################################################################## - -def get_viewport_clear_color() ->List[int]: - """Gets the viewport's clear color. - - Returns: - List[int] - """ - return internal_dpg.get_viewport_configuration()["clear_color"] - - -def get_viewport_pos() ->List[float]: - """Gets the viewport's position. - - Returns: - viewport position. - """ - config = internal_dpg.get_viewport_configuration() - x_pos = config["x_pos"] - y_pos = config["y_pos"] - return [x_pos, y_pos] - - -def get_viewport_width() -> int: - """Gets the viewport's width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["width"] - - -def get_viewport_client_width() -> int: - """Gets the viewport's client width. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_width"] - - -def get_viewport_client_height() -> int: - """Gets the viewport's client height. - - Returns: - viewport width - """ - return internal_dpg.get_viewport_configuration()["client_height"] - - -def get_viewport_height() -> int: - """Gets the viewport's height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["height"] - - -def get_viewport_min_width() -> int: - """Gets the viewport's minimum width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_width"] - - -def get_viewport_max_width() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_width"] - - -def get_viewport_min_height() -> int: - """Gets the viewport's minimum height. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["min_height"] - - -def get_viewport_max_height() -> int: - """Gets the viewport's max width. - - Returns: - int - """ - return internal_dpg.get_viewport_configuration()["max_height"] - - -def get_viewport_title() -> str: - """Gets the viewport's title. - - Returns: - str - """ - return internal_dpg.get_viewport_configuration()["title"] - - -def is_viewport_always_top() -> bool: - """Checks the viewport always on top flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["always_on_top"] - - -def is_viewport_resizable() -> bool: - """Checks the viewport resizable flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["resizable"] - - -def is_viewport_vsync_on() -> bool: - """Checks the viewport vsync flag. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["vsync"] - - -def is_viewport_decorated() -> bool: - """Checks if the viewport is docorated. - - Returns: - bool - """ - return internal_dpg.get_viewport_configuration()["decorated"] - -########################################################## -# Deprecated Commands -########################################################## - -from typing import Union - - -def deprecated(reason): - - string_types = (type(b''), type(u'')) - - if isinstance(reason, string_types): - - def decorator(func1): - - fmt1 = "Call to deprecated function {name} ({reason})." - - @functools.wraps(func1) - def new_func1(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt1.format(name=func1.__name__, reason=reason), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func1(*args, **kwargs) - - return new_func1 - - return decorator - - elif inspect.isfunction(reason): - - func2 = reason - fmt2 = "Call to deprecated function {name}." - - @functools.wraps(func2) - def new_func2(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) - warnings.warn( - fmt2.format(name=func2.__name__), - category=DeprecationWarning, - stacklevel=2 - ) - warnings.simplefilter('default', DeprecationWarning) - return func2(*args, **kwargs) - - return new_func2 - -@deprecated("Use 'configure_app(init_file=file)'.") -def set_init_file(file="dpg.ini"): - """ deprecated function """ - internal_dpg.configure_app(init_file=file) - -@deprecated("Use 'configure_app(init_file=file, load_init_file=True)'.") -def load_init_file(file): - """ deprecated function """ - internal_dpg.configure_app(init_file=file, load_init_file=True) - -@deprecated("Use: `is_viewport_ok(...)`") -def is_viewport_created(): - """ deprecated function """ - return internal_dpg.is_viewport_ok() - -@deprecated("Use: \ncreate_viewport()\nsetup_dearpygui()\nshow_viewport()") -def setup_viewport(): - """ deprecated function """ - internal_dpg.create_viewport() - internal_dpg.setup_dearpygui() - internal_dpg.show_viewport() - -@deprecated("Use: `bind_item_theme(...)`") -def set_item_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_theme(item, theme) - -@deprecated("Use: `bind_item_type_disabled_theme(...)`") -def set_item_type_disabled_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_disabled_theme(item, theme) - -@deprecated("Use: `bind_item_type_theme(...)`") -def set_item_type_theme(item, theme): - """ deprecated function """ - return internal_dpg.bind_item_type_theme(item, theme) - -@deprecated("Use: `bind_item_font(...)`") -def set_item_font(item, font): - """ deprecated function """ - return internal_dpg.bind_item_font(item, font) - -@deprecated("Use: `add_item_activated_handler(...)`") -def add_activated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_activated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_active_handler(...)`") -def add_active_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_active_handler(parent, **kwargs) - -@deprecated("Use: `add_item_clicked_handler(...)`") -def add_clicked_handler(parent, button=-1, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_clicked_handler(parent, button, **kwargs) - -@deprecated("Use: `add_item_deactived_after_edit_handler(...)`") -def add_deactivated_after_edit_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_after_edit_handler(parent, **kwargs) - -@deprecated("Use: `add_item_deactivated_handler(...)`") -def add_deactivated_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_deactivated_handler(parent, **kwargs) - -@deprecated("Use: `add_item_edited_handler(...)`") -def add_edited_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_edited_handler(parent, **kwargs) - -@deprecated("Use: `add_item_focus_handler(...)`") -def add_focus_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_focus_handler(parent, **kwargs) - -@deprecated("Use: `add_item_hover_handler(...)`") -def add_hover_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_hover_handler(parent, **kwargs) - -@deprecated("Use: `add_item_resize_handler(...)`") -def add_resize_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_resize_handler(parent, **kwargs) - -@deprecated("Use: `add_item_toggled_open_handler(...)`") -def add_toggled_open_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_toggled_open_handler(parent, **kwargs) - -@deprecated("Use: `add_item_visible_handler(...)`") -def add_visible_handler(parent, **kwargs): - """ deprecated function """ - return internal_dpg.add_item_visible_handler(parent, **kwargs) - -@deprecated("Use: `bind_colormap(...)`") -def set_colormap(item, source): - """ deprecated function """ - return internal_dpg.bind_colormap(item, source) - -@deprecated("Use: `bind_theme(0)`") -def reset_default_theme(item, source): - """ deprecated function """ - return internal_dpg.bind_theme(item, source) - -@deprecated -def set_staging_mode(mode): - """ deprecated function """ - pass - -@deprecated -def add_table_next_column(**kwargs): - """ deprecated function """ - pass - -@deprecated("Use: add_stage") -def add_staging_container(**kwargs): - """ deprecated function """ - return internal_dpg.add_stage(**kwargs) - -@deprecated("Use: stage") -@contextmanager -def staging_container(**kwargs): - """ - deprecated function - Args: - **label (str): Overrides 'name' as label. - **user_data (Any): User data for callbacks. - **use_internal_label (bool): Use generated internal label instead of user specified (appends ### uuid). - **id (Union[int, str]): Unique id used to programmatically refer to the item.If label is unused this will be the label. - Yields: - Union[int, str] - """ - try: - warnings.warn("'staging_container' is deprecated and was changed to 'stage'", DeprecationWarning, 2) - widget = internal_dpg.add_stage_container(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: add_spacer(...)") -def add_spacing(**kwargs): - """ (deprecated function) Adds vertical spacing. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - count (int, optional): Number of spacings to add the size is dependant on the curret style. - Returns: - Union[int, str] - """ - - if 'count' in kwargs.keys(): - count = kwargs["count"] - kwargs.pop("count", None) - internal_dpg.add_group(**kwargs) - internal_dpg.push_container_stack(internal_dpg.last_container()) - for i in range(count): - internal_dpg.add_spacer() - result_id = internal_dpg.pop_container_stack() - else: - result_id = internal_dpg.add_spacer(**kwargs) - return result_id - -@deprecated("Use: add_spacer(...)") -def add_dummy(**kwargs): - """ (deprecated function) Adds a spacer or 'dummy' object. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks. - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - Returns: - Union[int, str] - """ - - return internal_dpg.add_spacer(**kwargs) - -@deprecated("Use: `destroy_context()`") -def cleanup_dearpygui(): - """ deprecated function """ - return internal_dpg.destroy_context() - -@deprecated("Use: group(horizontal=True)") -def add_same_line(**kwargs): - """ deprecated function """ - - last_item = internal_dpg.last_item() - group = internal_dpg.add_group(horizontal=True, **kwargs) - internal_dpg.move_item(last_item, parent=group) - internal_dpg.capture_next_item(lambda s: internal_dpg.move_item(s, parent=group)) - return group - -@deprecated("Use: `get_plot_query_rects()`") -def is_plot_queried(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns true if the plot is currently being queried. - - Args: - plot (Union[int, str]): - Returns: - bool - """ - - return len(internal_dpg.get_plot_query_rects(plot, **kwargs)) > 0 - -@deprecated("Use: `get_plot_query_rects()`") -def get_plot_query_area(plot: Union[int, str], **kwargs): - """ (deprecated function) Returns the last/current query area of the plot. If no area is available [0, 0, 0, 0] will be returned. - - Args: - plot (Union[int, str]): - Returns: - Union[List[float], Tuple[float, ...]] - """ - - if rects := internal_dpg.get_plot_query_rects(plot, **kwargs): - return rects[0] - else: - return [0, 0, 0, 0] - -@deprecated("Use: `add_inf_line_series(horizontal=True)`") -def add_hline_series(x, **kwargs): - """ (deprecated function) Adds an infinite horizontal line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs, horizontal=True) - - -@deprecated("Use: `add_inf_line_series()`") -def add_vline_series(x, **kwargs): - """ (deprecated function) Adds an infinite vertical line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - return internal_dpg.add_inf_line_series(x, **kwargs) - - -@deprecated("Use: `add_child_window()`") -def add_child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Returns: - Union[int, str] - """ - - return internal_dpg.add_child_window(**kwargs) - - -@deprecated("Use: `child_window()`") -@contextmanager -def child(**kwargs): - """ (deprecated function) Adds an embedded child window. Will show scrollbars when items do not fit. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - delay_search (bool, optional): Delays searching container for specified items until the end of the app. Possible optimization when a container has many children that are not accessed often. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - Yields: - Union[int, str] - """ - try: - widget = internal_dpg.add_child_window(**kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@deprecated("Use: Just not recommended") -def setup_registries() -> None: - """Adds default registries for fonts, handlers, textures, colormaps, and values.""" - internal_dpg.add_font_registry(tag=internal_dpg.mvReservedUUID_0) - internal_dpg.add_handler_registry(tag=internal_dpg.mvReservedUUID_1) - internal_dpg.add_texture_registry(tag=internal_dpg.mvReservedUUID_2) - internal_dpg.add_value_registry(tag=internal_dpg.mvReservedUUID_3) - internal_dpg.add_colormap_registry(tag=internal_dpg.mvReservedUUID_4) - -@deprecated("Useless and doesn't work anyway") -def is_item_search_delayed(item: Union[int, str]) -> Union[bool, None]: - """Checks if item is search delayed. - - Returns: - tracked as a bool or None - """ - return internal_dpg.get_item_configuration(item)["delay_search"] - -@deprecated("Use: `set_frame_callback()`") -def set_start_callback(callback): - """ deprecated function """ - return internal_dpg.set_frame_callback(3, callback) - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_chars(chars : Union[List[int], Tuple[int, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds specific font characters to a font. - - Args: - chars (Union[List[int], Tuple[int, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range(first_char : int, last_char : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters to a font. - - Args: - first_char (int): - last_char (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -@deprecated("This call is a no-op because character ranges are now automatic") -def add_font_range_hint(hint : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ (deprecated function) Adds a range of font characters (mvFontRangeHint_ constants). - - Args: - hint (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - pass - -########################################################## -# Container Context Managers -########################################################## - - -@contextmanager -def child_window(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, border: bool =True, autosize_x: bool =False, autosize_y: bool =False, no_scrollbar: bool =False, horizontal_scrollbar: bool =False, menubar: bool =False, no_scroll_with_mouse: bool =False, flattened_navigation: bool =True, always_use_window_padding: bool =False, resizable_x: bool =False, resizable_y: bool =False, always_auto_resize: bool =False, frame_style: bool =False, auto_resize_x: bool =False, auto_resize_y: bool =False, **kwargs) -> Union[int, str]: - """ Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - flattened_navigation (bool, optional): Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) - always_use_window_padding (bool, optional): Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) - resizable_x (bool, optional): Allow resize from right border (layout direction). Enable .ini saving. - resizable_y (bool, optional): Allow resize from bottom border (layout direction). - always_auto_resize (bool, optional): Combined with auto_resize_x/auto_resize_y. Always measure size even when child is hidden and always disable clipping optimization! NOT RECOMMENDED. - frame_style (bool, optional): Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - auto_resize_x (bool, optional): Enable auto-resizing width based on child content. Read 'IMPORTANT: Size measurement' details above. - auto_resize_y (bool, optional): Enable auto-resizing height based on child content. Read 'IMPORTANT: Size measurement' details above. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_child_window(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, border=border, autosize_x=autosize_x, autosize_y=autosize_y, no_scrollbar=no_scrollbar, horizontal_scrollbar=horizontal_scrollbar, menubar=menubar, no_scroll_with_mouse=no_scroll_with_mouse, flattened_navigation=flattened_navigation, always_use_window_padding=always_use_window_padding, resizable_x=resizable_x, resizable_y=resizable_y, always_auto_resize=always_auto_resize, frame_style=frame_style, auto_resize_x=auto_resize_x, auto_resize_y=auto_resize_y, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def clipper(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_clipper(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def collapsing_header(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, closable: bool =False, default_open: bool =False, open_on_double_click: bool =False, open_on_arrow: bool =False, leaf: bool =False, bullet: bool =False, **kwargs) -> Union[int, str]: - """ Adds a collapsing header to add items to. Must be closed with the end command. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Adds the ability to hide this widget by pressing the (x) in the top right of widget. - default_open (bool, optional): Sets the collapseable header open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_collapsing_header(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, closable=closable, default_open=default_open, open_on_double_click=open_on_double_click, open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def colormap_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =False, **kwargs) -> Union[int, str]: - """ Adds a colormap registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_colormap_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def custom_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], channel_count : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, y1: Any =[], y2: Any =[], y3: Any =[], tooltip: bool =True, no_fit: bool =False, **kwargs) -> Union[int, str]: - """ Adds a custom series to a plot. New in 1.6. - - Args: - x (Any): - y (Any): - channel_count (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - y1 (Any, optional): - y2 (Any, optional): - y3 (Any, optional): - tooltip (bool, optional): Show tooltip when plot is hovered. - no_fit (bool, optional): the item won't be considered for plot fits - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_custom_series(x, y, channel_count, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, callback=callback, show=show, y1=y1, y2=y2, y3=y3, tooltip=tooltip, no_fit=no_fit, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def drag_payload(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, show: bool =True, drag_data: Any =None, drop_data: Any =None, payload_type: str ='$$DPG_PAYLOAD', **kwargs) -> Union[int, str]: - """ User data payload for drag and drop operations. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - drag_data (Any, optional): Drag data - drop_data (Any, optional): Drop data - payload_type (str, optional): - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_drag_payload(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, show=show, drag_data=drag_data, drop_data=drop_data, payload_type=payload_type, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def draw_layer(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, perspective_divide: bool =False, depth_clipping: bool =False, cull_mode: int =0, **kwargs) -> Union[int, str]: - """ New in 1.1. Creates a layer useful for grouping drawlist items. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - perspective_divide (bool, optional): New in 1.1. apply perspective divide - depth_clipping (bool, optional): New in 1.1. apply depth clipping - cull_mode (int, optional): New in 1.1. culling mode, mvCullMode_* constants. Only works with triangles currently. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_draw_layer(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, perspective_divide=perspective_divide, depth_clipping=depth_clipping, cull_mode=cull_mode, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def draw_node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_draw_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def drawlist(width : int, height : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, **kwargs) -> Union[int, str]: - """ Adds a drawing canvas. - - Args: - width (int): - height (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_drawlist(width, height, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def file_dialog(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, callback: Callable =None, show: bool =True, default_path: str ='', default_filename: str ='.', file_count: int =0, modal: bool =False, directory_selector: bool =False, min_size: Union[List[int], Tuple[int, ...]] =[100, 100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], cancel_callback: Callable =None, **kwargs) -> Union[int, str]: - """ Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_path (str, optional): Path that the file dialog will default to when opened. - default_filename (str, optional): Default name that will show in the file name input. - file_count (int, optional): Number of visible files in the dialog. - modal (bool, optional): Forces user interaction with the file selector. - directory_selector (bool, optional): Shows only directory/paths as options. Allows selection of directory/paths only. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - cancel_callback (Callable, optional): Callback called when cancel button is clicked. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_file_dialog(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, callback=callback, show=show, default_path=default_path, default_filename=default_filename, file_count=file_count, modal=modal, directory_selector=directory_selector, min_size=min_size, max_size=max_size, cancel_callback=cancel_callback, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def filter_set(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc]) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_filter_set(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def font(file : str, size : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, pixel_snapH: bool =False, pixel_snapV: bool =False, parent: Union[int, str] =internal_dpg.mvReservedUUID_0, **kwargs) -> Union[int, str]: - """ Adds font to a font registry. - - Args: - file (str): - size (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - pixel_snapH (bool, optional): Align every glyph to pixel boundary in horizontal direction. Useful if you are rendering text piece-by-piece (e.g. for coloring). - pixel_snapV (bool, optional): Align scaled GlyphOffset.y to pixel boundaries in ImGui. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - default_font (bool, optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'default_font' in kwargs.keys(): - warnings.warn('default_font keyword removed', DeprecationWarning, 2) - kwargs.pop('default_font', None) - widget = internal_dpg.add_font(file, size, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, pixel_snapH=pixel_snapH, pixel_snapV=pixel_snapV, parent=parent, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def font_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a font registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_font_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def group(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, horizontal: bool =False, horizontal_spacing: float =-1, xoffset: float =0.0, **kwargs) -> Union[int, str]: - """ Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. -Enable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - horizontal (bool, optional): Forces child widgets to be added in a horizontal layout. - horizontal_spacing (float, optional): Spacing for the horizontal layout. - xoffset (float, optional): Offset from containing window x item location within group. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_group(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, horizontal=horizontal, horizontal_spacing=horizontal_spacing, xoffset=xoffset, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def handler_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_handler_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def item_handler_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds an item handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_item_handler_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def menu(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, enabled: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, **kwargs) -> Union[int, str]: - """ Adds a menu to an existing menu bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_menu(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, enabled=enabled, filter_key=filter_key, tracked=tracked, track_offset=track_offset, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def menu_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a menu bar to a window. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_menu_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, draggable: bool =True, **kwargs) -> Union[int, str]: - """ Adds a node to a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - draggable (bool, optional): Allow node to be draggable. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, draggable=draggable, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node_attribute(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, attribute_type: int =0, shape: int =1, category: str ='general', **kwargs) -> Union[int, str]: - """ Adds a node attribute to a node. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - attribute_type (int, optional): mvNode_Attr_Input, mvNode_Attr_Output, or mvNode_Attr_Static. - shape (int, optional): Pin shape. - category (str, optional): Category - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_node_attribute(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, attribute_type=attribute_type, shape=shape, category=category, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def node_editor(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, delink_callback: Callable =None, menubar: bool =False, minimap: bool =False, minimap_location: int =2, **kwargs) -> Union[int, str]: - """ Adds a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - delink_callback (Callable, optional): Callback ran when a link is detached. - menubar (bool, optional): Shows or hides the menubar. - minimap (bool, optional): Shows or hides the Minimap. New in 1.6. - minimap_location (int, optional): mvNodeMiniMap_Location_* constants. New in 1.6. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_node_editor(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, parent=parent, before=before, callback=callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, delink_callback=delink_callback, menubar=menubar, minimap=minimap, minimap_location=minimap_location, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def plot(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_title: bool =False, no_menus: bool =False, no_box_select: bool =False, no_mouse_pos: bool =False, query: bool =False, query_color: Union[List[float], Tuple[float, ...]] =(0, 255, 0, 255), min_query_rects: int =1, max_query_rects: int =1, crosshairs: bool =False, equal_aspects: bool =False, no_inputs: bool =False, no_frame: bool =False, use_local_time: bool =False, use_ISO8601: bool =False, use_24hour_clock: bool =False, pan_button: int =internal_dpg.mvMouseButton_Left, pan_mod: int =internal_dpg.mvKey_None, context_menu_button: int =internal_dpg.mvMouseButton_Right, fit_button: int =internal_dpg.mvMouseButton_Left, box_select_button: int =internal_dpg.mvMouseButton_Right, box_select_mod: int =internal_dpg.mvKey_None, box_select_cancel_button: int =internal_dpg.mvMouseButton_Left, query_toggle_mod: int =internal_dpg.mvKey_ModCtrl, horizontal_mod: int =internal_dpg.mvKey_ModAlt, vertical_mod: int =internal_dpg.mvKey_ModShift, override_mod: int =internal_dpg.mvKey_ModCtrl, zoom_mod: int =internal_dpg.mvKey_None, zoom_rate: int =0.1, **kwargs) -> Union[int, str]: - """ Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_title (bool, optional): the plot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_box_select (bool, optional): the user will not be able to box-select with right-click drag - no_mouse_pos (bool, optional): the text of mouse position, in plot coordinates, will not be displayed inside of the plot - query (bool, optional): the user will be able to draw query rects with CTRL + right-click drag - query_color (Union[List[float], Tuple[float, ...]], optional): Color of the query rectangles. - min_query_rects (int, optional): The minimum number of query rects that can be in the plot. If there are less rects than this value, it won't be possible to delete them. - max_query_rects (int, optional): The maximum number of query rects that can be in the plot. If the number is reached any rect added will replace the latest one. (0 means unlimited) - crosshairs (bool, optional): the default mouse cursor will be replaced with a crosshair when hovered - equal_aspects (bool, optional): primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes) - no_inputs (bool, optional): the user will not be able to interact with the plot - no_frame (bool, optional): the ImGui frame will not be rendered - use_local_time (bool, optional): axis labels will be formatted for your timezone when - use_ISO8601 (bool, optional): dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.) - use_24hour_clock (bool, optional): times will be formatted using a 24 hour clock - pan_button (int, optional): mouse button that enables panning when held - pan_mod (int, optional): optional modifier that must be held for panning - context_menu_button (int, optional): opens context menus (if enabled) when clicked - fit_button (int, optional): fits visible data when double clicked - box_select_button (int, optional): begins box selection when pressed and confirms selection when released - box_select_mod (int, optional): begins box selection when pressed and confirms selection when released - box_select_cancel_button (int, optional): cancels active box selection when pressed - query_toggle_mod (int, optional): when held, active box selections turn into queries - horizontal_mod (int, optional): expands active box selection/query horizontally to plot edge when held - vertical_mod (int, optional): expands active box selection/query vertically to plot edge when held - override_mod (int, optional): when held, all input is ignored; used to enable axis/plots as DND sources - zoom_mod (int, optional): optional modifier that must be held for scroll wheel zooming - zoom_rate (int, optional): zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - no_highlight (bool, optional): (deprecated) Removed because not supported from the backend anymore. To control the highlighting of series use the same argument in `add_plot_legend` - no_child (bool, optional): (deprecated) a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications) - anti_aliased (bool, optional): (deprecated) This feature was deprecated in ImPlot. To enable/disable anti_aliasing use `dpg.configure_app()` with the `anti_aliasing` parameters. - query_button (int, optional): (deprecated) This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - query_mod (int, optional): (deprecated) This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - if 'no_highlight' in kwargs.keys(): - warnings.warn('no_highlight keyword removed', DeprecationWarning, 2) - kwargs.pop('no_highlight', None) - - if 'no_child' in kwargs.keys(): - warnings.warn('no_child keyword removed', DeprecationWarning, 2) - kwargs.pop('no_child', None) - - if 'anti_aliased' in kwargs.keys(): - warnings.warn('anti_aliased keyword removed', DeprecationWarning, 2) - kwargs.pop('anti_aliased', None) - - if 'query_button' in kwargs.keys(): - warnings.warn('query_button keyword removed', DeprecationWarning, 2) - kwargs.pop('query_button', None) - - if 'query_mod' in kwargs.keys(): - warnings.warn('query_mod keyword removed', DeprecationWarning, 2) - kwargs.pop('query_mod', None) - widget = internal_dpg.add_plot(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_title=no_title, no_menus=no_menus, no_box_select=no_box_select, no_mouse_pos=no_mouse_pos, query=query, query_color=query_color, min_query_rects=min_query_rects, max_query_rects=max_query_rects, crosshairs=crosshairs, equal_aspects=equal_aspects, no_inputs=no_inputs, no_frame=no_frame, use_local_time=use_local_time, use_ISO8601=use_ISO8601, use_24hour_clock=use_24hour_clock, pan_button=pan_button, pan_mod=pan_mod, context_menu_button=context_menu_button, fit_button=fit_button, box_select_button=box_select_button, box_select_mod=box_select_mod, box_select_cancel_button=box_select_cancel_button, query_toggle_mod=query_toggle_mod, horizontal_mod=horizontal_mod, vertical_mod=vertical_mod, override_mod=override_mod, zoom_mod=zoom_mod, zoom_rate=zoom_rate, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def plot_axis(axis : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, no_label: bool =False, no_gridlines: bool =False, no_tick_marks: bool =False, no_tick_labels: bool =False, no_initial_fit: bool =False, no_menus: bool =False, no_side_switch: bool =False, no_highlight: bool =False, opposite: bool =False, foreground_grid: bool =False, tick_format: str ='', scale: int =internal_dpg.mvPlotScale_Linear, invert: bool =False, auto_fit: bool =False, range_fit: bool =False, pan_stretch: bool =False, lock_min: bool =False, lock_max: bool =False, **kwargs) -> Union[int, str]: - """ Adds an axis to a plot. - - Args: - axis (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - no_label (bool, optional): the axis label will not be displayed - no_gridlines (bool, optional): no grid lines will be displayed - no_tick_marks (bool, optional): no tick marks will be displayed - no_tick_labels (bool, optional): no text labels will be displayed - no_initial_fit (bool, optional): axis will not be initially fit to data extents on the first rendered frame - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_side_switch (bool, optional): the user will not be able to switch the axis side by dragging it - no_highlight (bool, optional): the axis will not have its background highlighted when hovered or held - opposite (bool, optional): axis ticks and labels will be rendered on the conventionally opposite side (i.e, right or top) - foreground_grid (bool, optional): grid lines will be displayed in the foreground (i.e. on top of data) instead of the background - tick_format (str, optional): Sets a custom tick label formatter - scale (int, optional): Sets the axis' scale. Can have only mvPlotScale_ values - invert (bool, optional): the axis values will be inverted (i.e. growing from right to left) - auto_fit (bool, optional): axis will be auto-fitting to data extents - range_fit (bool, optional): axis will only fit points if the point is in the visible range of the **orthogonal** axis - pan_stretch (bool, optional): panning in a locked or constrained state will cause the axis to stretch if possible - lock_min (bool, optional): the axis minimum value will be locked when panning/zooming - lock_max (bool, optional): the axis maximum value will be locked when panning/zooming - id (Union[int, str], optional): (deprecated) - log_scale (bool, optional): (deprecated) Old way to set log scale in the axis. Use 'scale' argument instead. - time (bool, optional): (deprecated) Old way to set time scale in the axis. Use 'scale' argument instead. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'log_scale' in kwargs.keys(): - warnings.warn('log_scale keyword deprecated. See the new scale argument.', DeprecationWarning, 2) - - if 'time' in kwargs.keys(): - warnings.warn('time keyword deprecated. See the new scale argument.', DeprecationWarning, 2) - widget = internal_dpg.add_plot_axis(axis, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, payload_type=payload_type, drop_callback=drop_callback, show=show, no_label=no_label, no_gridlines=no_gridlines, no_tick_marks=no_tick_marks, no_tick_labels=no_tick_labels, no_initial_fit=no_initial_fit, no_menus=no_menus, no_side_switch=no_side_switch, no_highlight=no_highlight, opposite=opposite, foreground_grid=foreground_grid, tick_format=tick_format, scale=scale, invert=invert, auto_fit=auto_fit, range_fit=range_fit, pan_stretch=pan_stretch, lock_min=lock_min, lock_max=lock_max, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def stage(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a stage. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_stage(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def subplots(rows : int, columns : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, row_ratios: Union[List[float], Tuple[float, ...]] =[], column_ratios: Union[List[float], Tuple[float, ...]] =[], no_title: bool =False, no_menus: bool =False, no_resize: bool =False, no_align: bool =False, share_series: bool =False, link_rows: bool =False, link_columns: bool =False, link_all_x: bool =False, link_all_y: bool =False, column_major: bool =False, **kwargs) -> Union[int, str]: - """ Adds a collection of plots. - - Args: - rows (int): - columns (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - row_ratios (Union[List[float], Tuple[float, ...]], optional): - column_ratios (Union[List[float], Tuple[float, ...]], optional): - no_title (bool, optional): the subplot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_resize (bool, optional): resize splitters between subplot cells will be not be provided - no_align (bool, optional): subplot edges will not be aligned vertically or horizontally - share_series (bool, optional): when set to True, series from all sub-plots will be shared to some extent, using a single common color set and showing them in a single legend in the subplots item. Otherwise each plot will be independent from others and will have its own legend - link_rows (bool, optional): link the y-axis limits of all plots in each row (does not apply auxiliary y-axes) - link_columns (bool, optional): link the x-axis limits of all plots in each column - link_all_x (bool, optional): link the x-axis limits in every plot in the subplot - link_all_y (bool, optional): link the y-axis limits in every plot in the subplot (does not apply to auxiliary y-axes) - column_major (bool, optional): subplots are added in column major order instead of the default row major order - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_subplots(rows, columns, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, row_ratios=row_ratios, column_ratios=column_ratios, no_title=no_title, no_menus=no_menus, no_resize=no_resize, no_align=no_align, share_series=share_series, link_rows=link_rows, link_columns=link_columns, link_all_x=link_all_x, link_all_y=link_all_y, column_major=column_major, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def synced_tables(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Links all tables that are immediate children of this container so that they share their state (mostly column sizes). Other children are rendered as is. This is an experimental feature, use with caution. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_synced_tables(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tab(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, closable: bool =False, no_tooltip: bool =False, order_mode: int =0, unsaved_document: bool =False, no_close_with_middle_click: bool =False, no_reorder: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tab to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Creates a button on the tab that can hide the tab. - no_tooltip (bool, optional): Disable tooltip for the given tab. - order_mode (int, optional): set using a constant: mvTabOrder_Reorderable: allows reordering, mvTabOrder_Fixed: fixed ordering, mvTabOrder_Leading: adds tab to front, mvTabOrder_Trailing: adds tab to back - unsaved_document (bool, optional): Display a dot next to the title. - no_close_with_middle_click (bool, optional): Disable closing this tab (if closable==True) by clicking with middle mouse button. - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_tab(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, closable=closable, no_tooltip=no_tooltip, order_mode=order_mode, unsaved_document=unsaved_document, no_close_with_middle_click=no_close_with_middle_click, no_reorder=no_reorder, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tab_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, reorderable: bool =False, tab_list_popup_button: bool =False, no_close_with_middle_click: bool =False, no_scrolling_buttons: bool =False, no_tooltip: bool =False, draw_selected_overline: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - reorderable (bool, optional): Allows for the user to change the order of the tabs. - tab_list_popup_button (bool, optional): Show a button to select active tab from a dropdown list. - no_close_with_middle_click (bool, optional): Disable closing tabs (that have closable=True) by clicking with middle mouse button. - no_scrolling_buttons (bool, optional): Disable left/right scrolling buttons when tab buttons don't fit the container width. - no_tooltip (bool, optional): Disable tooltips when hovering a tab with a long name. - draw_selected_overline (bool, optional): Draw selected overline markers over selected tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_tab_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, reorderable=reorderable, tab_list_popup_button=tab_list_popup_button, no_close_with_middle_click=no_close_with_middle_click, no_scrolling_buttons=no_scrolling_buttons, no_tooltip=no_tooltip, draw_selected_overline=draw_selected_overline, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', header_row: bool =True, clipper: bool =False, inner_width: int =0, policy: int =0, freeze_rows: int =0, freeze_columns: int =0, sort_multi: bool =False, sort_tristate: bool =False, resizable: bool =False, reorderable: bool =False, hideable: bool =False, sortable: bool =False, context_menu_in_body: bool =False, row_background: bool =False, borders_innerH: bool =False, borders_outerH: bool =False, borders_innerV: bool =False, borders_outerV: bool =False, no_host_extendX: bool =False, no_host_extendY: bool =False, no_keep_columns_visible: bool =False, precise_widths: bool =False, no_clip: bool =False, pad_outerX: bool =False, no_pad_outerX: bool =False, no_pad_innerX: bool =False, scrollX: bool =False, scrollY: bool =False, no_saved_settings: bool =False, **kwargs) -> Union[int, str]: - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - header_row (bool, optional): show headers at the top of the columns - clipper (bool, optional): Use clipper (rows must be same height). - inner_width (int, optional): - policy (int, optional): - freeze_rows (int, optional): - freeze_columns (int, optional): - sort_multi (bool, optional): Hold shift when clicking headers to sort on multiple column. - sort_tristate (bool, optional): Allow no sorting, disable default sorting. - resizable (bool, optional): Enable resizing columns - reorderable (bool, optional): Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - hideable (bool, optional): Enable hiding/disabling columns in context menu. - sortable (bool, optional): Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - context_menu_in_body (bool, optional): Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - row_background (bool, optional): Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - borders_innerH (bool, optional): Draw horizontal borders between rows. - borders_outerH (bool, optional): Draw horizontal borders at the top and bottom. - borders_innerV (bool, optional): Draw vertical borders between columns. - borders_outerV (bool, optional): Draw vertical borders on the left and right sides. - no_host_extendX (bool, optional): Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - no_host_extendY (bool, optional): Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - no_keep_columns_visible (bool, optional): Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - precise_widths (bool, optional): Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - no_clip (bool, optional): Disable clipping rectangle for every individual columns. - pad_outerX (bool, optional): Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. - no_pad_outerX (bool, optional): Default if BordersOuterV is off. Disable outer-most padding. - no_pad_innerX (bool, optional): Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - scrollX (bool, optional): Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - scrollY (bool, optional): Enable vertical scrolling. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_table(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, callback=callback, show=show, pos=pos, filter_key=filter_key, header_row=header_row, clipper=clipper, inner_width=inner_width, policy=policy, freeze_rows=freeze_rows, freeze_columns=freeze_columns, sort_multi=sort_multi, sort_tristate=sort_tristate, resizable=resizable, reorderable=reorderable, hideable=hideable, sortable=sortable, context_menu_in_body=context_menu_in_body, row_background=row_background, borders_innerH=borders_innerH, borders_outerH=borders_outerH, borders_innerV=borders_innerV, borders_outerV=borders_outerV, no_host_extendX=no_host_extendX, no_host_extendY=no_host_extendY, no_keep_columns_visible=no_keep_columns_visible, precise_widths=precise_widths, no_clip=no_clip, pad_outerX=pad_outerX, no_pad_outerX=no_pad_outerX, no_pad_innerX=no_pad_innerX, scrollX=scrollX, scrollY=scrollY, no_saved_settings=no_saved_settings, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table_cell(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_table_cell(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, height=height, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def table_row(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Adds a table row. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_table_row(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, height=height, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def template_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a template registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_template_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def texture_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =False, **kwargs) -> Union[int, str]: - """ Adds a dynamic texture. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_texture_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def theme(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a theme. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - default_theme (bool, optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'default_theme' in kwargs.keys(): - warnings.warn('default_theme keyword removed', DeprecationWarning, 2) - kwargs.pop('default_theme', None) - widget = internal_dpg.add_theme(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def theme_component(item_type : int =0, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, enabled_state: bool =True, **kwargs) -> Union[int, str]: - """ Adds a theme component. - - Args: - item_type (int, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - enabled_state (bool, optional): - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_theme_component(item_type, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, enabled_state=enabled_state, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tooltip(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, delay: float =0.0, hide_on_activity: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tooltip window. - - Args: - parent (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - delay (float, optional): Activation delay: time, in seconds, during which the mouse should stay still in order to display the tooltip. May be zero for instant activation. - hide_on_activity (bool, optional): Hide the tooltip if the user has moved the mouse. If False, the tooltip will follow mouse pointer. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_tooltip(parent, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, delay=delay, hide_on_activity=hide_on_activity, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def tree_node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_open: bool =False, open_on_double_click: bool =False, open_on_arrow: bool =False, leaf: bool =False, bullet: bool =False, selectable: bool =False, span_text_width: bool =False, span_full_width: bool =False, catch_nav_left: bool =False, lines: int =internal_dpg.mvTreeLines_None, **kwargs) -> Union[int, str]: - """ Adds a tree node to add items to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_open (bool, optional): Sets the tree node open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - selectable (bool, optional): Makes the tree selectable. - span_text_width (bool, optional): Makes hitbox and highlight only cover the label. - span_full_width (bool, optional): Extend hit box to the left-most and right-most edges (cover the indent area). - catch_nav_left (bool, optional): Keyboard navigation: left arrow within this node's children, if unhandled, moves focus to this node. When setting it to True on a node, better set it on all children nodes in the subtree as well, otherwise it might give unexpected navigation jumps. - lines (int, optional): Experimental. Draw lines connecting tree_node hierarchy. One of dpg.mvTreeLines constants. To work correctly, must be configured the same way in every tree node. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_tree_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_open=default_open, open_on_double_click=open_on_double_click, open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet, selectable=selectable, span_text_width=span_text_width, span_full_width=span_full_width, catch_nav_left=catch_nav_left, lines=lines, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def value_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a value registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - widget = internal_dpg.add_value_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def viewport_drawlist(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, filter_key: str ='', front: bool =True, **kwargs) -> Union[int, str]: - """ A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - front (bool, optional): Draws to the front of the view port instead of the back. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_viewport_drawlist(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, filter_key=filter_key, front=front, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def viewport_menu_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a menubar to the viewport. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_viewport_menu_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, show=show, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -@contextmanager -def window(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], min_size: Union[List[int], Tuple[int, ...]] =[100, 100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], menubar: bool =False, collapsed: bool =False, autosize: bool =False, no_resize: bool =False, unsaved_document: bool =False, no_title_bar: bool =False, no_move: bool =False, no_scrollbar: bool =False, no_collapse: bool =False, horizontal_scrollbar: bool =False, no_focus_on_appearing: bool =False, no_bring_to_front_on_focus: bool =False, no_close: bool =False, no_background: bool =False, modal: bool =False, popup: bool =False, no_saved_settings: bool =False, no_open_over_existing_popup: bool =True, no_scroll_with_mouse: bool =False, no_docking: bool =False, copy_contents_shortcut: bool =False, on_close: Callable =None, **kwargs) -> Union[int, str]: - """ Creates a new window for following items to be added to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - menubar (bool, optional): Shows or hides the menubar. - collapsed (bool, optional): Collapse the window. - autosize (bool, optional): Autosized the window to fit it's items. - no_resize (bool, optional): Allows for the window size to be changed or fixed. - unsaved_document (bool, optional): Show a special marker if the document is not saved. - no_title_bar (bool, optional): Title name for the title bar of the window. - no_move (bool, optional): Allows for the window's position to be changed or fixed. - no_scrollbar (bool, optional): Disable scrollbars. (window can still scroll with mouse or programmatically) - no_collapse (bool, optional): Disable user collapsing window by double-clicking on it. - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear. (off by default) - no_focus_on_appearing (bool, optional): Disable taking focus when transitioning from hidden to visible state. - no_bring_to_front_on_focus (bool, optional): Disable bringing window to front when taking focus. (e.g. clicking on it or programmatically giving it focus) - no_close (bool, optional): Disable user closing the window by removing the close button. - no_background (bool, optional): Sets Background and border alpha to transparent. - modal (bool, optional): Fills area behind window according to the theme and disables user ability to interact with anything except the window. - popup (bool, optional): Fills area behind window according to the theme, removes title bar, collapse and close. Window can be closed by selecting area in the background behind the window. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - no_open_over_existing_popup (bool, optional): Don't open if there's already a popup - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - no_docking (bool, optional): Disable docking of this window - copy_contents_shortcut (bool, optional): Experimental. If True, window contents can be copied to clipboard by pressing Ctrl+C. Might be useful for message boxes. - on_close (Callable, optional): Callback ran when window is closed. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Yields: - Union[int, str] - """ - try: - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - widget = internal_dpg.add_window(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, show=show, pos=pos, min_size=min_size, max_size=max_size, menubar=menubar, collapsed=collapsed, autosize=autosize, no_resize=no_resize, unsaved_document=unsaved_document, no_title_bar=no_title_bar, no_move=no_move, no_scrollbar=no_scrollbar, no_collapse=no_collapse, horizontal_scrollbar=horizontal_scrollbar, no_focus_on_appearing=no_focus_on_appearing, no_bring_to_front_on_focus=no_bring_to_front_on_focus, no_close=no_close, no_background=no_background, modal=modal, popup=popup, no_saved_settings=no_saved_settings, no_open_over_existing_popup=no_open_over_existing_popup, no_scroll_with_mouse=no_scroll_with_mouse, no_docking=no_docking, copy_contents_shortcut=copy_contents_shortcut, on_close=on_close, **kwargs) - internal_dpg.push_container_stack(widget) - yield widget - finally: - internal_dpg.pop_container_stack() - -########################################################## -# Core Wrappings -########################################################## - -def add_2d_histogram_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, xbins: int =-1, ybins: int =-1, xmin_range: float =0.0, xmax_range: float =0.0, ymin_range: float =0.0, ymax_range: float =0.0, density: bool =False, outliers: bool =False, col_major: bool =False, **kwargs) -> Union[int, str]: - """ Adds a 2d histogram series. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - xbins (int, optional): - ybins (int, optional): - xmin_range (float, optional): set the min x range value, the values under this min will be ignored - xmax_range (float, optional): set the max x range value, the values over this max will be ignored - ymin_range (float, optional): set the min y range value, the values under this min will be ignored - ymax_range (float, optional): set the max y range value, the values over this max will be ignored. If all xmin, xmax, ymin and ymax are 0.0, then the values will be the min and max values of the series - density (bool, optional): counts will be normalized, i.e. the PDF will be visualized - outliers (bool, optional): exclude values outside the specified histogram range from the count used for normalizing - col_major (bool, optional): data will be read in column major order - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_2d_histogram_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, xbins=xbins, ybins=ybins, xmin_range=xmin_range, xmax_range=xmax_range, ymin_range=ymin_range, ymax_range=ymax_range, density=density, outliers=outliers, col_major=col_major, **kwargs) - -def add_3d_slider(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), max_x: float =100.0, max_y: float =100.0, max_z: float =100.0, min_x: float =0.0, min_y: float =0.0, min_z: float =0.0, scale: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a 3D box slider. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - max_x (float, optional): Applies upper limit to slider. - max_y (float, optional): Applies upper limit to slider. - max_z (float, optional): Applies upper limit to slider. - min_x (float, optional): Applies lower limit to slider. - min_y (float, optional): Applies lower limit to slider. - min_z (float, optional): Applies lower limit to slider. - scale (float, optional): Size of the widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_3d_slider(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, max_x=max_x, max_y=max_y, max_z=max_z, min_x=min_x, min_y=min_y, min_z=min_z, scale=scale, **kwargs) - -def add_alias(alias : str, item : Union[int, str], **kwargs) -> None: - """ Adds an alias. - - Args: - alias (str): - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.add_alias(alias, item, **kwargs) - -def add_area_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), contribute_to_bounds: bool =True, **kwargs) -> Union[int, str]: - """ Adds an area series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - fill (Union[List[int], Tuple[int, ...]], optional): - contribute_to_bounds (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_area_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, fill=fill, contribute_to_bounds=contribute_to_bounds, **kwargs) - -def add_axis_tag(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, default_value: float =0.0, color: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), auto_rounding: bool =False, **kwargs) -> Union[int, str]: - """ Adds custom labels to axes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - default_value (float, optional): - color (Union[List[int], Tuple[int, ...]], optional): - auto_rounding (bool, optional): When enabled, the value displayed on the tag will be automatically rounded to the precision of other values displayed at axis' ticks. Only makes sense when label is not set, i.e. when the tag displays its location on the axis. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_axis_tag(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, default_value=default_value, color=color, auto_rounding=auto_rounding, **kwargs) - -def add_bar_group_series(values : Union[List[float], Tuple[float, ...]], label_ids : Union[List[str], Tuple[str, ...]], group_size : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, group_width: float =0.67, shift: int =0, horizontal: bool =False, stacked: bool =False, **kwargs) -> Union[int, str]: - """ Adds a bar groups series to a plot. - - Args: - values (Any): - label_ids (Union[List[str], Tuple[str, ...]]): Label of each bar in a group - group_size (int): Number of bars in a group - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - group_width (float, optional): Size of bar groups - shift (int, optional): The position on the x axis where to start plotting bar groups - horizontal (bool, optional): bar groups will be rendered horizontally on the current y-axis - stacked (bool, optional): items in a group will be stacked on top of each other - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_bar_group_series(values, label_ids, group_size, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, group_width=group_width, shift=shift, horizontal=horizontal, stacked=stacked, **kwargs) - -def add_bar_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, weight: float =1.0, horizontal: bool =False, **kwargs) -> Union[int, str]: - """ Adds a bar series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - weight (float, optional): - horizontal (bool, optional): bars will be rendered horizontally on the current y-axis - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_bar_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, weight=weight, horizontal=horizontal, **kwargs) - -def add_bool_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: bool =False, parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a bool value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (bool, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_bool_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_button(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, small: bool =False, arrow: bool =False, direction: int =0, repeat: bool =False, **kwargs) -> Union[int, str]: - """ Adds a button. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - small (bool, optional): Shrinks the size of the button to the text of the label it contains. Useful for embedding in text. - arrow (bool, optional): Displays an arrow in place of the text string. This requires the direction keyword. - direction (int, optional): Sets the cardinal direction for the arrow by using constants mvDir_Left, mvDir_Up, mvDir_Down, mvDir_Right, mvDir_None. Arrow keyword must be set to True. - repeat (bool, optional): Hold to continuosly repeat the click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_button(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, small=small, arrow=arrow, direction=direction, repeat=repeat, **kwargs) - -def add_candle_series(dates : Union[List[float], Tuple[float, ...]], opens : Union[List[float], Tuple[float, ...]], closes : Union[List[float], Tuple[float, ...]], lows : Union[List[float], Tuple[float, ...]], highs : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, bull_color: Union[List[int], Tuple[int, ...]] =(0, 255, 113, 255), bear_color: Union[List[int], Tuple[int, ...]] =(218, 13, 79, 255), weight: float =0.25, tooltip: bool =True, time_unit: int =5, **kwargs) -> Union[int, str]: - """ Adds a candle series to a plot. - - Args: - dates (Any): - opens (Any): - closes (Any): - lows (Any): - highs (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - bull_color (Union[List[int], Tuple[int, ...]], optional): - bear_color (Union[List[int], Tuple[int, ...]], optional): - weight (float, optional): - tooltip (bool, optional): - time_unit (int, optional): mvTimeUnit_* constants. Default mvTimeUnit_Day. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_candle_series(dates, opens, closes, lows, highs, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, bull_color=bull_color, bear_color=bear_color, weight=weight, tooltip=tooltip, time_unit=time_unit, **kwargs) - -def add_char_remap(source : int, target : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Remaps a character. - - Args: - source (int): - target (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_char_remap(source, target, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, **kwargs) - -def add_checkbox(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds a checkbox. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): Sets the default value of the checkmark - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_checkbox(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, **kwargs) - -def add_child_window(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, border: bool =True, autosize_x: bool =False, autosize_y: bool =False, no_scrollbar: bool =False, horizontal_scrollbar: bool =False, menubar: bool =False, no_scroll_with_mouse: bool =False, flattened_navigation: bool =True, always_use_window_padding: bool =False, resizable_x: bool =False, resizable_y: bool =False, always_auto_resize: bool =False, frame_style: bool =False, auto_resize_x: bool =False, auto_resize_y: bool =False, **kwargs) -> Union[int, str]: - """ Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - border (bool, optional): Shows/Hides the border around the sides. - autosize_x (bool, optional): Autosize the window to its parents size in x. - autosize_y (bool, optional): Autosize the window to its parents size in y. - no_scrollbar (bool, optional): Disable scrollbars (window can still scroll with mouse or programmatically). - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear (off by default). - menubar (bool, optional): Shows/Hides the menubar at the top. - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - flattened_navigation (bool, optional): Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) - always_use_window_padding (bool, optional): Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) - resizable_x (bool, optional): Allow resize from right border (layout direction). Enable .ini saving. - resizable_y (bool, optional): Allow resize from bottom border (layout direction). - always_auto_resize (bool, optional): Combined with auto_resize_x/auto_resize_y. Always measure size even when child is hidden and always disable clipping optimization! NOT RECOMMENDED. - frame_style (bool, optional): Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - auto_resize_x (bool, optional): Enable auto-resizing width based on child content. Read 'IMPORTANT: Size measurement' details above. - auto_resize_y (bool, optional): Enable auto-resizing height based on child content. Read 'IMPORTANT: Size measurement' details above. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_child_window(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, border=border, autosize_x=autosize_x, autosize_y=autosize_y, no_scrollbar=no_scrollbar, horizontal_scrollbar=horizontal_scrollbar, menubar=menubar, no_scroll_with_mouse=no_scroll_with_mouse, flattened_navigation=flattened_navigation, always_use_window_padding=always_use_window_padding, resizable_x=resizable_x, resizable_y=resizable_y, always_auto_resize=always_auto_resize, frame_style=frame_style, auto_resize_x=auto_resize_x, auto_resize_y=auto_resize_y, **kwargs) - -def add_clipper(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_clipper(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, show=show, **kwargs) - -def add_collapsing_header(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, closable: bool =False, default_open: bool =False, open_on_double_click: bool =False, open_on_arrow: bool =False, leaf: bool =False, bullet: bool =False, **kwargs) -> Union[int, str]: - """ Adds a collapsing header to add items to. Must be closed with the end command. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Adds the ability to hide this widget by pressing the (x) in the top right of widget. - default_open (bool, optional): Sets the collapseable header open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_collapsing_header(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, closable=closable, default_open=default_open, open_on_double_click=open_on_double_click, open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet, **kwargs) - -def add_color_button(default_value : Union[List[int], Tuple[int, ...]] =(0, 0, 0, 255), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_alpha: bool =False, no_border: bool =False, no_drag_drop: bool =False, alpha_preview: int =internal_dpg.mvColorEdit_AlphaPreviewNone, no_tooltip: bool =False, **kwargs) -> Union[int, str]: - """ Adds a color button. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_border (bool, optional): Disable border around the image. - no_drag_drop (bool, optional): Disable ability to drag and drop small preview (color square) to apply colors to other items. - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - no_tooltip (bool, optional): Disable tooltip when hovering the button. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_color_button(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_alpha=no_alpha, no_border=no_border, no_drag_drop=no_drag_drop, alpha_preview=alpha_preview, no_tooltip=no_tooltip, **kwargs) - -def add_color_edit(default_value : Union[List[int], Tuple[int, ...]] =(0, 0, 0, 255), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_alpha: bool =False, no_picker: bool =False, no_options: bool =False, no_small_preview: bool =False, no_inputs: bool =False, no_tooltip: bool =False, no_label: bool =False, no_drag_drop: bool =False, alpha_bar: bool =False, alpha_preview: int =internal_dpg.mvColorEdit_AlphaPreviewNone, display_mode: int =internal_dpg.mvColorEdit_rgb, display_type: int =internal_dpg.mvColorEdit_uint8, input_mode: int =internal_dpg.mvColorEdit_input_rgb, **kwargs) -> Union[int, str]: - """ Adds an RGBA color editor. Left clicking the small color preview will provide a color picker. Click and draging the small color preview will copy the color to be applied on any other color widget. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_picker (bool, optional): Disable picker popup when color square is clicked. - no_options (bool, optional): Disable toggling options menu when right-clicking on inputs/small preview. - no_small_preview (bool, optional): Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown. - no_inputs (bool, optional): Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square) - no_tooltip (bool, optional): Disable tooltip when hovering the preview. - no_label (bool, optional): Disable display of inline text label. - no_drag_drop (bool, optional): Disable ability to drag and drop small preview (color square) to apply colors to other items. - alpha_bar (bool, optional): Show vertical alpha bar/gradient in picker. - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - display_mode (int, optional): mvColorEdit_rgb, mvColorEdit_hsv, or mvColorEdit_hex - display_type (int, optional): mvColorEdit_uint8 or mvColorEdit_float - input_mode (int, optional): mvColorEdit_input_* values - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_color_edit(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_alpha=no_alpha, no_picker=no_picker, no_options=no_options, no_small_preview=no_small_preview, no_inputs=no_inputs, no_tooltip=no_tooltip, no_label=no_label, no_drag_drop=no_drag_drop, alpha_bar=alpha_bar, alpha_preview=alpha_preview, display_mode=display_mode, display_type=display_type, input_mode=input_mode, **kwargs) - -def add_color_picker(default_value : Union[List[int], Tuple[int, ...]] =(0, 0, 0, 255), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_alpha: bool =False, no_side_preview: bool =False, no_small_preview: bool =False, no_inputs: bool =False, no_tooltip: bool =False, no_label: bool =False, alpha_bar: bool =False, display_rgb: bool =False, display_hsv: bool =False, display_hex: bool =False, picker_mode: int =internal_dpg.mvColorPicker_bar, alpha_preview: int =internal_dpg.mvColorEdit_AlphaPreviewNone, display_type: int =internal_dpg.mvColorEdit_uint8, input_mode: int =internal_dpg.mvColorEdit_input_rgb, **kwargs) -> Union[int, str]: - """ Adds an RGB color picker. Right click the color picker for options. Click and drag the color preview to copy the color and drop on any other color widget to apply. Right Click allows the style of the color picker to be changed. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_alpha (bool, optional): Removes the displayed slider that can change alpha channel. - no_side_preview (bool, optional): Disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden. - no_small_preview (bool, optional): Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown. - no_inputs (bool, optional): Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square) - no_tooltip (bool, optional): Disable tooltip when hovering the preview. - no_label (bool, optional): Disable display of inline text label. - alpha_bar (bool, optional): Show vertical alpha bar/gradient in picker. - display_rgb (bool, optional): Override _display_ type among RGB/HSV/Hex. - display_hsv (bool, optional): Override _display_ type among RGB/HSV/Hex. - display_hex (bool, optional): Override _display_ type among RGB/HSV/Hex. - picker_mode (int, optional): mvColorPicker_bar or mvColorPicker_wheel - alpha_preview (int, optional): mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf - display_type (int, optional): mvColorEdit_uint8 or mvColorEdit_float - input_mode (int, optional): mvColorEdit_input_* values. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_color_picker(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_alpha=no_alpha, no_side_preview=no_side_preview, no_small_preview=no_small_preview, no_inputs=no_inputs, no_tooltip=no_tooltip, no_label=no_label, alpha_bar=alpha_bar, display_rgb=display_rgb, display_hsv=display_hsv, display_hex=display_hex, picker_mode=picker_mode, alpha_preview=alpha_preview, display_type=display_type, input_mode=input_mode, **kwargs) - -def add_color_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a color value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_color_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_colormap(colors : List[Union[List[int], Tuple[int, ...]]], qualitative : bool, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_4, **kwargs) -> Union[int, str]: - """ Adds a legend that pairs colors with normalized value 0.0->1.0. Each color will be This is typically used with a heat series. (ex. [[0, 0, 0, 255], [255, 255, 255, 255]] will be mapped to a soft transition from 0.0-1.0) - - Args: - colors (Any): colors that will be mapped to the normalized value 0.0->1.0 - qualitative (bool): Qualitative will create hard transitions for color boundries across the value range when enabled. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_colormap(colors, qualitative, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, parent=parent, **kwargs) - -def add_colormap_button(default_value : Union[List[int], Tuple[int, ...]] =(0, 0, 0, 255), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, **kwargs) -> Union[int, str]: - """ Adds a button that a color map can be bound to. - - Args: - default_value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_colormap_button(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, **kwargs) - -def add_colormap_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =False, **kwargs) -> Union[int, str]: - """ Adds a colormap registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_colormap_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - -def add_colormap_scale(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], colormap: Union[int, str] =0, min_scale: float =0.0, max_scale: float =1.0, format: str ='%g', reverse_dir: bool =False, mirror: bool =False, **kwargs) -> Union[int, str]: - """ Adds a legend that pairs values with colors. This is typically used with a heat series. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - colormap (Union[int, str], optional): mvPlotColormap_* constants or mvColorMap uuid from a color map registry - min_scale (float, optional): Sets the min number of the color scale. Typically is the same as the min scale from the heat series. - max_scale (float, optional): Sets the max number of the color scale. Typically is the same as the max scale from the heat series. - format (str, optional): Formatting used for the labels. - reverse_dir (bool, optional): invert the colormap bar and axis scale (this only affects rendering; if you only want to reverse the scale mapping, make scale_min > scale_max) - mirror (bool, optional): render the colormap label and tick labels on the opposite side - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'drag_callback' in kwargs.keys(): - - warnings.warn('drag_callback keyword removed', DeprecationWarning, 2) - - kwargs.pop('drag_callback', None) - - return internal_dpg.add_colormap_scale(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drop_callback=drop_callback, show=show, pos=pos, colormap=colormap, min_scale=min_scale, max_scale=max_scale, format=format, reverse_dir=reverse_dir, mirror=mirror, **kwargs) - -def add_colormap_slider(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, **kwargs) -> Union[int, str]: - """ Adds a color slider that a color map can be bound to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'drag_callback' in kwargs.keys(): - - warnings.warn('drag_callback keyword removed', DeprecationWarning, 2) - - kwargs.pop('drag_callback', None) - - return internal_dpg.add_colormap_slider(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, **kwargs) - -def add_combo(items : Union[List[str], Tuple[str, ...]] =(), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: str ='', popup_align_left: bool =False, no_arrow_button: bool =False, no_preview: bool =False, fit_width: bool =False, height_mode: int =1, **kwargs) -> Union[int, str]: - """ Adds a combo dropdown that allows a user to select a single option from a drop down window. All items will be shown as selectables on the dropdown. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown in the drop down window. Can consist of any combination of types but will convert all items to strings to be shown. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): Sets a selected item from the drop down by specifying the string value. - popup_align_left (bool, optional): Align the contents on the popup toward the left. - no_arrow_button (bool, optional): Display the preview box without the square arrow button indicating dropdown activity. - no_preview (bool, optional): Display only the square arrow button and not the selected value. - fit_width (bool, optional): Fit the available width. - height_mode (int, optional): Controlls the number of items shown in the dropdown by the constants mvComboHeight_Small, mvComboHeight_Regular, mvComboHeight_Large, mvComboHeight_Largest - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_combo(items, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, popup_align_left=popup_align_left, no_arrow_button=no_arrow_button, no_preview=no_preview, fit_width=fit_width, height_mode=height_mode, **kwargs) - -def add_custom_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], channel_count : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, y1: Any =[], y2: Any =[], y3: Any =[], tooltip: bool =True, no_fit: bool =False, **kwargs) -> Union[int, str]: - """ Adds a custom series to a plot. New in 1.6. - - Args: - x (Any): - y (Any): - channel_count (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - y1 (Any, optional): - y2 (Any, optional): - y3 (Any, optional): - tooltip (bool, optional): Show tooltip when plot is hovered. - no_fit (bool, optional): the item won't be considered for plot fits - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_custom_series(x, y, channel_count, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, callback=callback, show=show, y1=y1, y2=y2, y3=y3, tooltip=tooltip, no_fit=no_fit, **kwargs) - -def add_date_picker(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: dict ={'month_day': 14, 'year':20, 'month':5}, level: int =0, **kwargs) -> Union[int, str]: - """ Adds a date picker. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (dict, optional): - level (int, optional): Use avaliable constants. mvDatePickerLevel_Day, mvDatePickerLevel_Month, mvDatePickerLevel_Year - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_date_picker(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, level=level, **kwargs) - -def add_digital_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a digital series to a plot. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_digital_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, **kwargs) - -def add_double4_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Any =(0.0, 0.0, 0.0, 0.0), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a double value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Any, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_double4_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_double_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: float =0.0, parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a double value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (float, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_double_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_drag_double(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, format: str ='%0.3f', speed: float =1.0, min_value: float =0.0, max_value: float =100.0, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag for a single double value. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_double(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_doublex(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Any =(0.0, 0.0, 0.0, 0.0), size: int =4, format: str ='%0.3f', speed: float =1.0, min_value: float =0.0, max_value: float =100.0, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag input for a set of double values up to 4. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - size (int, optional): Number of doubles to be displayed. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_doublex(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_float(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, format: str ='%0.3f', speed: float =1.0, min_value: float =0.0, max_value: float =100.0, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_float(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_floatx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), size: int =4, format: str ='%0.3f', speed: float =1.0, min_value: float =0.0, max_value: float =100.0, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag input for a set of float values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - size (int, optional): Number of floats to be displayed. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (float, optional): Applies a limit only to draging entry only. - max_value (float, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_floatx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_int(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: int =0, format: str ='%d', speed: float =1.0, min_value: int =0, max_value: int =100, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (int, optional): Applies a limit only to draging entry only. - max_value (int, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_int(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_intx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[int], Tuple[int, ...]] =(0, 0, 0, 0), size: int =4, format: str ='%d', speed: float =1.0, min_value: int =0, max_value: int =100, no_input: bool =False, clamped: bool =False, **kwargs) -> Union[int, str]: - """ Adds drag input for a set of int values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - size (int, optional): Number of ints to be displayed. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - speed (float, optional): Sets the sensitivity the float will be modified while dragging. - min_value (int, optional): Applies a limit only to draging entry only. - max_value (int, optional): Applies a limit only to draging entry only. - no_input (bool, optional): Disable direct entry methods or Enter key allowing to input text directly into the widget. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_intx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, format=format, speed=speed, min_value=min_value, max_value=max_value, no_input=no_input, clamped=clamped, **kwargs) - -def add_drag_line(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, default_value: float =0.0, color: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, show_label: bool =True, vertical: bool =True, delayed: bool =False, no_cursor: bool =False, no_fit: bool =False, no_inputs: bool =False, **kwargs) -> Union[int, str]: - """ Adds a drag line to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (float, optional): - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - show_label (bool, optional): - vertical (bool, optional): - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_line(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, callback=callback, show=show, default_value=default_value, color=color, thickness=thickness, show_label=show_label, vertical=vertical, delayed=delayed, no_cursor=no_cursor, no_fit=no_fit, no_inputs=no_inputs, **kwargs) - -def add_drag_payload(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, show: bool =True, drag_data: Any =None, drop_data: Any =None, payload_type: str ='$$DPG_PAYLOAD', **kwargs) -> Union[int, str]: - """ User data payload for drag and drop operations. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - drag_data (Any, optional): Drag data - drop_data (Any, optional): Drop data - payload_type (str, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_payload(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, show=show, drag_data=drag_data, drop_data=drop_data, payload_type=payload_type, **kwargs) - -def add_drag_point(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, default_value: Any =(0.0, 0.0), color: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, show_label: bool =True, offset: Union[List[float], Tuple[float, ...]] =(16.0, 8.0), clamped: bool =True, delayed: bool =False, no_cursor: bool =False, no_fit: bool =False, no_inputs: bool =False, **kwargs) -> Union[int, str]: - """ Adds a drag point to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - show_label (bool, optional): - offset (Union[List[float], Tuple[float, ...]], optional): Offset of the label, in pixels, relative to the drag point itself - clamped (bool, optional): Keep the label within the visible area of the plot even if the drag point itself goes outside of the visible area - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_point(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, callback=callback, show=show, default_value=default_value, color=color, thickness=thickness, show_label=show_label, offset=offset, clamped=clamped, delayed=delayed, no_cursor=no_cursor, no_fit=no_fit, no_inputs=no_inputs, **kwargs) - -def add_drag_rect(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, default_value: Any =(0.0, 0.0, 0.0, 0.0), color: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), delayed: bool =False, no_cursor: bool =False, no_fit: bool =False, no_inputs: bool =False, **kwargs) -> Union[int, str]: - """ Adds a drag rectangle to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): The coordinates are specified in a sequence of: (xmin, ymin, xmax, ymax) - color (Union[List[int], Tuple[int, ...]], optional): - delayed (bool, optional): tool rendering will be delayed one frame; useful when applying position-constraints - no_cursor (bool, optional): drag tools won't change cursor icons when hovered or held - no_fit (bool, optional): the drag tool won't be considered for plot fits - no_inputs (bool, optional): lock the tool from user inputs - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_drag_rect(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, callback=callback, show=show, default_value=default_value, color=color, delayed=delayed, no_cursor=no_cursor, no_fit=no_fit, no_inputs=no_inputs, **kwargs) - -def add_draw_layer(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, perspective_divide: bool =False, depth_clipping: bool =False, cull_mode: int =0, **kwargs) -> Union[int, str]: - """ New in 1.1. Creates a layer useful for grouping drawlist items. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - perspective_divide (bool, optional): New in 1.1. apply perspective divide - depth_clipping (bool, optional): New in 1.1. apply depth clipping - cull_mode (int, optional): New in 1.1. culling mode, mvCullMode_* constants. Only works with triangles currently. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_draw_layer(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, perspective_divide=perspective_divide, depth_clipping=depth_clipping, cull_mode=cull_mode, **kwargs) - -def add_draw_node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_draw_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, **kwargs) - -def add_drawlist(width : int, height : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, **kwargs) -> Union[int, str]: - """ Adds a drawing canvas. - - Args: - width (int): - height (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_drawlist(width, height, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, **kwargs) - -def add_dynamic_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =internal_dpg.mvReservedUUID_2, **kwargs) -> Union[int, str]: - """ Adds a dynamic texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_dynamic_texture(width, height, default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, **kwargs) - -def add_error_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], negative : Union[List[float], Tuple[float, ...]], positive : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, contribute_to_bounds: bool =True, horizontal: bool =False, **kwargs) -> Union[int, str]: - """ Adds an error series to a plot. - - Args: - x (Any): - y (Any): - negative (Any): - positive (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - contribute_to_bounds (bool, optional): - horizontal (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_error_series(x, y, negative, positive, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, contribute_to_bounds=contribute_to_bounds, horizontal=horizontal, **kwargs) - -def add_file_dialog(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, callback: Callable =None, show: bool =True, default_path: str ='', default_filename: str ='.', file_count: int =0, modal: bool =False, directory_selector: bool =False, min_size: Union[List[int], Tuple[int, ...]] =[100, 100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], cancel_callback: Callable =None, **kwargs) -> Union[int, str]: - """ Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - default_path (str, optional): Path that the file dialog will default to when opened. - default_filename (str, optional): Default name that will show in the file name input. - file_count (int, optional): Number of visible files in the dialog. - modal (bool, optional): Forces user interaction with the file selector. - directory_selector (bool, optional): Shows only directory/paths as options. Allows selection of directory/paths only. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - cancel_callback (Callable, optional): Callback called when cancel button is clicked. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_file_dialog(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, callback=callback, show=show, default_path=default_path, default_filename=default_filename, file_count=file_count, modal=modal, directory_selector=directory_selector, min_size=min_size, max_size=max_size, cancel_callback=cancel_callback, **kwargs) - -def add_file_extension(extension : str, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, custom_text: str ='', color: Union[List[int], Tuple[int, ...]] =(-255, 0, 0, 255), **kwargs) -> Union[int, str]: - """ Creates a file extension filter option in the file dialog. - - Args: - extension (str): Extension that will show as an when the parent is a file dialog. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - custom_text (str, optional): Replaces the displayed text in the drop down for this extension. - color (Union[List[int], Tuple[int, ...]], optional): Color for the text that will be shown with specified extensions. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_file_extension(extension, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, parent=parent, before=before, custom_text=custom_text, color=color, **kwargs) - -def add_filter_set(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc]) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_filter_set(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, show=show, **kwargs) - -def add_float4_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a float4 value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_float4_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_float_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: float =0.0, parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a float value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (float, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_float_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_float_vect_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Union[List[float], Tuple[float, ...]] =(), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a float vect value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[float], Tuple[float, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_float_vect_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_font(file : str, size : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, pixel_snapH: bool =False, pixel_snapV: bool =False, parent: Union[int, str] =internal_dpg.mvReservedUUID_0, **kwargs) -> Union[int, str]: - """ Adds font to a font registry. - - Args: - file (str): - size (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - pixel_snapH (bool, optional): Align every glyph to pixel boundary in horizontal direction. Useful if you are rendering text piece-by-piece (e.g. for coloring). - pixel_snapV (bool, optional): Align scaled GlyphOffset.y to pixel boundaries in ImGui. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - default_font (bool, optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'default_font' in kwargs.keys(): - - warnings.warn('default_font keyword removed', DeprecationWarning, 2) - - kwargs.pop('default_font', None) - - return internal_dpg.add_font(file, size, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, pixel_snapH=pixel_snapH, pixel_snapV=pixel_snapV, parent=parent, **kwargs) - -def add_font_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a font registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_font_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - -def add_group(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, horizontal: bool =False, horizontal_spacing: float =-1, xoffset: float =0.0, **kwargs) -> Union[int, str]: - """ Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members. -Enable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.) - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - horizontal (bool, optional): Forces child widgets to be added in a horizontal layout. - horizontal_spacing (float, optional): Spacing for the horizontal layout. - xoffset (float, optional): Offset from containing window x item location within group. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_group(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, horizontal=horizontal, horizontal_spacing=horizontal_spacing, xoffset=xoffset, **kwargs) - -def add_handler_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_handler_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - -def add_heat_series(x : Union[List[float], Tuple[float, ...]], rows : int, cols : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, scale_min: float =0.0, scale_max: float =1.0, bounds_min: Any =(0.0, 0.0), bounds_max: Any =(1.0, 1.0), format: str ='%0.1f', contribute_to_bounds: bool =True, col_major: bool =False, **kwargs) -> Union[int, str]: - """ Adds a heat series to a plot. - - Args: - x (Any): - rows (int): - cols (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - scale_min (float, optional): Sets the color scale min. Typically paired with the color scale widget scale_min. - scale_max (float, optional): Sets the color scale max. Typically paired with the color scale widget scale_max. - bounds_min (Any, optional): - bounds_max (Any, optional): - format (str, optional): - contribute_to_bounds (bool, optional): - col_major (bool, optional): data will be read in column major order - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_heat_series(x, rows, cols, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, scale_min=scale_min, scale_max=scale_max, bounds_min=bounds_min, bounds_max=bounds_max, format=format, contribute_to_bounds=contribute_to_bounds, col_major=col_major, **kwargs) - -def add_histogram_series(x : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, bins: int =-1, bar_scale: float =1.0, min_range: float =0.0, max_range: float =0.0, cumulative: bool =False, density: bool =False, outliers: bool =True, horizontal: bool =False, contribute_to_bounds: bool =True, **kwargs) -> Union[int, str]: - """ Adds a histogram series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - bins (int, optional): - bar_scale (float, optional): - min_range (float, optional): set the min range value, the values under this min will be ignored - max_range (float, optional): set the max range value, the values over this max will be ignored. If both min and max are 0.0, then the values will be the min and max values of the series - cumulative (bool, optional): each bin will contain its count plus the counts of all previous bins - density (bool, optional): counts will be normalized, i.e. the PDF will be visualized, or the CDF will be visualized if Cumulative is also set - outliers (bool, optional): exclude values outside the specifed histogram range from the count toward normalizing and cumulative counts - horizontal (bool, optional): histogram bars will be rendered horizontally - contribute_to_bounds (bool, optional): - id (Union[int, str], optional): (deprecated) - cumlative (bool, optional): (deprecated) Deprecated because of typo - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'cumlative' in kwargs.keys(): - warnings.warn('cumlative keyword renamed to cumulative', DeprecationWarning, 2) - cumulative=kwargs['cumlative'] - - return internal_dpg.add_histogram_series(x, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, bins=bins, bar_scale=bar_scale, min_range=min_range, max_range=max_range, cumulative=cumulative, density=density, outliers=outliers, horizontal=horizontal, contribute_to_bounds=contribute_to_bounds, **kwargs) - -def add_image(texture_tag : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, tint_color: Union[List[float], Tuple[float, ...]] =(255, 255, 255, 255), border_color: Union[List[float], Tuple[float, ...]] =(0, 0, 0, 0), uv_min: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), uv_max: Union[List[float], Tuple[float, ...]] =(1.0, 1.0), **kwargs) -> Union[int, str]: - """ Adds an image from a specified texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) for texture coordinates will generally display the entire texture. - - Args: - texture_tag (Union[int, str]): The texture_tag should come from a texture that was added to a texture registry. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - tint_color (Union[List[float], Tuple[float, ...]], optional): Applies a color tint to the entire texture. - border_color (Union[List[float], Tuple[float, ...]], optional): Displays a border of the specified color around the texture. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates min point. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates max point. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_image(texture_tag, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, tint_color=tint_color, border_color=border_color, uv_min=uv_min, uv_max=uv_max, **kwargs) - -def add_image_button(texture_tag : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, tint_color: Union[List[float], Tuple[float, ...]] =(255, 255, 255, 255), background_color: Union[List[float], Tuple[float, ...]] =(0, 0, 0, 0), uv_min: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), uv_max: Union[List[float], Tuple[float, ...]] =(1.0, 1.0), **kwargs) -> Union[int, str]: - """ Adds an button with a texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) texture coordinates will generally display the entire texture - - Args: - texture_tag (Union[int, str]): The texture_tag should come from a texture that was added to a texture registry. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - tint_color (Union[List[float], Tuple[float, ...]], optional): Applies a color tint to the entire texture. - background_color (Union[List[float], Tuple[float, ...]], optional): Displays a border of the specified color around the texture. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates min point. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized texture coordinates max point. - id (Union[int, str], optional): (deprecated) - frame_padding (int, optional): (deprecated) Empty space around the outside of the texture. Button will show around the texture. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'frame_padding' in kwargs.keys(): - warnings.warn('frame_padding keyword deprecated. This is not supported anymore by ImGui but still used here as deprecated.', DeprecationWarning, 2) - - return internal_dpg.add_image_button(texture_tag, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, tint_color=tint_color, background_color=background_color, uv_min=uv_min, uv_max=uv_max, **kwargs) - -def add_image_series(texture_tag : Union[int, str], bounds_min : Union[List[float], Tuple[float, ...]], bounds_max : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, uv_min: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), uv_max: Union[List[float], Tuple[float, ...]] =(1.0, 1.0), tint_color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), **kwargs) -> Union[int, str]: - """ Adds an image series to a plot. - - Args: - texture_tag (Union[int, str]): - bounds_min (Any): - bounds_max (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - uv_min (Union[List[float], Tuple[float, ...]], optional): normalized texture coordinates - uv_max (Union[List[float], Tuple[float, ...]], optional): normalized texture coordinates - tint_color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_image_series(texture_tag, bounds_min, bounds_max, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, uv_min=uv_min, uv_max=uv_max, tint_color=tint_color, **kwargs) - -def add_inf_line_series(x : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, horizontal: bool =False, **kwargs) -> Union[int, str]: - """ Adds an infinite line series to a plot. - - Args: - x (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - horizontal (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_inf_line_series(x, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, horizontal=horizontal, **kwargs) - -def add_input_double(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, format: str ='%.3f', min_value: float =0.0, max_value: float =100.0, step: float =0.1, step_fast: float =1.0, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds input for an double. Useful when input float is not accurate enough. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (float, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (float, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (float, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_double(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, min_value=min_value, max_value=max_value, step=step, step_fast=step_fast, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_doublex(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Any =(0.0, 0.0, 0.0, 0.0), format: str ='%.3f', min_value: float =0.0, max_value: float =100.0, size: int =4, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds multi double input for up to 4 double values. Useful when input float mulit is not accurate enough. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (float, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_doublex(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, min_value=min_value, max_value=max_value, size=size, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_float(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, format: str ='%.3f', min_value: float =0.0, max_value: float =100.0, step: float =0.1, step_fast: float =1.0, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds input for an float. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (float, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (float, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (float, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_float(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, min_value=min_value, max_value=max_value, step=step, step_fast=step_fast, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_floatx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), format: str ='%.3f', min_value: float =0.0, max_value: float =100.0, size: int =4, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds multi float input for up to 4 float values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - format (str, optional): Determines the format the float will be displayed as use python string formatting. - min_value (float, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (float, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_floatx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, format=format, min_value=min_value, max_value=max_value, size=size, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_int(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: int =0, min_value: int =0, max_value: int =100, step: int =1, step_fast: int =100, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds input for an int. +/- buttons can be activated by setting the value of step. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - min_value (int, optional): Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input. - max_value (int, optional): Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input. - step (int, optional): Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons. - step_fast (int, optional): Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter key press. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_int(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, min_value=min_value, max_value=max_value, step=step, step_fast=step_fast, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_intx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[int], Tuple[int, ...]] =(0, 0, 0, 0), min_value: int =0, max_value: int =100, size: int =4, min_clamped: bool =False, max_clamped: bool =False, on_enter: bool =False, readonly: bool =False, accept_empty_input: bool =False, display_empty_value: bool =False, **kwargs) -> Union[int, str]: - """ Adds multi int input for up to 4 integer values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - min_value (int, optional): Value for lower limit of input for each cell. Use min_clamped to turn on. - max_value (int, optional): Value for upper limit of input for each cell. Use max_clamped to turn on. - size (int, optional): Number of components displayed for input. - min_clamped (bool, optional): Activates and deactivates the enforcment of min_value. - max_clamped (bool, optional): Activates and deactivates the enforcment of max_value. - on_enter (bool, optional): Only runs callback on enter. - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - accept_empty_input (bool, optional): Treat empty input as a zero value. - display_empty_value (bool, optional): If True, display an empty input if the value is zero. Generally used together with accept_empty_input. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_intx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, min_value=min_value, max_value=max_value, size=size, min_clamped=min_clamped, max_clamped=max_clamped, on_enter=on_enter, readonly=readonly, accept_empty_input=accept_empty_input, display_empty_value=display_empty_value, **kwargs) - -def add_input_text(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: str ='', hint: str ='', multiline: bool =False, no_spaces: bool =False, uppercase: bool =False, tab_input: bool =False, decimal: bool =False, hexadecimal: bool =False, readonly: bool =False, password: bool =False, scientific: bool =False, on_enter: bool =False, auto_select_all: bool =False, ctrl_enter_for_new_line: bool =False, no_horizontal_scroll: bool =False, always_overwrite: bool =False, no_undo_redo: bool =False, escape_clears_all: bool =False, elide_left: bool =False, **kwargs) -> Union[int, str]: - """ Adds input for text. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): - hint (str, optional): Displayed only when value is an empty string. Will reappear if input value is set to empty string. Will not show if default value is anything other than default empty string. - multiline (bool, optional): Allows for multiline text input. - no_spaces (bool, optional): Filter out spaces and tabs. - uppercase (bool, optional): Automatically make all inputs uppercase. - tab_input (bool, optional): Allows tabs to be input into the string value instead of changing item focus. - decimal (bool, optional): Only allow characters 0123456789.+-*/ - hexadecimal (bool, optional): Only allow characters 0123456789ABCDEFabcdef - readonly (bool, optional): Activates read only mode where no text can be input but text can still be highlighted. - password (bool, optional): Display all input characters as '*'. - scientific (bool, optional): Only allow characters 0123456789.+-*/eE (Scientific notation input) - on_enter (bool, optional): Only runs callback on enter key press. - auto_select_all (bool, optional): Select entire text when first taking mouse focus - ctrl_enter_for_new_line (bool, optional): In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). - no_horizontal_scroll (bool, optional): Disable following the cursor horizontally - always_overwrite (bool, optional): Overwrite mode - no_undo_redo (bool, optional): Disable undo/redo. - escape_clears_all (bool, optional): Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) - elide_left (bool, optional): When text doesn't fit an inactive input field, clip it on the left side and ensure the right side stays visible. Useful for path/filenames. Single-line inputs only. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_input_text(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, hint=hint, multiline=multiline, no_spaces=no_spaces, uppercase=uppercase, tab_input=tab_input, decimal=decimal, hexadecimal=hexadecimal, readonly=readonly, password=password, scientific=scientific, on_enter=on_enter, auto_select_all=auto_select_all, ctrl_enter_for_new_line=ctrl_enter_for_new_line, no_horizontal_scroll=no_horizontal_scroll, always_overwrite=always_overwrite, no_undo_redo=no_undo_redo, escape_clears_all=escape_clears_all, elide_left=elide_left, **kwargs) - -def add_int4_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Union[List[int], Tuple[int, ...]] =(0, 0, 0, 0), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a int4 value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Union[List[int], Tuple[int, ...]], optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_int4_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_int_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: int =0, parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a int value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (int, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_int_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_item_activated_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a activated handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_activated_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_active_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a active handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_active_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_clicked_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a clicked handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_clicked_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_deactivated_after_edit_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a deactivated after edit handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_deactivated_after_edit_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_deactivated_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a deactivated handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_deactivated_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_double_clicked_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a double click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_double_clicked_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_edited_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds an edited handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_edited_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_focus_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, event_type: int =None, **kwargs) -> Union[int, str]: - """ Adds a focus handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - event_type (int, optional): What kind of events to track: just got focus (mvEventType_Enter), currently having focus (mvEventType_On), lost focus (mvEventType_Leave). Can be a combination of these flags. Defaults to mvEventType_On. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_focus_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, event_type=event_type, **kwargs) - -def add_item_handler_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds an item handler registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_handler_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - -def add_item_hover_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, event_type: int =None, **kwargs) -> Union[int, str]: - """ Adds a hover handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - event_type (int, optional): What kind of events to track: mouse-in (mvEventType_Enter), mouse-over (mvEventType_On), mouse-out (mvEventType_Leave). Can be a combination of these flags. Defaults to mouse-over. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_hover_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, event_type=event_type, **kwargs) - -def add_item_resize_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a resize handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_resize_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_scroll_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a scroll handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_scroll_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_item_toggled_open_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, two_way: bool =False, **kwargs) -> Union[int, str]: - """ Adds a togged open handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - two_way (bool, optional): Trigger on both 'opened' and 'closed' events, i.e. when the 'opened' state is toggled between the two values. If False, some containers will trigger it only on the 'opened' event. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_toggled_open_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, two_way=two_way, **kwargs) - -def add_item_visible_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, callback: Callable =None, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a visible handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_item_visible_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, callback=callback, show=show, **kwargs) - -def add_key_down_handler(key : int =internal_dpg.mvKey_None, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a key down handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_key_down_handler(key, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_key_press_handler(key : int =internal_dpg.mvKey_None, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a key press handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_key_press_handler(key, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_key_release_handler(key : int =internal_dpg.mvKey_None, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a key release handler. - - Args: - key (int, optional): Submits callback for all keys - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_key_release_handler(key, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_knob_float(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, min_value: float =0.0, max_value: float =100.0, **kwargs) -> Union[int, str]: - """ Adds a knob that rotates based on change in x mouse position. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - min_value (float, optional): Applies lower limit to value. - max_value (float, optional): Applies upper limit to value. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_knob_float(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, min_value=min_value, max_value=max_value, **kwargs) - -def add_line_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, segments: bool =False, loop: bool =False, skip_nan: bool =False, no_clip: bool =False, shaded: bool =False, **kwargs) -> Union[int, str]: - """ Adds a line series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - segments (bool, optional): a line segment will be rendered from every two consecutive points - loop (bool, optional): the last and first point will be connected to form a closed loop - skip_nan (bool, optional): NaNs values will be skipped instead of rendered as missing data - no_clip (bool, optional): markers (if displayed) on the edge of a plot will not be clipped - shaded (bool, optional): a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_line_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, segments=segments, loop=loop, skip_nan=skip_nan, no_clip=no_clip, shaded=shaded, **kwargs) - -def add_listbox(items : Union[List[str], Tuple[str, ...]] =(), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: str ='', num_items: int =3, **kwargs) -> Union[int, str]: - """ Adds a listbox. If height is not large enough to show all items a scroll bar will appear. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown in the listbox. Can consist of any combination of types. All items will be displayed as strings. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): String value of the item that will be selected by default. - num_items (int, optional): Expands the height of the listbox to show specified number of items. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_listbox(items, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, num_items=num_items, **kwargs) - -def add_loading_indicator(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], style: int =0, circle_count: int =8, speed: float =1.0, radius: float =3.0, thickness: float =1.0, color: Union[List[int], Tuple[int, ...]] =None, secondary_color: Union[List[int], Tuple[int, ...]] =None, **kwargs) -> Union[int, str]: - """ Adds a rotating animated loading symbol. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - style (int, optional): mvLoadInd_DottedCircle is rotating dots style, mvLoadInd_Ring is rotating bar style. - circle_count (int, optional): DottedCircle style: number of dots to show. - speed (float, optional): Speed with which the animation will rotate. - radius (float, optional): Scale factor for the loading indicator radius. The size of the indicator is determined by font size and this scale factor. - thickness (float, optional): Ring style: scale factor of line thickness; thickness=1 corresponds to line width being 1/8 of the ring diameter. - color (Union[List[int], Tuple[int, ...]], optional): Main color of the indicator. If omitted, the color for mvThemeCol_Button will be used. - secondary_color (Union[List[int], Tuple[int, ...]], optional): DottedCircle style: color of 'inactive' dots. If omitted, the color for mvThemeCol_ButtonHovered will be used. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_loading_indicator(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, pos=pos, style=style, circle_count=circle_count, speed=speed, radius=radius, thickness=thickness, color=color, secondary_color=secondary_color, **kwargs) - -def add_menu(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, enabled: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, **kwargs) -> Union[int, str]: - """ Adds a menu to an existing menu bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_menu(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, enabled=enabled, filter_key=filter_key, tracked=tracked, track_offset=track_offset, **kwargs) - -def add_menu_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a menu bar to a window. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_menu_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, show=show, **kwargs) - -def add_menu_item(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: bool =False, shortcut: str ='', check: bool =False, **kwargs) -> Union[int, str]: - """ Adds a menu item to an existing menu. Menu items act similar to selectables and has a bool value. When placed in a menu the checkmark will reflect its value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): This value also controls the checkmark when shown. - shortcut (str, optional): Displays text on the menu item. Typically used to show a shortcut key command. - check (bool, optional): Displays a checkmark on the menu item when it is selected and placed in a menu. - id (Union[int, str], optional): (deprecated) - drag_callback (Callable, optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'drag_callback' in kwargs.keys(): - - warnings.warn('drag_callback keyword removed', DeprecationWarning, 2) - - kwargs.pop('drag_callback', None) - - return internal_dpg.add_menu_item(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drop_callback=drop_callback, show=show, enabled=enabled, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, shortcut=shortcut, check=check, **kwargs) - -def add_mouse_click_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_click_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_double_click_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse double click handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_double_click_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_down_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse down handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_down_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_drag_handler(button : int =-1, threshold : float =10.0, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse drag handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - threshold (float, optional): The threshold the mouse must be dragged before the callback is ran - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_drag_handler(button, threshold, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_move_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse move handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_move_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_release_handler(button : int =-1, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse release handler. - - Args: - button (int, optional): Submits callback for all mouse buttons - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_release_handler(button, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_mouse_wheel_handler(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True, parent: Union[int, str] =internal_dpg.mvReservedUUID_1, **kwargs) -> Union[int, str]: - """ Adds a mouse wheel handler. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_mouse_wheel_handler(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, callback=callback, show=show, parent=parent, **kwargs) - -def add_node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, draggable: bool =True, **kwargs) -> Union[int, str]: - """ Adds a node to a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - draggable (bool, optional): Allow node to be draggable. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, draggable=draggable, **kwargs) - -def add_node_attribute(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, attribute_type: int =0, shape: int =1, category: str ='general', **kwargs) -> Union[int, str]: - """ Adds a node attribute to a node. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - attribute_type (int, optional): mvNode_Attr_Input, mvNode_Attr_Output, or mvNode_Attr_Static. - shape (int, optional): Pin shape. - category (str, optional): Category - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_node_attribute(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, attribute_type=attribute_type, shape=shape, category=category, **kwargs) - -def add_node_editor(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, delink_callback: Callable =None, menubar: bool =False, minimap: bool =False, minimap_location: int =2, **kwargs) -> Union[int, str]: - """ Adds a node editor. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - delink_callback (Callable, optional): Callback ran when a link is detached. - menubar (bool, optional): Shows or hides the menubar. - minimap (bool, optional): Shows or hides the Minimap. New in 1.6. - minimap_location (int, optional): mvNodeMiniMap_Location_* constants. New in 1.6. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_node_editor(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, parent=parent, before=before, callback=callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, delink_callback=delink_callback, menubar=menubar, minimap=minimap, minimap_location=minimap_location, **kwargs) - -def add_node_link(attr_1 : Union[int, str], attr_2 : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a node link between 2 node attributes. - - Args: - attr_1 (Union[int, str]): - attr_2 (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_node_link(attr_1, attr_2, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, show=show, **kwargs) - -def add_pie_series(x : float, y : float, radius : float, values : Union[List[float], Tuple[float, ...]], labels : Union[List[str], Tuple[str, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, format: str ='%0.2f', angle: float =90.0, normalize: bool =False, ignore_hidden: bool =False, **kwargs) -> Union[int, str]: - """ Adds an pie series to a plot. - - Args: - x (float): - y (float): - radius (float): - values (Any): - labels (Union[List[str], Tuple[str, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - format (str, optional): - angle (float, optional): - normalize (bool, optional): force normalization of pie chart values (i.e. always make a full circle if sum < 0) - ignore_hidden (bool, optional): ignore hidden slices when drawing the pie chart (as if they were not there) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_pie_series(x, y, radius, values, labels, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, format=format, angle=angle, normalize=normalize, ignore_hidden=ignore_hidden, **kwargs) - -def add_plot(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_title: bool =False, no_menus: bool =False, no_box_select: bool =False, no_mouse_pos: bool =False, query: bool =False, query_color: Union[List[float], Tuple[float, ...]] =(0, 255, 0, 255), min_query_rects: int =1, max_query_rects: int =1, crosshairs: bool =False, equal_aspects: bool =False, no_inputs: bool =False, no_frame: bool =False, use_local_time: bool =False, use_ISO8601: bool =False, use_24hour_clock: bool =False, pan_button: int =internal_dpg.mvMouseButton_Left, pan_mod: int =internal_dpg.mvKey_None, context_menu_button: int =internal_dpg.mvMouseButton_Right, fit_button: int =internal_dpg.mvMouseButton_Left, box_select_button: int =internal_dpg.mvMouseButton_Right, box_select_mod: int =internal_dpg.mvKey_None, box_select_cancel_button: int =internal_dpg.mvMouseButton_Left, query_toggle_mod: int =internal_dpg.mvKey_ModCtrl, horizontal_mod: int =internal_dpg.mvKey_ModAlt, vertical_mod: int =internal_dpg.mvKey_ModShift, override_mod: int =internal_dpg.mvKey_ModCtrl, zoom_mod: int =internal_dpg.mvKey_None, zoom_rate: int =0.1, **kwargs) -> Union[int, str]: - """ Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_title (bool, optional): the plot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_box_select (bool, optional): the user will not be able to box-select with right-click drag - no_mouse_pos (bool, optional): the text of mouse position, in plot coordinates, will not be displayed inside of the plot - query (bool, optional): the user will be able to draw query rects with CTRL + right-click drag - query_color (Union[List[float], Tuple[float, ...]], optional): Color of the query rectangles. - min_query_rects (int, optional): The minimum number of query rects that can be in the plot. If there are less rects than this value, it won't be possible to delete them. - max_query_rects (int, optional): The maximum number of query rects that can be in the plot. If the number is reached any rect added will replace the latest one. (0 means unlimited) - crosshairs (bool, optional): the default mouse cursor will be replaced with a crosshair when hovered - equal_aspects (bool, optional): primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes) - no_inputs (bool, optional): the user will not be able to interact with the plot - no_frame (bool, optional): the ImGui frame will not be rendered - use_local_time (bool, optional): axis labels will be formatted for your timezone when - use_ISO8601 (bool, optional): dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.) - use_24hour_clock (bool, optional): times will be formatted using a 24 hour clock - pan_button (int, optional): mouse button that enables panning when held - pan_mod (int, optional): optional modifier that must be held for panning - context_menu_button (int, optional): opens context menus (if enabled) when clicked - fit_button (int, optional): fits visible data when double clicked - box_select_button (int, optional): begins box selection when pressed and confirms selection when released - box_select_mod (int, optional): begins box selection when pressed and confirms selection when released - box_select_cancel_button (int, optional): cancels active box selection when pressed - query_toggle_mod (int, optional): when held, active box selections turn into queries - horizontal_mod (int, optional): expands active box selection/query horizontally to plot edge when held - vertical_mod (int, optional): expands active box selection/query vertically to plot edge when held - override_mod (int, optional): when held, all input is ignored; used to enable axis/plots as DND sources - zoom_mod (int, optional): optional modifier that must be held for scroll wheel zooming - zoom_rate (int, optional): zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - no_highlight (bool, optional): (deprecated) Removed because not supported from the backend anymore. To control the highlighting of series use the same argument in `add_plot_legend` - no_child (bool, optional): (deprecated) a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications) - anti_aliased (bool, optional): (deprecated) This feature was deprecated in ImPlot. To enable/disable anti_aliasing use `dpg.configure_app()` with the `anti_aliasing` parameters. - query_button (int, optional): (deprecated) This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - query_mod (int, optional): (deprecated) This refers to the old way of querying of ImPlot, now replaced with `DragRect()` - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - if 'no_highlight' in kwargs.keys(): - - warnings.warn('no_highlight keyword removed', DeprecationWarning, 2) - - kwargs.pop('no_highlight', None) - - if 'no_child' in kwargs.keys(): - - warnings.warn('no_child keyword removed', DeprecationWarning, 2) - - kwargs.pop('no_child', None) - - if 'anti_aliased' in kwargs.keys(): - - warnings.warn('anti_aliased keyword removed', DeprecationWarning, 2) - - kwargs.pop('anti_aliased', None) - - if 'query_button' in kwargs.keys(): - - warnings.warn('query_button keyword removed', DeprecationWarning, 2) - - kwargs.pop('query_button', None) - - if 'query_mod' in kwargs.keys(): - - warnings.warn('query_mod keyword removed', DeprecationWarning, 2) - - kwargs.pop('query_mod', None) - - return internal_dpg.add_plot(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_title=no_title, no_menus=no_menus, no_box_select=no_box_select, no_mouse_pos=no_mouse_pos, query=query, query_color=query_color, min_query_rects=min_query_rects, max_query_rects=max_query_rects, crosshairs=crosshairs, equal_aspects=equal_aspects, no_inputs=no_inputs, no_frame=no_frame, use_local_time=use_local_time, use_ISO8601=use_ISO8601, use_24hour_clock=use_24hour_clock, pan_button=pan_button, pan_mod=pan_mod, context_menu_button=context_menu_button, fit_button=fit_button, box_select_button=box_select_button, box_select_mod=box_select_mod, box_select_cancel_button=box_select_cancel_button, query_toggle_mod=query_toggle_mod, horizontal_mod=horizontal_mod, vertical_mod=vertical_mod, override_mod=override_mod, zoom_mod=zoom_mod, zoom_rate=zoom_rate, **kwargs) - -def add_plot_annotation(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, default_value: Any =(0.0, 0.0), offset: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), color: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), clamped: bool =True, **kwargs) -> Union[int, str]: - """ Adds an annotation to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - default_value (Any, optional): - offset (Union[List[float], Tuple[float, ...]], optional): - color (Union[List[int], Tuple[int, ...]], optional): - clamped (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_plot_annotation(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, default_value=default_value, offset=offset, color=color, clamped=clamped, **kwargs) - -def add_plot_axis(axis : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, no_label: bool =False, no_gridlines: bool =False, no_tick_marks: bool =False, no_tick_labels: bool =False, no_initial_fit: bool =False, no_menus: bool =False, no_side_switch: bool =False, no_highlight: bool =False, opposite: bool =False, foreground_grid: bool =False, tick_format: str ='', scale: int =internal_dpg.mvPlotScale_Linear, invert: bool =False, auto_fit: bool =False, range_fit: bool =False, pan_stretch: bool =False, lock_min: bool =False, lock_max: bool =False, **kwargs) -> Union[int, str]: - """ Adds an axis to a plot. - - Args: - axis (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - no_label (bool, optional): the axis label will not be displayed - no_gridlines (bool, optional): no grid lines will be displayed - no_tick_marks (bool, optional): no tick marks will be displayed - no_tick_labels (bool, optional): no text labels will be displayed - no_initial_fit (bool, optional): axis will not be initially fit to data extents on the first rendered frame - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_side_switch (bool, optional): the user will not be able to switch the axis side by dragging it - no_highlight (bool, optional): the axis will not have its background highlighted when hovered or held - opposite (bool, optional): axis ticks and labels will be rendered on the conventionally opposite side (i.e, right or top) - foreground_grid (bool, optional): grid lines will be displayed in the foreground (i.e. on top of data) instead of the background - tick_format (str, optional): Sets a custom tick label formatter - scale (int, optional): Sets the axis' scale. Can have only mvPlotScale_ values - invert (bool, optional): the axis values will be inverted (i.e. growing from right to left) - auto_fit (bool, optional): axis will be auto-fitting to data extents - range_fit (bool, optional): axis will only fit points if the point is in the visible range of the **orthogonal** axis - pan_stretch (bool, optional): panning in a locked or constrained state will cause the axis to stretch if possible - lock_min (bool, optional): the axis minimum value will be locked when panning/zooming - lock_max (bool, optional): the axis maximum value will be locked when panning/zooming - id (Union[int, str], optional): (deprecated) - log_scale (bool, optional): (deprecated) Old way to set log scale in the axis. Use 'scale' argument instead. - time (bool, optional): (deprecated) Old way to set time scale in the axis. Use 'scale' argument instead. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'log_scale' in kwargs.keys(): - warnings.warn('log_scale keyword deprecated. See the new scale argument.', DeprecationWarning, 2) - - if 'time' in kwargs.keys(): - warnings.warn('time keyword deprecated. See the new scale argument.', DeprecationWarning, 2) - - return internal_dpg.add_plot_axis(axis, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, payload_type=payload_type, drop_callback=drop_callback, show=show, no_label=no_label, no_gridlines=no_gridlines, no_tick_marks=no_tick_marks, no_tick_labels=no_tick_labels, no_initial_fit=no_initial_fit, no_menus=no_menus, no_side_switch=no_side_switch, no_highlight=no_highlight, opposite=opposite, foreground_grid=foreground_grid, tick_format=tick_format, scale=scale, invert=invert, auto_fit=auto_fit, range_fit=range_fit, pan_stretch=pan_stretch, lock_min=lock_min, lock_max=lock_max, **kwargs) - -def add_plot_legend(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, location: int =5, horizontal: bool =False, sort: bool =False, outside: bool =False, no_highlight_item: bool =False, no_highlight_axis: bool =False, no_menus: bool =False, no_buttons: bool =False, **kwargs) -> Union[int, str]: - """ Adds a plot legend to a plot. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - location (int, optional): location, mvPlot_Location_* - horizontal (bool, optional): legend entries will be displayed horizontally - sort (bool, optional): legend entries will be displayed in alphabetical order - outside (bool, optional): legend will be rendered outside of the plot area - no_highlight_item (bool, optional): plot items will not be highlighted when their legend entry is hovered - no_highlight_axis (bool, optional): axes will not be highlighted when legend entries are hovered (only relevant if x/y-axis count > 1) - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_buttons (bool, optional): legend icons will not function as hide/show buttons - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_plot_legend(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, payload_type=payload_type, drop_callback=drop_callback, show=show, location=location, horizontal=horizontal, sort=sort, outside=outside, no_highlight_item=no_highlight_item, no_highlight_axis=no_highlight_axis, no_menus=no_menus, no_buttons=no_buttons, **kwargs) - -def add_progress_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, overlay: str ='', default_value: float =0.0, **kwargs) -> Union[int, str]: - """ Adds a progress bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - overlay (str, optional): Overlayed text onto the bar that typically used to display the value of the progress. - default_value (float, optional): Normalized value to fill the bar from 0.0 to 1.0. Put a negative value to show an indeterminate progress bar. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_progress_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, overlay=overlay, default_value=default_value, **kwargs) - -def add_radio_button(items : Union[List[str], Tuple[str, ...]] =(), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: str ='', horizontal: bool =False, **kwargs) -> Union[int, str]: - """ Adds a set of radio buttons. If items keyword is empty, nothing will be shown. - - Args: - items (Union[List[str], Tuple[str, ...]], optional): A tuple of items to be shown as radio options. Can consist of any combination of types. All types will be shown as strings. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (str, optional): Default selected radio option. Set by using the string value of the item. - horizontal (bool, optional): Displays the radio options horizontally. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_radio_button(items, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, horizontal=horizontal, **kwargs) - -def add_raw_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, format: int =internal_dpg.mvFormat_Float_rgba, parent: Union[int, str] =internal_dpg.mvReservedUUID_2, **kwargs) -> Union[int, str]: - """ Adds a raw texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - format (int, optional): Data format. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_raw_texture(width, height, default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, format=format, parent=parent, **kwargs) - -def add_scatter_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, no_clip: bool =False, **kwargs) -> Union[int, str]: - """ Adds a scatter series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - no_clip (bool, optional): markers on the edge of a plot will not be clipped - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_scatter_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, no_clip=no_clip, **kwargs) - -def add_selectable(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: bool =False, span_columns: bool =False, disable_popup_close: bool =False, select_on_nav: bool =False, **kwargs) -> Union[int, str]: - """ Adds a selectable. Similar to a button but can indicate its selected state. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (bool, optional): - span_columns (bool, optional): Forces the selectable to span the width of all columns if placed in a table. - disable_popup_close (bool, optional): Disable closing a modal or popup window. - select_on_nav (bool, optional): Auto-select when moved into with keyboard navigation, unless Ctrl is held. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_selectable(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, span_columns=span_columns, disable_popup_close=disable_popup_close, select_on_nav=select_on_nav, **kwargs) - -def add_separator(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], **kwargs) -> Union[int, str]: - """ Adds a horizontal line separator. Use 'label' parameter to add text and mvStyleVar_SeparatorText* elements to style it. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_separator(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, show=show, pos=pos, **kwargs) - -def add_series_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: Any =(), parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a plot series value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (Any, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_series_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_shade_series(x : Union[List[float], Tuple[float, ...]], y1 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, y2: Any =[], **kwargs) -> Union[int, str]: - """ Adds a shade series to a plot. - - Args: - x (Any): - y1 (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - y2 (Any, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_shade_series(x, y1, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, y2=y2, **kwargs) - -def add_simple_plot(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[float], Tuple[float, ...]] =(), overlay: str ='', histogram: bool =False, autosize: bool =True, min_scale: float =0.0, max_scale: float =0.0, **kwargs) -> Union[int, str]: - """ Adds a simple plot for visualization of a 1 dimensional set of values. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - overlay (str, optional): overlays text (similar to a plot title) - histogram (bool, optional): - autosize (bool, optional): - min_scale (float, optional): - max_scale (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_simple_plot(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, overlay=overlay, histogram=histogram, autosize=autosize, min_scale=min_scale, max_scale=max_scale, **kwargs) - -def add_slider_double(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, vertical: bool =False, no_input: bool =False, clamped: bool =False, min_value: float =0.0, max_value: float =100.0, format: str ='%.3f', **kwargs) -> Union[int, str]: - """ Adds slider for a single double value. Useful when slider float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_double(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, vertical=vertical, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_slider_doublex(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Any =(0.0, 0.0, 0.0, 0.0), size: int =4, no_input: bool =False, clamped: bool =False, min_value: float =0.0, max_value: float =100.0, format: str ='%.3f', **kwargs) -> Union[int, str]: - """ Adds multi slider for up to 4 double values. Usueful for when multi slide float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Any, optional): - size (int, optional): Number of doubles to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_doublex(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_slider_float(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: float =0.0, vertical: bool =False, no_input: bool =False, clamped: bool =False, min_value: float =0.0, max_value: float =100.0, format: str ='%.3f', **kwargs) -> Union[int, str]: - """ Adds slider for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (float, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the float will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_float(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, vertical=vertical, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_slider_floatx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[float], Tuple[float, ...]] =(0.0, 0.0, 0.0, 0.0), size: int =4, no_input: bool =False, clamped: bool =False, min_value: float =0.0, max_value: float =100.0, format: str ='%.3f', **kwargs) -> Union[int, str]: - """ Adds multi slider for up to 4 float values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[float], Tuple[float, ...]], optional): - size (int, optional): Number of floats to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (float, optional): Applies a limit only to sliding entry only. - max_value (float, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_floatx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_slider_int(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: int =0, vertical: bool =False, no_input: bool =False, clamped: bool =False, min_value: int =0, max_value: int =100, format: str ='%d', **kwargs) -> Union[int, str]: - """ Adds slider for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (int, optional): - vertical (bool, optional): Sets orientation of the slidebar and slider to vertical. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (int, optional): Applies a limit only to sliding entry only. - max_value (int, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_int(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, vertical=vertical, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_slider_intx(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, enabled: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: Union[List[int], Tuple[int, ...]] =(0, 0, 0, 0), size: int =4, no_input: bool =False, clamped: bool =False, min_value: int =0, max_value: int =100, format: str ='%d', **kwargs) -> Union[int, str]: - """ Adds multi slider for up to 4 int values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (Union[List[int], Tuple[int, ...]], optional): - size (int, optional): Number of ints to be displayed. - no_input (bool, optional): Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item. - clamped (bool, optional): Applies the min and max limits to direct entry methods also such as double click and CTRL+Click. - min_value (int, optional): Applies a limit only to sliding entry only. - max_value (int, optional): Applies a limit only to sliding entry only. - format (str, optional): Determines the format the int will be displayed as use python string formatting. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_slider_intx(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, enabled=enabled, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, size=size, no_input=no_input, clamped=clamped, min_value=min_value, max_value=max_value, format=format, **kwargs) - -def add_spacer(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], **kwargs) -> Union[int, str]: - """ Adds a spacer item that can be used to help with layouts or can be used as a placeholder item. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_spacer(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, show=show, pos=pos, **kwargs) - -def add_stage(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a stage. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_stage(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - -def add_stair_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, pre_step: bool =False, shaded: bool =False, **kwargs) -> Union[int, str]: - """ Adds a stair series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - pre_step (bool, optional): the y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i] - shaded (bool, optional): a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_stair_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, pre_step=pre_step, shaded=shaded, **kwargs) - -def add_static_texture(width : int, height : int, default_value : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =internal_dpg.mvReservedUUID_2, **kwargs) -> Union[int, str]: - """ Adds a static texture. - - Args: - width (int): - height (int): - default_value (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_static_texture(width, height, default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, **kwargs) - -def add_stem_series(x : Union[List[float], Tuple[float, ...]], y : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, horizontal: bool =False, **kwargs) -> Union[int, str]: - """ Adds a stem series to a plot. - - Args: - x (Any): - y (Any): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - horizontal (bool, optional): stems will be rendered horizontally on the current y-axis - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_stem_series(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, source=source, show=show, horizontal=horizontal, **kwargs) - -def add_string_value(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, source: Union[int, str] =0, default_value: str ='', parent: Union[int, str] =internal_dpg.mvReservedUUID_3, **kwargs) -> Union[int, str]: - """ Adds a string value. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - source (Union[int, str], optional): Overrides 'id' as value storage key. - default_value (str, optional): - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_string_value(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, source=source, default_value=default_value, parent=parent, **kwargs) - -def add_subplots(rows : int, columns : int, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, row_ratios: Union[List[float], Tuple[float, ...]] =[], column_ratios: Union[List[float], Tuple[float, ...]] =[], no_title: bool =False, no_menus: bool =False, no_resize: bool =False, no_align: bool =False, share_series: bool =False, link_rows: bool =False, link_columns: bool =False, link_all_x: bool =False, link_all_y: bool =False, column_major: bool =False, **kwargs) -> Union[int, str]: - """ Adds a collection of plots. - - Args: - rows (int): - columns (int): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - row_ratios (Union[List[float], Tuple[float, ...]], optional): - column_ratios (Union[List[float], Tuple[float, ...]], optional): - no_title (bool, optional): the subplot title will not be displayed - no_menus (bool, optional): the user will not be able to open context menus with right-click - no_resize (bool, optional): resize splitters between subplot cells will be not be provided - no_align (bool, optional): subplot edges will not be aligned vertically or horizontally - share_series (bool, optional): when set to True, series from all sub-plots will be shared to some extent, using a single common color set and showing them in a single legend in the subplots item. Otherwise each plot will be independent from others and will have its own legend - link_rows (bool, optional): link the y-axis limits of all plots in each row (does not apply auxiliary y-axes) - link_columns (bool, optional): link the x-axis limits of all plots in each column - link_all_x (bool, optional): link the x-axis limits in every plot in the subplot - link_all_y (bool, optional): link the y-axis limits in every plot in the subplot (does not apply to auxiliary y-axes) - column_major (bool, optional): subplots are added in column major order instead of the default row major order - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_subplots(rows, columns, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, row_ratios=row_ratios, column_ratios=column_ratios, no_title=no_title, no_menus=no_menus, no_resize=no_resize, no_align=no_align, share_series=share_series, link_rows=link_rows, link_columns=link_columns, link_all_x=link_all_x, link_all_y=link_all_y, column_major=column_major, **kwargs) - -def add_synced_tables(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Links all tables that are immediate children of this container so that they share their state (mostly column sizes). Other children are rendered as is. This is an experimental feature, use with caution. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_synced_tables(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - -def add_tab(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drop_callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, closable: bool =False, no_tooltip: bool =False, order_mode: int =0, unsaved_document: bool =False, no_close_with_middle_click: bool =False, no_reorder: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tab to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - closable (bool, optional): Creates a button on the tab that can hide the tab. - no_tooltip (bool, optional): Disable tooltip for the given tab. - order_mode (int, optional): set using a constant: mvTabOrder_Reorderable: allows reordering, mvTabOrder_Fixed: fixed ordering, mvTabOrder_Leading: adds tab to front, mvTabOrder_Trailing: adds tab to back - unsaved_document (bool, optional): Display a dot next to the title. - no_close_with_middle_click (bool, optional): Disable closing this tab (if closable==True) by clicking with middle mouse button. - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_tab(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drop_callback=drop_callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, closable=closable, no_tooltip=no_tooltip, order_mode=order_mode, unsaved_document=unsaved_document, no_close_with_middle_click=no_close_with_middle_click, no_reorder=no_reorder, **kwargs) - -def add_tab_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, reorderable: bool =False, tab_list_popup_button: bool =False, no_close_with_middle_click: bool =False, no_scrolling_buttons: bool =False, no_tooltip: bool =False, draw_selected_overline: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - reorderable (bool, optional): Allows for the user to change the order of the tabs. - tab_list_popup_button (bool, optional): Show a button to select active tab from a dropdown list. - no_close_with_middle_click (bool, optional): Disable closing tabs (that have closable=True) by clicking with middle mouse button. - no_scrolling_buttons (bool, optional): Disable left/right scrolling buttons when tab buttons don't fit the container width. - no_tooltip (bool, optional): Disable tooltips when hovering a tab with a long name. - draw_selected_overline (bool, optional): Draw selected overline markers over selected tab. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_tab_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, callback=callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, reorderable=reorderable, tab_list_popup_button=tab_list_popup_button, no_close_with_middle_click=no_close_with_middle_click, no_scrolling_buttons=no_scrolling_buttons, no_tooltip=no_tooltip, draw_selected_overline=draw_selected_overline, **kwargs) - -def add_tab_button(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, filter_key: str ='', tracked: bool =False, track_offset: float =0.5, no_reorder: bool =False, leading: bool =False, trailing: bool =False, no_tooltip: bool =False, unsaved_document: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tab button to a tab bar. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - no_reorder (bool, optional): Disable reordering this tab or having another tab cross over this tab. Fixes the position of this tab in relation to the order of neighboring tabs at start. - leading (bool, optional): Enforce the tab position to the left of the tab bar (after the tab list popup button). - trailing (bool, optional): Enforce the tab position to the right of the tab bar (before the scrolling buttons). - no_tooltip (bool, optional): Disable tooltip for the given tab. - unsaved_document (bool, optional): Display a dot next to the title. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_tab_button(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, filter_key=filter_key, tracked=tracked, track_offset=track_offset, no_reorder=no_reorder, leading=leading, trailing=trailing, no_tooltip=no_tooltip, unsaved_document=unsaved_document, **kwargs) - -def add_table(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', header_row: bool =True, clipper: bool =False, inner_width: int =0, policy: int =0, freeze_rows: int =0, freeze_columns: int =0, sort_multi: bool =False, sort_tristate: bool =False, resizable: bool =False, reorderable: bool =False, hideable: bool =False, sortable: bool =False, context_menu_in_body: bool =False, row_background: bool =False, borders_innerH: bool =False, borders_outerH: bool =False, borders_innerV: bool =False, borders_outerV: bool =False, no_host_extendX: bool =False, no_host_extendY: bool =False, no_keep_columns_visible: bool =False, precise_widths: bool =False, no_clip: bool =False, pad_outerX: bool =False, no_pad_outerX: bool =False, no_pad_innerX: bool =False, scrollX: bool =False, scrollY: bool =False, no_saved_settings: bool =False, **kwargs) -> Union[int, str]: - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - callback (Callable, optional): Registers a callback. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - header_row (bool, optional): show headers at the top of the columns - clipper (bool, optional): Use clipper (rows must be same height). - inner_width (int, optional): - policy (int, optional): - freeze_rows (int, optional): - freeze_columns (int, optional): - sort_multi (bool, optional): Hold shift when clicking headers to sort on multiple column. - sort_tristate (bool, optional): Allow no sorting, disable default sorting. - resizable (bool, optional): Enable resizing columns - reorderable (bool, optional): Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - hideable (bool, optional): Enable hiding/disabling columns in context menu. - sortable (bool, optional): Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - context_menu_in_body (bool, optional): Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - row_background (bool, optional): Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - borders_innerH (bool, optional): Draw horizontal borders between rows. - borders_outerH (bool, optional): Draw horizontal borders at the top and bottom. - borders_innerV (bool, optional): Draw vertical borders between columns. - borders_outerV (bool, optional): Draw vertical borders on the left and right sides. - no_host_extendX (bool, optional): Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - no_host_extendY (bool, optional): Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - no_keep_columns_visible (bool, optional): Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - precise_widths (bool, optional): Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - no_clip (bool, optional): Disable clipping rectangle for every individual columns. - pad_outerX (bool, optional): Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. - no_pad_outerX (bool, optional): Default if BordersOuterV is off. Disable outer-most padding. - no_pad_innerX (bool, optional): Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - scrollX (bool, optional): Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - scrollY (bool, optional): Enable vertical scrolling. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_table(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, parent=parent, before=before, source=source, callback=callback, show=show, pos=pos, filter_key=filter_key, header_row=header_row, clipper=clipper, inner_width=inner_width, policy=policy, freeze_rows=freeze_rows, freeze_columns=freeze_columns, sort_multi=sort_multi, sort_tristate=sort_tristate, resizable=resizable, reorderable=reorderable, hideable=hideable, sortable=sortable, context_menu_in_body=context_menu_in_body, row_background=row_background, borders_innerH=borders_innerH, borders_outerH=borders_outerH, borders_innerV=borders_innerV, borders_outerV=borders_outerV, no_host_extendX=no_host_extendX, no_host_extendY=no_host_extendY, no_keep_columns_visible=no_keep_columns_visible, precise_widths=precise_widths, no_clip=no_clip, pad_outerX=pad_outerX, no_pad_outerX=no_pad_outerX, no_pad_innerX=no_pad_innerX, scrollX=scrollX, scrollY=scrollY, no_saved_settings=no_saved_settings, **kwargs) - -def add_table_cell(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Adds a table. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_table_cell(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, height=height, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - -def add_table_column(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, enabled: bool =True, init_width_or_weight: float =0.0, default_hide: bool =False, default_sort: bool =False, width_stretch: bool =False, width_fixed: bool =False, no_resize: bool =False, no_reorder: bool =False, no_hide: bool =False, no_clip: bool =False, no_sort: bool =False, no_sort_ascending: bool =False, no_sort_descending: bool =False, no_header_width: bool =False, prefer_sort_ascending: bool =True, prefer_sort_descending: bool =False, indent_enable: bool =False, indent_disable: bool =False, angled_header: bool =False, no_header_label: bool =False, **kwargs) -> Union[int, str]: - """ Adds a table column. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - enabled (bool, optional): Turns off functionality of widget and applies the disabled theme. - init_width_or_weight (float, optional): - default_hide (bool, optional): Default as a hidden/disabled column. - default_sort (bool, optional): Default as a sorting column. - width_stretch (bool, optional): Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). - width_fixed (bool, optional): Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). - no_resize (bool, optional): Disable manual resizing. - no_reorder (bool, optional): Disable manual reordering this column, this will also prevent other columns from crossing over this column. - no_hide (bool, optional): Disable ability to hide/disable this column. - no_clip (bool, optional): Disable clipping for this column (all NoClip columns will render in a same draw command). - no_sort (bool, optional): Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). - no_sort_ascending (bool, optional): Disable ability to sort in the ascending direction. - no_sort_descending (bool, optional): Disable ability to sort in the descending direction. - no_header_width (bool, optional): Disable header text width contribution to automatic column width. - prefer_sort_ascending (bool, optional): Make the initial sort direction Ascending when first sorting on this column (default). - prefer_sort_descending (bool, optional): Make the initial sort direction Descending when first sorting on this column. - indent_enable (bool, optional): Use current Indent value when entering cell (default for column 0). - indent_disable (bool, optional): Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. - angled_header (bool, optional): Set this parameter to True to display the header text for this column in an angled (diagonal) orientation. This will add an additional row to accommodate the angled text. - no_header_label (bool, optional): Disable horizontal label for this column. Name will still appear in context menu or in angled headers. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_table_column(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, parent=parent, before=before, show=show, enabled=enabled, init_width_or_weight=init_width_or_weight, default_hide=default_hide, default_sort=default_sort, width_stretch=width_stretch, width_fixed=width_fixed, no_resize=no_resize, no_reorder=no_reorder, no_hide=no_hide, no_clip=no_clip, no_sort=no_sort, no_sort_ascending=no_sort_ascending, no_sort_descending=no_sort_descending, no_header_width=no_header_width, prefer_sort_ascending=prefer_sort_ascending, prefer_sort_descending=prefer_sort_descending, indent_enable=indent_enable, indent_disable=indent_disable, angled_header=angled_header, no_header_label=no_header_label, **kwargs) - -def add_table_row(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, height: int =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, filter_key: str ='', **kwargs) -> Union[int, str]: - """ Adds a table row. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - height (int, optional): Height of the item. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_table_row(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, height=height, parent=parent, before=before, show=show, filter_key=filter_key, **kwargs) - -def add_template_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a template registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_template_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - -def add_text(default_value : str ='', *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, wrap: int =-1, bullet: bool =False, color: Union[List[int], Tuple[int, ...]] =(-255, 0, 0, 255), show_label: bool =False, **kwargs) -> Union[int, str]: - """ Adds text. Text can have an optional label that will display to the right of the text. - - Args: - default_value (str, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - wrap (int, optional): Number of pixels from the start of the item until wrapping starts. - bullet (bool, optional): Places a bullet to the left of the text. - color (Union[List[int], Tuple[int, ...]], optional): Color of the text (rgba). - show_label (bool, optional): Displays the label to the right of the text. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_text(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, wrap=wrap, bullet=bullet, color=color, show_label=show_label, **kwargs) - -def add_text_point(x : float, y : float, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, source: Union[int, str] =0, show: bool =True, offset: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), vertical: bool =False, **kwargs) -> Union[int, str]: - """ Adds a label series to a plot. x and y can only have one elements each. - - Args: - x (float): - y (float): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - source (Union[int, str], optional): Overrides 'id' as value storage key. - show (bool, optional): Attempt to render widget. - offset (Union[List[float], Tuple[float, ...]], optional): Offset of the label, in pixels, relative to the coordinates. - vertical (bool, optional): - id (Union[int, str], optional): (deprecated) - x_offset (int, optional): (deprecated) Old way to set x offset of the label. Use `offset` argument instead. - y_offset (int, optional): (deprecated) Old way to set y offset of the label. Use `offset` argument instead. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'x_offset' in kwargs.keys(): - warnings.warn('x_offset keyword deprecated. See the new offset argument.', DeprecationWarning, 2) - - if 'y_offset' in kwargs.keys(): - warnings.warn('y_offset keyword deprecated. See the new offset argument.', DeprecationWarning, 2) - - return internal_dpg.add_text_point(x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, source=source, show=show, offset=offset, vertical=vertical, **kwargs) - -def add_texture_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =False, **kwargs) -> Union[int, str]: - """ Adds a dynamic texture. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_texture_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, **kwargs) - -def add_theme(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a theme. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - default_theme (bool, optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'default_theme' in kwargs.keys(): - - warnings.warn('default_theme keyword removed', DeprecationWarning, 2) - - kwargs.pop('default_theme', None) - - return internal_dpg.add_theme(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - -def add_theme_color(target : int =0, value : Union[List[int], Tuple[int, ...]] =(0, 0, 0, 255), *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, category: int =0, **kwargs) -> Union[int, str]: - """ Adds a theme color. - - Args: - target (int, optional): - value (Union[List[int], Tuple[int, ...]], optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - category (int, optional): Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_theme_color(target, value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, category=category, **kwargs) - -def add_theme_component(item_type : int =0, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, enabled_state: bool =True, **kwargs) -> Union[int, str]: - """ Adds a theme component. - - Args: - item_type (int, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - enabled_state (bool, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_theme_component(item_type, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, enabled_state=enabled_state, **kwargs) - -def add_theme_style(target : int =0, x : float =1.0, y : float =-1.0, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, category: int =0, **kwargs) -> Union[int, str]: - """ Adds a theme style. - - Args: - target (int, optional): - x (float, optional): - y (float, optional): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - category (int, optional): Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_theme_style(target, x, y, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, category=category, **kwargs) - -def add_time_picker(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', callback: Callable =None, drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_value: dict ={'hour': 14, 'min': 32, 'sec': 23}, hour24: bool =False, **kwargs) -> Union[int, str]: - """ Adds a time picker. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - callback (Callable, optional): Registers a callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_value (dict, optional): - hour24 (bool, optional): Show 24 hour clock instead of 12 hour. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_time_picker(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, callback=callback, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_value=default_value, hour24=hour24, **kwargs) - -def add_tooltip(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, delay: float =0.0, hide_on_activity: bool =False, **kwargs) -> Union[int, str]: - """ Adds a tooltip window. - - Args: - parent (Union[int, str]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - delay (float, optional): Activation delay: time, in seconds, during which the mouse should stay still in order to display the tooltip. May be zero for instant activation. - hide_on_activity (bool, optional): Hide the tooltip if the user has moved the mouse. If False, the tooltip will follow mouse pointer. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_tooltip(parent, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, delay=delay, hide_on_activity=hide_on_activity, **kwargs) - -def add_tree_node(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, before: Union[int, str] =0, payload_type: str ='$$DPG_PAYLOAD', drag_callback: Callable =None, drop_callback: Callable =None, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], filter_key: str ='', tracked: bool =False, track_offset: float =0.5, default_open: bool =False, open_on_double_click: bool =False, open_on_arrow: bool =False, leaf: bool =False, bullet: bool =False, selectable: bool =False, span_text_width: bool =False, span_full_width: bool =False, catch_nav_left: bool =False, lines: int =internal_dpg.mvTreeLines_None, **kwargs) -> Union[int, str]: - """ Adds a tree node to add items to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - payload_type (str, optional): Sender string type must be the same as the target for the target to run the payload_callback. - drag_callback (Callable, optional): Registers a drag callback for drag and drop. - drop_callback (Callable, optional): Registers a drop callback for drag and drop. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - filter_key (str, optional): Used by filter widget. - tracked (bool, optional): Scroll tracking - track_offset (float, optional): 0.0f:top, 0.5f:center, 1.0f:bottom - default_open (bool, optional): Sets the tree node open by default. - open_on_double_click (bool, optional): Need double-click to open node. - open_on_arrow (bool, optional): Only open when clicking on the arrow part. - leaf (bool, optional): No collapsing, no arrow (use as a convenience for leaf nodes). - bullet (bool, optional): Display a bullet instead of arrow. - selectable (bool, optional): Makes the tree selectable. - span_text_width (bool, optional): Makes hitbox and highlight only cover the label. - span_full_width (bool, optional): Extend hit box to the left-most and right-most edges (cover the indent area). - catch_nav_left (bool, optional): Keyboard navigation: left arrow within this node's children, if unhandled, moves focus to this node. When setting it to True on a node, better set it on all children nodes in the subtree as well, otherwise it might give unexpected navigation jumps. - lines (int, optional): Experimental. Draw lines connecting tree_node hierarchy. One of dpg.mvTreeLines constants. To work correctly, must be configured the same way in every tree node. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_tree_node(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, default_open=default_open, open_on_double_click=open_on_double_click, open_on_arrow=open_on_arrow, leaf=leaf, bullet=bullet, selectable=selectable, span_text_width=span_text_width, span_full_width=span_full_width, catch_nav_left=catch_nav_left, lines=lines, **kwargs) - -def add_value_registry(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, **kwargs) -> Union[int, str]: - """ Adds a value registry. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.add_value_registry(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, **kwargs) - -def add_viewport_drawlist(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, show: bool =True, filter_key: str ='', front: bool =True, **kwargs) -> Union[int, str]: - """ A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - show (bool, optional): Attempt to render widget. - filter_key (str, optional): Used by filter widget. - front (bool, optional): Draws to the front of the view port instead of the back. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_viewport_drawlist(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, show=show, filter_key=filter_key, front=front, **kwargs) - -def add_viewport_menu_bar(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, indent: int =-1, parent: Union[int, str] =0, show: bool =True, **kwargs) -> Union[int, str]: - """ Adds a menubar to the viewport. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - show (bool, optional): Attempt to render widget. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_viewport_menu_bar(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, show=show, **kwargs) - -def add_window(*, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, width: int =0, height: int =0, indent: int =-1, show: bool =True, pos: Union[List[int], Tuple[int, ...]] =[], min_size: Union[List[int], Tuple[int, ...]] =[100, 100], max_size: Union[List[int], Tuple[int, ...]] =[30000, 30000], menubar: bool =False, collapsed: bool =False, autosize: bool =False, no_resize: bool =False, unsaved_document: bool =False, no_title_bar: bool =False, no_move: bool =False, no_scrollbar: bool =False, no_collapse: bool =False, horizontal_scrollbar: bool =False, no_focus_on_appearing: bool =False, no_bring_to_front_on_focus: bool =False, no_close: bool =False, no_background: bool =False, modal: bool =False, popup: bool =False, no_saved_settings: bool =False, no_open_over_existing_popup: bool =True, no_scroll_with_mouse: bool =False, no_docking: bool =False, copy_contents_shortcut: bool =False, on_close: Callable =None, **kwargs) -> Union[int, str]: - """ Creates a new window for following items to be added to. - - Args: - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - width (int, optional): Width of the item. - height (int, optional): Height of the item. - indent (int, optional): Offsets the widget to the right the specified number multiplied by the indent style. - show (bool, optional): Attempt to render widget. - pos (Union[List[int], Tuple[int, ...]], optional): Places the item relative to window coordinates, [0,0] is top left. - min_size (Union[List[int], Tuple[int, ...]], optional): Minimum window size. - max_size (Union[List[int], Tuple[int, ...]], optional): Maximum window size. - menubar (bool, optional): Shows or hides the menubar. - collapsed (bool, optional): Collapse the window. - autosize (bool, optional): Autosized the window to fit it's items. - no_resize (bool, optional): Allows for the window size to be changed or fixed. - unsaved_document (bool, optional): Show a special marker if the document is not saved. - no_title_bar (bool, optional): Title name for the title bar of the window. - no_move (bool, optional): Allows for the window's position to be changed or fixed. - no_scrollbar (bool, optional): Disable scrollbars. (window can still scroll with mouse or programmatically) - no_collapse (bool, optional): Disable user collapsing window by double-clicking on it. - horizontal_scrollbar (bool, optional): Allow horizontal scrollbar to appear. (off by default) - no_focus_on_appearing (bool, optional): Disable taking focus when transitioning from hidden to visible state. - no_bring_to_front_on_focus (bool, optional): Disable bringing window to front when taking focus. (e.g. clicking on it or programmatically giving it focus) - no_close (bool, optional): Disable user closing the window by removing the close button. - no_background (bool, optional): Sets Background and border alpha to transparent. - modal (bool, optional): Fills area behind window according to the theme and disables user ability to interact with anything except the window. - popup (bool, optional): Fills area behind window according to the theme, removes title bar, collapse and close. Window can be closed by selecting area in the background behind the window. - no_saved_settings (bool, optional): Never load/save settings in .ini file. - no_open_over_existing_popup (bool, optional): Don't open if there's already a popup - no_scroll_with_mouse (bool, optional): Disable user vertically scrolling with mouse wheel. - no_docking (bool, optional): Disable docking of this window - copy_contents_shortcut (bool, optional): Experimental. If True, window contents can be copied to clipboard by pressing Ctrl+C. Might be useful for message boxes. - on_close (Callable, optional): Callback ran when window is closed. - id (Union[int, str], optional): (deprecated) - delay_search (bool, optional): (deprecated) This was used as an optimization hint but is not relevant anymore. - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'delay_search' in kwargs.keys(): - warnings.warn('delay_search keyword deprecated. ', DeprecationWarning, 2) - - return internal_dpg.add_window(label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, width=width, height=height, indent=indent, show=show, pos=pos, min_size=min_size, max_size=max_size, menubar=menubar, collapsed=collapsed, autosize=autosize, no_resize=no_resize, unsaved_document=unsaved_document, no_title_bar=no_title_bar, no_move=no_move, no_scrollbar=no_scrollbar, no_collapse=no_collapse, horizontal_scrollbar=horizontal_scrollbar, no_focus_on_appearing=no_focus_on_appearing, no_bring_to_front_on_focus=no_bring_to_front_on_focus, no_close=no_close, no_background=no_background, modal=modal, popup=popup, no_saved_settings=no_saved_settings, no_open_over_existing_popup=no_open_over_existing_popup, no_scroll_with_mouse=no_scroll_with_mouse, no_docking=no_docking, copy_contents_shortcut=copy_contents_shortcut, on_close=on_close, **kwargs) - -def apply_transform(item : Union[int, str], transform : Any, **kwargs) -> None: - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - item (Union[int, str]): Drawing node to apply transform to. - transform (Any): Transformation matrix. - Returns: - None - """ - - return internal_dpg.apply_transform(item, transform, **kwargs) - -def bind_colormap(item : Union[int, str], source : Union[int, str], **kwargs) -> None: - """ Sets the color map for widgets that accept it. - - Args: - item (Union[int, str]): item that the color map will be applied to - source (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - Returns: - None - """ - - return internal_dpg.bind_colormap(item, source, **kwargs) - -def bind_font(font : Union[int, str], **kwargs) -> Union[int, str]: - """ Binds a global font. - - Args: - font (Union[int, str]): - Returns: - Union[int, str] - """ - - return internal_dpg.bind_font(font, **kwargs) - -def bind_item_font(item : Union[int, str], font : Union[int, str], **kwargs) -> None: - """ Sets an item's font. - - Args: - item (Union[int, str]): - font (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_font(item, font, **kwargs) - -def bind_item_handler_registry(item : Union[int, str], handler_registry : Union[int, str], **kwargs) -> None: - """ Binds an item handler registry to an item. - - Args: - item (Union[int, str]): - handler_registry (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_handler_registry(item, handler_registry, **kwargs) - -def bind_item_theme(item : Union[int, str], theme : Union[int, str], **kwargs) -> None: - """ Binds a theme to an item. - - Args: - item (Union[int, str]): - theme (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_item_theme(item, theme, **kwargs) - -def bind_theme(theme : Union[int, str], **kwargs) -> None: - """ Binds a global theme. - - Args: - theme (Union[int, str]): - Returns: - None - """ - - return internal_dpg.bind_theme(theme, **kwargs) - -def capture_next_item(callback : Callable, *, user_data: Any =None, **kwargs) -> None: - """ Captures the next item. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - None - """ - - return internal_dpg.capture_next_item(callback, user_data=user_data, **kwargs) - -def clear_selected_links(node_editor : Union[int, str], **kwargs) -> None: - """ Clears a node editor's selected links. - - Args: - node_editor (Union[int, str]): - Returns: - None - """ - - return internal_dpg.clear_selected_links(node_editor, **kwargs) - -def clear_selected_nodes(node_editor : Union[int, str], **kwargs) -> None: - """ Clears a node editor's selected nodes. - - Args: - node_editor (Union[int, str]): - Returns: - None - """ - - return internal_dpg.clear_selected_nodes(node_editor, **kwargs) - -def create_context(**kwargs) -> None: - """ Creates the Dear PyGui context. - - Args: - Returns: - None - """ - - return internal_dpg.create_context(**kwargs) - -def create_fps_matrix(eye : Union[List[float], Tuple[float, ...]], pitch : float, yaw : float, **kwargs) -> Any: - """ New in 1.1. Create a 'first person shooter' matrix. - - Args: - eye (Union[List[float], Tuple[float, ...]]): eye position - pitch (float): pitch (in radians) - yaw (float): yaw (in radians) - Returns: - Any - """ - - return internal_dpg.create_fps_matrix(eye, pitch, yaw, **kwargs) - -def create_lookat_matrix(eye : Union[List[float], Tuple[float, ...]], target : Union[List[float], Tuple[float, ...]], up : Union[List[float], Tuple[float, ...]], **kwargs) -> Any: - """ New in 1.1. Creates a 'Look at matrix'. - - Args: - eye (Union[List[float], Tuple[float, ...]]): eye position - target (Union[List[float], Tuple[float, ...]]): target position - up (Union[List[float], Tuple[float, ...]]): up vector - Returns: - Any - """ - - return internal_dpg.create_lookat_matrix(eye, target, up, **kwargs) - -def create_orthographic_matrix(left : float, right : float, bottom : float, top : float, zNear : float, zFar : float, **kwargs) -> Any: - """ New in 1.1. Creates an orthographic matrix. - - Args: - left (float): left plane - right (float): right plane - bottom (float): bottom plane - top (float): top plane - zNear (float): Near clipping plane. - zFar (float): Far clipping plane. - Returns: - Any - """ - - return internal_dpg.create_orthographic_matrix(left, right, bottom, top, zNear, zFar, **kwargs) - -def create_perspective_matrix(fov : float, aspect : float, zNear : float, zFar : float, **kwargs) -> Any: - """ New in 1.1. Creates a perspective matrix. - - Args: - fov (float): Field of view (in radians) - aspect (float): Aspect ratio (width/height) - zNear (float): Near clipping plane. - zFar (float): Far clipping plane. - Returns: - Any - """ - - return internal_dpg.create_perspective_matrix(fov, aspect, zNear, zFar, **kwargs) - -def create_rotation_matrix(angle : float, axis : Union[List[float], Tuple[float, ...]], **kwargs) -> Any: - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - angle (float): angle to rotate - axis (Union[List[float], Tuple[float, ...]]): axis to rotate around - Returns: - Any - """ - - return internal_dpg.create_rotation_matrix(angle, axis, **kwargs) - -def create_scale_matrix(scales : Union[List[float], Tuple[float, ...]], **kwargs) -> Any: - """ New in 1.1. Applies a transformation matrix to a layer. - - Args: - scales (Union[List[float], Tuple[float, ...]]): scale values per axis - Returns: - Any - """ - - return internal_dpg.create_scale_matrix(scales, **kwargs) - -def create_translation_matrix(translation : Union[List[float], Tuple[float, ...]], **kwargs) -> Any: - """ New in 1.1. Creates a translation matrix. - - Args: - translation (Union[List[float], Tuple[float, ...]]): translation vector - Returns: - Any - """ - - return internal_dpg.create_translation_matrix(translation, **kwargs) - -def create_viewport(*, title: str ='Dear PyGui', small_icon: str ='', large_icon: str ='', width: int =1280, height: int =800, x_pos: int =100, y_pos: int =100, min_width: int =250, max_width: int =10000, min_height: int =250, max_height: int =10000, resizable: bool =True, vsync: bool =True, always_on_top: bool =False, decorated: bool =True, clear_color: Union[List[float], Tuple[float, ...]] =(0, 0, 0, 255), disable_close: bool =False, **kwargs) -> None: - """ Creates a viewport. Viewports are required. - - Args: - title (str, optional): Sets the title of the viewport. - small_icon (str, optional): Sets the small icon that is found in the viewport's decorator bar. Must be ***.ico on windows and either ***.ico or ***.png on mac. - large_icon (str, optional): Sets the large icon that is found in the task bar while the app is running. Must be ***.ico on windows and either ***.ico or ***.png on mac. - width (int, optional): Sets the width of the drawable space on the viewport. Does not inclue the border. - height (int, optional): Sets the height of the drawable space on the viewport. Does not inclue the border or decorator bar. - x_pos (int, optional): Sets x position the viewport will be drawn in screen coordinates. - y_pos (int, optional): Sets y position the viewport will be drawn in screen coordinates. - min_width (int, optional): Applies a minimuim limit to the width of the viewport. - max_width (int, optional): Applies a maximum limit to the width of the viewport. - min_height (int, optional): Applies a minimuim limit to the height of the viewport. - max_height (int, optional): Applies a maximum limit to the height of the viewport. - resizable (bool, optional): Enables and Disables user ability to resize the viewport. - vsync (bool, optional): Enables and Disables the renderloop vsync limit. vsync frame value is set by refresh rate of display. - always_on_top (bool, optional): Forces the viewport to always be drawn ontop of all other viewports. - decorated (bool, optional): Enabled and disabled the decorator bar at the top of the viewport. - clear_color (Union[List[float], Tuple[float, ...]], optional): Sets the color of the back of the viewport. - disable_close (bool, optional): Disables the viewport close button. can be used with set_exit_callback - Returns: - None - """ - - return internal_dpg.create_viewport(title=title, small_icon=small_icon, large_icon=large_icon, width=width, height=height, x_pos=x_pos, y_pos=y_pos, min_width=min_width, max_width=max_width, min_height=min_height, max_height=max_height, resizable=resizable, vsync=vsync, always_on_top=always_on_top, decorated=decorated, clear_color=clear_color, disable_close=disable_close, **kwargs) - -def delete_item(item : Union[int, str], *, children_only: bool =False, slot: int =-1, **kwargs) -> None: - """ Deletes an item.. - - Args: - item (Union[int, str]): - children_only (bool, optional): - slot (int, optional): - Returns: - None - """ - - return internal_dpg.delete_item(item, children_only=children_only, slot=slot, **kwargs) - -def destroy_context(**kwargs) -> None: - """ Destroys the Dear PyGui context. - - Args: - Returns: - None - """ - - return internal_dpg.destroy_context(**kwargs) - -def does_alias_exist(alias : str, **kwargs) -> bool: - """ Checks if an alias exist. - - Args: - alias (str): - Returns: - bool - """ - - return internal_dpg.does_alias_exist(alias, **kwargs) - -def does_item_exist(item : Union[int, str], **kwargs) -> bool: - """ Checks if an item exist.. - - Args: - item (Union[int, str]): - Returns: - bool - """ - - return internal_dpg.does_item_exist(item, **kwargs) - -def draw_arrow(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), thickness: float =1.0, size: int =4, **kwargs) -> Union[int, str]: - """ Adds an arrow. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): Arrow tip. - p2 (Union[List[float], Tuple[float, ...]]): Arrow tail. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - size (int, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_arrow(p1, p2, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, thickness=thickness, size=size, **kwargs) - -def draw_bezier_cubic(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), thickness: float =1.0, segments: int =0, **kwargs) -> Union[int, str]: - """ Adds a cubic bezier curve. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): First point in curve. - p2 (Union[List[float], Tuple[float, ...]]): Second point in curve. - p3 (Union[List[float], Tuple[float, ...]]): Third point in curve. - p4 (Union[List[float], Tuple[float, ...]]): Fourth point in curve. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_bezier_cubic(p1, p2, p3, p4, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, thickness=thickness, segments=segments, **kwargs) - -def draw_bezier_quadratic(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), thickness: float =1.0, segments: int =0, **kwargs) -> Union[int, str]: - """ Adds a quadratic bezier curve. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): First point in curve. - p2 (Union[List[float], Tuple[float, ...]]): Second point in curve. - p3 (Union[List[float], Tuple[float, ...]]): Third point in curve. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_bezier_quadratic(p1, p2, p3, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, thickness=thickness, segments=segments, **kwargs) - -def draw_circle(center : Union[List[float], Tuple[float, ...]], radius : float, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, segments: int =0, **kwargs) -> Union[int, str]: - """ Adds a circle - - Args: - center (Union[List[float], Tuple[float, ...]]): - radius (float): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate circle. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_circle(center, radius, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, thickness=thickness, segments=segments, **kwargs) - -def draw_ellipse(pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, segments: int =32, **kwargs) -> Union[int, str]: - """ Adds an ellipse. - - Args: - pmin (Union[List[float], Tuple[float, ...]]): Min point of bounding rectangle. - pmax (Union[List[float], Tuple[float, ...]]): Max point of bounding rectangle. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - segments (int, optional): Number of segments to approximate bezier curve. - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_ellipse(pmin, pmax, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, thickness=thickness, segments=segments, **kwargs) - -def draw_image(texture_tag : Union[int, str], pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, uv_min: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), uv_max: Union[List[float], Tuple[float, ...]] =(1.0, 1.0), color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), **kwargs) -> Union[int, str]: - """ Adds an image (for a drawing). - - Args: - texture_tag (Union[int, str]): - pmin (Union[List[float], Tuple[float, ...]]): Point of to start drawing texture. - pmax (Union[List[float], Tuple[float, ...]]): Point to complete drawing texture. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - uv_min (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv_max (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_image(texture_tag, pmin, pmax, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, uv_min=uv_min, uv_max=uv_max, color=color, **kwargs) - -def draw_image_quad(texture_tag : Union[int, str], p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, uv1: Union[List[float], Tuple[float, ...]] =(0.0, 0.0), uv2: Union[List[float], Tuple[float, ...]] =(1.0, 0.0), uv3: Union[List[float], Tuple[float, ...]] =(1.0, 1.0), uv4: Union[List[float], Tuple[float, ...]] =(0.0, 1.0), color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), **kwargs) -> Union[int, str]: - """ Adds an image (for a drawing). - - Args: - texture_tag (Union[int, str]): - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - p4 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - uv1 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv2 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv3 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - uv4 (Union[List[float], Tuple[float, ...]], optional): Normalized coordinates on texture that will be drawn. - color (Union[List[int], Tuple[int, ...]], optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_image_quad(texture_tag, p1, p2, p3, p4, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, uv1=uv1, uv2=uv2, uv3=uv3, uv4=uv4, color=color, **kwargs) - -def draw_line(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), thickness: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a line. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): Start of line. - p2 (Union[List[float], Tuple[float, ...]]): End of line. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_line(p1, p2, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, thickness=thickness, **kwargs) - -def draw_polygon(points : List[List[float]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a polygon. - - Args: - points (List[List[float]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_polygon(points, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, thickness=thickness, **kwargs) - -def draw_polyline(points : List[List[float]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, closed: bool =False, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), thickness: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a polyline. - - Args: - points (List[List[float]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - closed (bool, optional): Will close the polyline by returning to the first point. - color (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_polyline(points, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, closed=closed, color=color, thickness=thickness, **kwargs) - -def draw_quad(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], p4 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a quad. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - p4 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_quad(p1, p2, p3, p4, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, thickness=thickness, **kwargs) - -def draw_rectangle(pmin : Union[List[float], Tuple[float, ...]], pmax : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), multicolor: bool =False, rounding: float =0.0, thickness: float =1.0, corner_colors: Any =None, **kwargs) -> Union[int, str]: - """ Adds a rectangle. - - Args: - pmin (Union[List[float], Tuple[float, ...]]): Min point of bounding rectangle. - pmax (Union[List[float], Tuple[float, ...]]): Max point of bounding rectangle. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - multicolor (bool, optional): - rounding (float, optional): Number of pixels of the radius that will round the corners of the rectangle. Note: doesn't work with multicolor - thickness (float, optional): - corner_colors (Any, optional): Corner colors in a list, starting with upper-left and going clockwise: (upper-left, upper-right, bottom-right, bottom-left). 'multicolor' must be set to 'True'. - id (Union[int, str], optional): (deprecated) - color_upper_left (Union[List[int], Tuple[int, ...]], optional): (deprecated) Use corner_colors instead - color_upper_right (Union[List[int], Tuple[int, ...]], optional): (deprecated) Use corner_colors instead - color_bottom_right (Union[List[int], Tuple[int, ...]], optional): (deprecated) Use corner_colors instead - color_bottom_left (Union[List[int], Tuple[int, ...]], optional): (deprecated) Use corner_colors instead - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - if 'color_upper_left' in kwargs.keys(): - warnings.warn('color_upper_left keyword deprecated. Use corner_colors instead.', DeprecationWarning, 2) - - if 'color_upper_right' in kwargs.keys(): - warnings.warn('color_upper_right keyword deprecated. Use corner_colors instead.', DeprecationWarning, 2) - - if 'color_bottom_right' in kwargs.keys(): - warnings.warn('color_bottom_right keyword deprecated. Use corner_colors instead.', DeprecationWarning, 2) - - if 'color_bottom_left' in kwargs.keys(): - warnings.warn('color_bottom_left keyword deprecated. Use corner_colors instead.', DeprecationWarning, 2) - - return internal_dpg.draw_rectangle(pmin, pmax, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, multicolor=multicolor, rounding=rounding, thickness=thickness, corner_colors=corner_colors, **kwargs) - -def draw_text(pos : Union[List[float], Tuple[float, ...]], text : str, *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), size: float =10.0, **kwargs) -> Union[int, str]: - """ Adds text (drawlist). - - Args: - pos (Union[List[float], Tuple[float, ...]]): Top left point of bounding text rectangle. - text (str): Text to draw. - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - size (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_text(pos, text, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, size=size, **kwargs) - -def draw_triangle(p1 : Union[List[float], Tuple[float, ...]], p2 : Union[List[float], Tuple[float, ...]], p3 : Union[List[float], Tuple[float, ...]], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, parent: Union[int, str] =0, before: Union[int, str] =0, show: bool =True, color: Union[List[int], Tuple[int, ...]] =(255, 255, 255, 255), fill: Union[List[int], Tuple[int, ...]] =(0, 0, 0, -255), thickness: float =1.0, **kwargs) -> Union[int, str]: - """ Adds a triangle. - - Args: - p1 (Union[List[float], Tuple[float, ...]]): - p2 (Union[List[float], Tuple[float, ...]]): - p3 (Union[List[float], Tuple[float, ...]]): - label (str, optional): Overrides 'name' as label. - user_data (Any, optional): User data for callbacks - use_internal_label (bool, optional): Use generated internal label instead of user specified (appends ### uuid). - tag (Union[int, str], optional): Unique id used to programmatically refer to the item.If label is unused this will be the label. - parent (Union[int, str], optional): Parent to add this item to. (runtime adding) - before (Union[int, str], optional): This item will be displayed before the specified item in the parent. - show (bool, optional): Attempt to render widget. - color (Union[List[int], Tuple[int, ...]], optional): - fill (Union[List[int], Tuple[int, ...]], optional): - thickness (float, optional): - id (Union[int, str], optional): (deprecated) - Returns: - Union[int, str] - """ - - if 'id' in kwargs.keys(): - warnings.warn('id keyword renamed to tag', DeprecationWarning, 2) - tag=kwargs['id'] - - return internal_dpg.draw_triangle(p1, p2, p3, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, parent=parent, before=before, show=show, color=color, fill=fill, thickness=thickness, **kwargs) - -def empty_container_stack(**kwargs) -> None: - """ Emptyes the container stack. - - Args: - Returns: - None - """ - - return internal_dpg.empty_container_stack(**kwargs) - -def fit_axis_data(axis : Union[int, str], **kwargs) -> None: - """ Sets the axis boundaries max/min in the data series currently on the plot. - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.fit_axis_data(axis, **kwargs) - -def focus_item(item : Union[int, str], **kwargs) -> None: - """ Focuses an item. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.focus_item(item, **kwargs) - -def generate_uuid(**kwargs) -> Union[int, str]: - """ Generate a new UUID. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.generate_uuid(**kwargs) - -def get_active_window(**kwargs) -> Union[int, str]: - """ Returns the active window. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.get_active_window(**kwargs) - -def get_alias_id(alias : str, **kwargs) -> Union[int, str]: - """ Returns the ID associated with an alias. - - Args: - alias (str): - Returns: - Union[int, str] - """ - - return internal_dpg.get_alias_id(alias, **kwargs) - -def get_aliases(**kwargs) -> Union[List[str], Tuple[str, ...]]: - """ Returns all aliases. - - Args: - Returns: - Union[List[str], Tuple[str, ...]] - """ - - return internal_dpg.get_aliases(**kwargs) - -def get_all_items(**kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns all items. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_all_items(**kwargs) - -def get_app_configuration(**kwargs) -> dict: - """ Returns app configuration. - - Args: - Returns: - dict - """ - - return internal_dpg.get_app_configuration(**kwargs) - -def get_axis_limits(axis : Union[int, str], **kwargs) -> Union[List[float], Tuple[float, ...]]: - """ Get the specified axis limits. - - Args: - axis (Union[int, str]): - Returns: - Union[List[float], Tuple[float, ...]] - """ - - return internal_dpg.get_axis_limits(axis, **kwargs) - -def get_callback_queue(**kwargs) -> Any: - """ New in 1.2. Returns and clears callback queue. - - Args: - Returns: - Any - """ - - return internal_dpg.get_callback_queue(**kwargs) - -def get_clipboard_text(**kwargs) -> str: - """ New in 1.3. Gets the clipboard text. - - Args: - Returns: - str - """ - - return internal_dpg.get_clipboard_text(**kwargs) - -def get_colormap_color(colormap : Union[int, str], index : int, **kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns a color from a colormap given an index >= 0. (ex. 0 will be the first color in the color list of the color map) Modulo will be performed against the number of items in the color list. - - Args: - colormap (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - index (int): Desired position of the color in the colors list value of the colormap being quiered - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_colormap_color(colormap, index, **kwargs) - -def get_delta_time(**kwargs) -> float: - """ Returns time since last frame. - - Args: - Returns: - float - """ - - return internal_dpg.get_delta_time(**kwargs) - -def get_drawing_mouse_pos(**kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns mouse position in drawing. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_drawing_mouse_pos(**kwargs) - -def get_file_dialog_info(file_dialog : Union[int, str], **kwargs) -> dict: - """ Returns information related to the file dialog. Typically used while the file dialog is in use to query data about the state or info related to the file dialog. - - Args: - file_dialog (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_file_dialog_info(file_dialog, **kwargs) - -def get_focused_item(**kwargs) -> Union[int, str]: - """ Returns the item currently having focus. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.get_focused_item(**kwargs) - -def get_frame_count(**kwargs) -> int: - """ Returns frame count. - - Args: - Returns: - int - """ - - return internal_dpg.get_frame_count(**kwargs) - -def get_frame_rate(**kwargs) -> float: - """ Returns the average frame rate across 120 frames. - - Args: - Returns: - float - """ - - return internal_dpg.get_frame_rate(**kwargs) - -def get_global_font_scale(**kwargs) -> float: - """ Returns global font scale. - - Args: - Returns: - float - """ - - return internal_dpg.get_global_font_scale(**kwargs) - -def get_item_alias(item : Union[int, str], **kwargs) -> str: - """ Returns an item's alias. - - Args: - item (Union[int, str]): - Returns: - str - """ - - return internal_dpg.get_item_alias(item, **kwargs) - -def get_item_configuration(item : Union[int, str], **kwargs) -> dict: - """ Returns an item's configuration. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_configuration(item, **kwargs) - -def get_item_info(item : Union[int, str], **kwargs) -> dict: - """ Returns an item's information. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_info(item, **kwargs) - -def get_item_state(item : Union[int, str], **kwargs) -> dict: - """ Returns an item's state. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_item_state(item, **kwargs) - -def get_item_types(**kwargs) -> dict: - """ Returns an item types. - - Args: - Returns: - dict - """ - - return internal_dpg.get_item_types(**kwargs) - -def get_mouse_drag_delta(**kwargs) -> float: - """ Returns mouse drag delta. - - Args: - Returns: - float - """ - - return internal_dpg.get_mouse_drag_delta(**kwargs) - -def get_mouse_pos(*, local: bool =True, **kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns mouse position. - - Args: - local (bool, optional): - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_mouse_pos(local=local, **kwargs) - -def get_platform(**kwargs) -> int: - """ New in 1.6. Returns platform constant. - - Args: - Returns: - int - """ - - return internal_dpg.get_platform(**kwargs) - -def get_plot_mouse_pos(**kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns mouse position in plot. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_plot_mouse_pos(**kwargs) - -def get_plot_query_rects(plot : Union[int, str], **kwargs) -> List[List[float]]: - """ Returns the query rects of the plot. Returns an array of array containing the top-left coordinates and bottom-right coordinates of the plot area. - - Args: - plot (Union[int, str]): - Returns: - List[List[float]] - """ - - return internal_dpg.get_plot_query_rects(plot, **kwargs) - -def get_selected_links(node_editor : Union[int, str], **kwargs) -> List[List[str]]: - """ Returns a node editor's selected links. - - Args: - node_editor (Union[int, str]): - Returns: - List[List[str]] - """ - - return internal_dpg.get_selected_links(node_editor, **kwargs) - -def get_selected_nodes(node_editor : Union[int, str], **kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns a node editor's selected nodes. - - Args: - node_editor (Union[int, str]): - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_selected_nodes(node_editor, **kwargs) - -def get_text_size(text : str, *, wrap_width: float =-1.0, font: Union[int, str] =0, **kwargs) -> Union[List[float], Tuple[float, ...]]: - """ Returns width/height of text with specified font (must occur after 1st frame). - - Args: - text (str): - wrap_width (float, optional): Wrap width to use (-1.0 turns wrap off). - font (Union[int, str], optional): Font to use. - Returns: - Union[List[float], Tuple[float, ...]] - """ - - return internal_dpg.get_text_size(text, wrap_width=wrap_width, font=font, **kwargs) - -def get_total_time(**kwargs) -> float: - """ Returns total time since Dear PyGui has started. - - Args: - Returns: - float - """ - - return internal_dpg.get_total_time(**kwargs) - -def get_value(item : Union[int, str], **kwargs) -> Any: - """ Returns an item's value. - - Args: - item (Union[int, str]): - Returns: - Any - """ - - return internal_dpg.get_value(item, **kwargs) - -def get_values(items : Union[List[int], Tuple[int, ...]], **kwargs) -> Any: - """ Returns values of a list of items. - - Args: - items (Union[List[int], Tuple[int, ...]]): - Returns: - Any - """ - - return internal_dpg.get_values(items, **kwargs) - -def get_viewport_configuration(item : Union[int, str], **kwargs) -> dict: - """ Returns a viewport's configuration. - - Args: - item (Union[int, str]): - Returns: - dict - """ - - return internal_dpg.get_viewport_configuration(item, **kwargs) - -def get_windows(**kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns all windows. - - Args: - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.get_windows(**kwargs) - -def get_x_scroll(item : Union[int, str], **kwargs) -> float: - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_x_scroll(item, **kwargs) - -def get_x_scroll_max(item : Union[int, str], **kwargs) -> float: - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_x_scroll_max(item, **kwargs) - -def get_y_scroll(item : Union[int, str], **kwargs) -> float: - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_y_scroll(item, **kwargs) - -def get_y_scroll_max(item : Union[int, str], **kwargs) -> float: - """ Undocumented - - Args: - item (Union[int, str]): - Returns: - float - """ - - return internal_dpg.get_y_scroll_max(item, **kwargs) - -def highlight_table_cell(table : Union[int, str], row : int, column : int, color : Union[List[int], Tuple[int, ...]], **kwargs) -> None: - """ Highlight specified table cell. - - Args: - table (Union[int, str]): - row (int): - column (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_cell(table, row, column, color, **kwargs) - -def highlight_table_column(table : Union[int, str], column : int, color : Union[List[int], Tuple[int, ...]], **kwargs) -> None: - """ Highlight specified table column. - - Args: - table (Union[int, str]): - column (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_column(table, column, color, **kwargs) - -def highlight_table_row(table : Union[int, str], row : int, color : Union[List[int], Tuple[int, ...]], **kwargs) -> None: - """ Highlight specified table row. - - Args: - table (Union[int, str]): - row (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.highlight_table_row(table, row, color, **kwargs) - -def is_dearpygui_running(**kwargs) -> bool: - """ Checks if Dear PyGui is running - - Args: - Returns: - bool - """ - - return internal_dpg.is_dearpygui_running(**kwargs) - -def is_key_down(key : int, **kwargs) -> bool: - """ Checks if key is down. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_down(key, **kwargs) - -def is_key_pressed(key : int, **kwargs) -> bool: - """ Checks if key is pressed. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_pressed(key, **kwargs) - -def is_key_released(key : int, **kwargs) -> bool: - """ Checks if key is released. - - Args: - key (int): - Returns: - bool - """ - - return internal_dpg.is_key_released(key, **kwargs) - -def is_mouse_button_clicked(button : int, **kwargs) -> bool: - """ Checks if mouse button is clicked. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_clicked(button, **kwargs) - -def is_mouse_button_double_clicked(button : int, **kwargs) -> bool: - """ Checks if mouse button is double clicked. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_double_clicked(button, **kwargs) - -def is_mouse_button_down(button : int, **kwargs) -> bool: - """ Checks if mouse button is down. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_down(button, **kwargs) - -def is_mouse_button_dragging(button : int, threshold : float, **kwargs) -> bool: - """ Checks if mouse button is down and dragging. - - Args: - button (int): - threshold (float): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_dragging(button, threshold, **kwargs) - -def is_mouse_button_released(button : int, **kwargs) -> bool: - """ Checks if mouse button is released. - - Args: - button (int): - Returns: - bool - """ - - return internal_dpg.is_mouse_button_released(button, **kwargs) - -def is_table_cell_highlighted(table : Union[int, str], row : int, column : int, **kwargs) -> bool: - """ Checks if a table cell is highlighted. - - Args: - table (Union[int, str]): - row (int): - column (int): - Returns: - bool - """ - - return internal_dpg.is_table_cell_highlighted(table, row, column, **kwargs) - -def is_table_column_highlighted(table : Union[int, str], column : int, **kwargs) -> bool: - """ Checks if a table column is highlighted. - - Args: - table (Union[int, str]): - column (int): - Returns: - bool - """ - - return internal_dpg.is_table_column_highlighted(table, column, **kwargs) - -def is_table_row_highlighted(table : Union[int, str], row : int, **kwargs) -> bool: - """ Checks if a table row is highlighted. - - Args: - table (Union[int, str]): - row (int): - Returns: - bool - """ - - return internal_dpg.is_table_row_highlighted(table, row, **kwargs) - -def is_viewport_ok(**kwargs) -> bool: - """ Checks if a viewport has been created and shown. - - Args: - Returns: - bool - """ - - return internal_dpg.is_viewport_ok(**kwargs) - -def last_container(**kwargs) -> Union[int, str]: - """ Returns the last container item added. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_container(**kwargs) - -def last_item(**kwargs) -> Union[int, str]: - """ Returns the last item added. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_item(**kwargs) - -def last_root(**kwargs) -> Union[int, str]: - """ Returns the last root added (registry or window). - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.last_root(**kwargs) - -def load_image(file : str, *, gamma: float =1.0, gamma_scale_factor: float =1.0, **kwargs) -> Any: - """ Loads an image. Returns width, height, channels, mvBuffer - - Args: - file (str): - gamma (float, optional): Gamma correction factor. (default is 1.0 to avoid automatic gamma correction on loading. - gamma_scale_factor (float, optional): Gamma scale factor. - Returns: - Any - """ - - return internal_dpg.load_image(file, gamma=gamma, gamma_scale_factor=gamma_scale_factor, **kwargs) - -def lock_mutex(**kwargs) -> None: - """ Locks render thread mutex. - - Args: - Returns: - None - """ - - return internal_dpg.lock_mutex(**kwargs) - -def maximize_viewport(**kwargs) -> None: - """ Maximizes the viewport. - - Args: - Returns: - None - """ - - return internal_dpg.maximize_viewport(**kwargs) - -def minimize_viewport(**kwargs) -> None: - """ Minimizes a viewport. - - Args: - Returns: - None - """ - - return internal_dpg.minimize_viewport(**kwargs) - -def move_item(item : Union[int, str], *, parent: Union[int, str] =0, before: Union[int, str] =0, **kwargs) -> None: - """ Moves an item to a new location. - - Args: - item (Union[int, str]): - parent (Union[int, str], optional): - before (Union[int, str], optional): - Returns: - None - """ - - return internal_dpg.move_item(item, parent=parent, before=before, **kwargs) - -def move_item_down(item : Union[int, str], **kwargs) -> None: - """ Moves an item down. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.move_item_down(item, **kwargs) - -def move_item_up(item : Union[int, str], **kwargs) -> None: - """ Moves an item up. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.move_item_up(item, **kwargs) - -def output_frame_buffer(file : str ='', *, callback: Callable =None, **kwargs) -> Any: - """ Outputs frame buffer as a png if file is specified or through the second argument of a callback if specified. Render loop must have been started. - - Args: - file (str, optional): - callback (Callable, optional): Callback will return framebuffer as an array through the second arg. - Returns: - Any - """ - - return internal_dpg.output_frame_buffer(file, callback=callback, **kwargs) - -def pop_container_stack(**kwargs) -> Union[int, str]: - """ Pops the top item off the parent stack and return its ID. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.pop_container_stack(**kwargs) - -def push_container_stack(item : Union[int, str], **kwargs) -> bool: - """ Pushes an item onto the container stack. - - Args: - item (Union[int, str]): - Returns: - bool - """ - - return internal_dpg.push_container_stack(item, **kwargs) - -def remove_alias(alias : str, **kwargs) -> None: - """ Removes an alias. - - Args: - alias (str): - Returns: - None - """ - - return internal_dpg.remove_alias(alias, **kwargs) - -def render_dearpygui_frame(**kwargs) -> None: - """ Render a single Dear PyGui frame. - - Args: - Returns: - None - """ - - return internal_dpg.render_dearpygui_frame(**kwargs) - -def reorder_items(container : Union[int, str], slot : int, new_order : Union[List[int], Tuple[int, ...]], **kwargs) -> None: - """ Reorders an item's children. - - Args: - container (Union[int, str]): - slot (int): - new_order (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.reorder_items(container, slot, new_order, **kwargs) - -def reset_axis_limits_constraints(axis : Union[int, str], **kwargs) -> None: - """ Remove an axis' limits constraints - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_limits_constraints(axis, **kwargs) - -def reset_axis_ticks(axis : Union[int, str], **kwargs) -> None: - """ Removes the manually set axis ticks and applies the default axis ticks - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_ticks(axis, **kwargs) - -def reset_axis_zoom_constraints(axis : Union[int, str], **kwargs) -> None: - """ Remove an axis' zoom constraints - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_axis_zoom_constraints(axis, **kwargs) - -def reset_pos(item : Union[int, str], **kwargs) -> None: - """ Resets an item's position after using 'set_item_pos'. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.reset_pos(item, **kwargs) - -def sample_colormap(colormap : Union[int, str], t : float, **kwargs) -> Union[List[int], Tuple[int, ...]]: - """ Returns a color from a colormap given t between 0.0-1.0. - - Args: - colormap (Union[int, str]): The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_*** - t (float): Value of the colormap to sample between 0.0-1.0 - Returns: - Union[List[int], Tuple[int, ...]] - """ - - return internal_dpg.sample_colormap(colormap, t, **kwargs) - -def save_image(file : str, width : int, height : int, data : Any, *, components: int =4, quality: int =50, **kwargs) -> None: - """ Saves an image. Possible formats: png, bmp, tga, hdr, jpg. - - Args: - file (str): - width (int): - height (int): - data (Any): - components (int, optional): Number of components (1-4). Default of 4. - quality (int, optional): Stride in bytes (only used for jpg). - Returns: - None - """ - - return internal_dpg.save_image(file, width, height, data, components=components, quality=quality, **kwargs) - -def save_init_file(file : str, **kwargs) -> None: - """ Save dpg.ini file. - - Args: - file (str): - Returns: - None - """ - - return internal_dpg.save_init_file(file, **kwargs) - -def set_axis_limits(axis : Union[int, str], ymin : float, ymax : float, **kwargs) -> None: - """ Sets limits on the axis for pan and zoom. - - Args: - axis (Union[int, str]): - ymin (float): - ymax (float): - Returns: - None - """ - - return internal_dpg.set_axis_limits(axis, ymin, ymax, **kwargs) - -def set_axis_limits_auto(axis : Union[int, str], **kwargs) -> None: - """ Removes all limits on specified axis. - - Args: - axis (Union[int, str]): - Returns: - None - """ - - return internal_dpg.set_axis_limits_auto(axis, **kwargs) - -def set_axis_limits_constraints(axis : Union[int, str], vmin : float, vmax : float, **kwargs) -> None: - """ Sets an axis' limits constraints so that users can't pan beyond a min or max value - - Args: - axis (Union[int, str]): - vmin (float): - vmax (float): - Returns: - None - """ - - return internal_dpg.set_axis_limits_constraints(axis, vmin, vmax, **kwargs) - -def set_axis_ticks(axis : Union[int, str], label_pairs : Any, **kwargs) -> None: - """ Replaces axis ticks with 'label_pairs' argument. - - Args: - axis (Union[int, str]): - label_pairs (Any): Tuples of label and value in the form '((label, axis_value), (label, axis_value), ...)' - Returns: - None - """ - - return internal_dpg.set_axis_ticks(axis, label_pairs, **kwargs) - -def set_axis_zoom_constraints(axis : Union[int, str], vmin : float, vmax : float, **kwargs) -> None: - """ Sets an axis' zoom constraints so that users can't zoom beyond a min or max value - - Args: - axis (Union[int, str]): - vmin (float): - vmax (float): - Returns: - None - """ - - return internal_dpg.set_axis_zoom_constraints(axis, vmin, vmax, **kwargs) - -def set_clip_space(item : Union[int, str], top_left_x : float, top_left_y : float, width : float, height : float, min_depth : float, max_depth : float, **kwargs) -> None: - """ New in 1.1. Set the clip space for depth clipping and 'viewport' transformation. - - Args: - item (Union[int, str]): draw layer to set clip space - top_left_x (float): angle to rotate - top_left_y (float): angle to rotate - width (float): angle to rotate - height (float): angle to rotate - min_depth (float): angle to rotate - max_depth (float): angle to rotate - Returns: - None - """ - - return internal_dpg.set_clip_space(item, top_left_x, top_left_y, width, height, min_depth, max_depth, **kwargs) - -def set_clipboard_text(text : str, **kwargs) -> None: - """ New in 1.3. Sets the clipboard text. - - Args: - text (str): - Returns: - None - """ - - return internal_dpg.set_clipboard_text(text, **kwargs) - -def set_exit_callback(callback : Callable, *, user_data: Any =None, **kwargs) -> str: - """ Sets a callback to run on last frame. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_exit_callback(callback, user_data=user_data, **kwargs) - -def set_frame_callback(frame : int, callback : Callable, *, user_data: Any =None, **kwargs) -> str: - """ Sets a callback to run on first frame. - - Args: - frame (int): - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_frame_callback(frame, callback, user_data=user_data, **kwargs) - -def set_global_font_scale(scale : float, **kwargs) -> None: - """ Sets global font scale. - - Args: - scale (float): - Returns: - None - """ - - return internal_dpg.set_global_font_scale(scale, **kwargs) - -def set_item_alias(item : Union[int, str], alias : str, **kwargs) -> None: - """ Sets an item's alias. - - Args: - item (Union[int, str]): - alias (str): - Returns: - None - """ - - return internal_dpg.set_item_alias(item, alias, **kwargs) - -def set_item_children(item : Union[int, str], source : Union[int, str], slot : int, **kwargs) -> None: - """ Sets an item's children. - - Args: - item (Union[int, str]): - source (Union[int, str]): - slot (int): - Returns: - None - """ - - return internal_dpg.set_item_children(item, source, slot, **kwargs) - -def set_primary_window(window : Union[int, str], value : bool =True, **kwargs) -> None: - """ Sets the primary window. - - Args: - window (Union[int, str]): - value (bool, optional): True to select this window as primary, False to make it a regular window (without any primary window). Only one window at a time can be primary. - Returns: - None - """ - - return internal_dpg.set_primary_window(window, value, **kwargs) - -def set_table_row_color(table : Union[int, str], row : int, color : Union[List[int], Tuple[int, ...]], **kwargs) -> None: - """ Set table row color. - - Args: - table (Union[int, str]): - row (int): - color (Union[List[int], Tuple[int, ...]]): - Returns: - None - """ - - return internal_dpg.set_table_row_color(table, row, color, **kwargs) - -def set_value(item : Union[int, str], value : Any, **kwargs) -> None: - """ Set's an item's value. - - Args: - item (Union[int, str]): - value (Any): - Returns: - None - """ - - return internal_dpg.set_value(item, value, **kwargs) - -def set_viewport_resize_callback(callback : Callable, *, user_data: Any =None, **kwargs) -> str: - """ Sets a callback to run on viewport resize. - - Args: - callback (Callable): - user_data (Any, optional): New in 1.3. Optional user data to send to the callback - Returns: - str - """ - - return internal_dpg.set_viewport_resize_callback(callback, user_data=user_data, **kwargs) - -def set_x_scroll(item : Union[int, str], value : float, *, when: int =internal_dpg.mvSetScrollFlags_Delayed, **kwargs) -> None: - """ Sets horizontal scroll position. - - Args: - item (Union[int, str]): - value (float): Scroll position - when (int, optional): Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used to set the position twice. - Returns: - None - """ - - return internal_dpg.set_x_scroll(item, value, when=when, **kwargs) - -def set_y_scroll(item : Union[int, str], value : float, *, when: int =internal_dpg.mvSetScrollFlags_Delayed, **kwargs) -> None: - """ Sets vertical scroll position. - - Args: - item (Union[int, str]): - value (float): Scroll position - when (int, optional): Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used to set the position twice. - Returns: - None - """ - - return internal_dpg.set_y_scroll(item, value, when=when, **kwargs) - -def setup_dearpygui(**kwargs) -> None: - """ Sets up Dear PyGui - - Args: - viewport (Union[int, str], optional): (deprecated) - Returns: - None - """ - - if 'viewport' in kwargs.keys(): - - warnings.warn('viewport keyword removed', DeprecationWarning, 2) - - kwargs.pop('viewport', None) - - return internal_dpg.setup_dearpygui(**kwargs) - -def show_imgui_demo(**kwargs) -> None: - """ Shows the imgui demo. - - Args: - Returns: - None - """ - - return internal_dpg.show_imgui_demo(**kwargs) - -def show_implot_demo(**kwargs) -> None: - """ Shows the implot demo. - - Args: - Returns: - None - """ - - return internal_dpg.show_implot_demo(**kwargs) - -def show_item_debug(item : Union[int, str], **kwargs) -> None: - """ Shows an item's debug window - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.show_item_debug(item, **kwargs) - -def show_tool(tool : Union[int, str], **kwargs) -> str: - """ Shows a built in tool. - - Args: - tool (Union[int, str]): - Returns: - str - """ - - return internal_dpg.show_tool(tool, **kwargs) - -def show_viewport(*, minimized: bool =False, maximized: bool =False, **kwargs) -> None: - """ Shows the main viewport. - - Args: - minimized (bool, optional): Sets the state of the viewport to minimized - maximized (bool, optional): Sets the state of the viewport to maximized - viewport (Union[int, str], optional): (deprecated) - Returns: - None - """ - - if 'viewport' in kwargs.keys(): - - warnings.warn('viewport keyword removed', DeprecationWarning, 2) - - kwargs.pop('viewport', None) - - return internal_dpg.show_viewport(minimized=minimized, maximized=maximized, **kwargs) - -def split_frame(**kwargs) -> None: - """ Waits one frame. - - Args: - delay (int, optional): (deprecated) Do not use it anymore, it has no effect. - Returns: - None - """ - - if 'delay' in kwargs.keys(): - - warnings.warn('delay keyword removed', DeprecationWarning, 2) - - kwargs.pop('delay', None) - - return internal_dpg.split_frame(**kwargs) - -def stop_dearpygui(**kwargs) -> None: - """ Stops Dear PyGui - - Args: - Returns: - None - """ - - return internal_dpg.stop_dearpygui(**kwargs) - -def toggle_viewport_fullscreen(**kwargs) -> None: - """ Toggle viewport fullscreen mode.. - - Args: - Returns: - None - """ - - return internal_dpg.toggle_viewport_fullscreen(**kwargs) - -def top_container_stack(**kwargs) -> Union[int, str]: - """ Returns the item on the top of the container stack. - - Args: - Returns: - Union[int, str] - """ - - return internal_dpg.top_container_stack(**kwargs) - -def unhighlight_table_cell(table : Union[int, str], row : int, column : int, **kwargs) -> None: - """ Unhighlight specified table cell. - - Args: - table (Union[int, str]): - row (int): - column (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_cell(table, row, column, **kwargs) - -def unhighlight_table_column(table : Union[int, str], column : int, **kwargs) -> None: - """ Unhighlight specified table column. - - Args: - table (Union[int, str]): - column (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_column(table, column, **kwargs) - -def unhighlight_table_row(table : Union[int, str], row : int, **kwargs) -> None: - """ Unhighlight specified table row. - - Args: - table (Union[int, str]): - row (int): - Returns: - None - """ - - return internal_dpg.unhighlight_table_row(table, row, **kwargs) - -def unlock_mutex(**kwargs) -> None: - """ Unlocks render thread mutex - - Args: - Returns: - None - """ - - return internal_dpg.unlock_mutex(**kwargs) - -def unset_table_row_color(table : Union[int, str], row : int, **kwargs) -> None: - """ Remove user set table row color. - - Args: - table (Union[int, str]): - row (int): - Returns: - None - """ - - return internal_dpg.unset_table_row_color(table, row, **kwargs) - -def unstage(item : Union[int, str], **kwargs) -> None: - """ Unstages an item. - - Args: - item (Union[int, str]): - Returns: - None - """ - - return internal_dpg.unstage(item, **kwargs) - - -########################################################## -# Constants # -########################################################## - -mvGraphicsBackend_D3D11=internal_dpg.mvGraphicsBackend_D3D11 -mvGraphicsBackend_D3D12=internal_dpg.mvGraphicsBackend_D3D12 -mvGraphicsBackend_VULKAN=internal_dpg.mvGraphicsBackend_VULKAN -mvGraphicsBackend_METAL=internal_dpg.mvGraphicsBackend_METAL -mvGraphicsBackend_OPENGL=internal_dpg.mvGraphicsBackend_OPENGL -mvMouseButton_Left=internal_dpg.mvMouseButton_Left -mvMouseButton_Right=internal_dpg.mvMouseButton_Right -mvMouseButton_Middle=internal_dpg.mvMouseButton_Middle -mvMouseButton_X1=internal_dpg.mvMouseButton_X1 -mvMouseButton_X2=internal_dpg.mvMouseButton_X2 -mvKey_ModDisabled=internal_dpg.mvKey_ModDisabled -mvKey_None=internal_dpg.mvKey_None -mvKey_0=internal_dpg.mvKey_0 -mvKey_1=internal_dpg.mvKey_1 -mvKey_2=internal_dpg.mvKey_2 -mvKey_3=internal_dpg.mvKey_3 -mvKey_4=internal_dpg.mvKey_4 -mvKey_5=internal_dpg.mvKey_5 -mvKey_6=internal_dpg.mvKey_6 -mvKey_7=internal_dpg.mvKey_7 -mvKey_8=internal_dpg.mvKey_8 -mvKey_9=internal_dpg.mvKey_9 -mvKey_A=internal_dpg.mvKey_A -mvKey_B=internal_dpg.mvKey_B -mvKey_C=internal_dpg.mvKey_C -mvKey_D=internal_dpg.mvKey_D -mvKey_E=internal_dpg.mvKey_E -mvKey_F=internal_dpg.mvKey_F -mvKey_G=internal_dpg.mvKey_G -mvKey_H=internal_dpg.mvKey_H -mvKey_I=internal_dpg.mvKey_I -mvKey_J=internal_dpg.mvKey_J -mvKey_K=internal_dpg.mvKey_K -mvKey_L=internal_dpg.mvKey_L -mvKey_M=internal_dpg.mvKey_M -mvKey_N=internal_dpg.mvKey_N -mvKey_O=internal_dpg.mvKey_O -mvKey_P=internal_dpg.mvKey_P -mvKey_Q=internal_dpg.mvKey_Q -mvKey_R=internal_dpg.mvKey_R -mvKey_S=internal_dpg.mvKey_S -mvKey_T=internal_dpg.mvKey_T -mvKey_U=internal_dpg.mvKey_U -mvKey_V=internal_dpg.mvKey_V -mvKey_W=internal_dpg.mvKey_W -mvKey_X=internal_dpg.mvKey_X -mvKey_Y=internal_dpg.mvKey_Y -mvKey_Z=internal_dpg.mvKey_Z -mvKey_Back=internal_dpg.mvKey_Back -mvKey_Tab=internal_dpg.mvKey_Tab -mvKey_Return=internal_dpg.mvKey_Return -mvKey_LShift=internal_dpg.mvKey_LShift -mvKey_RShift=internal_dpg.mvKey_RShift -mvKey_LControl=internal_dpg.mvKey_LControl -mvKey_RControl=internal_dpg.mvKey_RControl -mvKey_LAlt=internal_dpg.mvKey_LAlt -mvKey_RAlt=internal_dpg.mvKey_RAlt -mvKey_Pause=internal_dpg.mvKey_Pause -mvKey_CapsLock=internal_dpg.mvKey_CapsLock -mvKey_Escape=internal_dpg.mvKey_Escape -mvKey_Spacebar=internal_dpg.mvKey_Spacebar -mvKey_End=internal_dpg.mvKey_End -mvKey_Home=internal_dpg.mvKey_Home -mvKey_Left=internal_dpg.mvKey_Left -mvKey_Up=internal_dpg.mvKey_Up -mvKey_Right=internal_dpg.mvKey_Right -mvKey_Down=internal_dpg.mvKey_Down -mvKey_Print=internal_dpg.mvKey_Print -mvKey_Insert=internal_dpg.mvKey_Insert -mvKey_Delete=internal_dpg.mvKey_Delete -mvKey_NumPad0=internal_dpg.mvKey_NumPad0 -mvKey_NumPad1=internal_dpg.mvKey_NumPad1 -mvKey_NumPad2=internal_dpg.mvKey_NumPad2 -mvKey_NumPad3=internal_dpg.mvKey_NumPad3 -mvKey_NumPad4=internal_dpg.mvKey_NumPad4 -mvKey_NumPad5=internal_dpg.mvKey_NumPad5 -mvKey_NumPad6=internal_dpg.mvKey_NumPad6 -mvKey_NumPad7=internal_dpg.mvKey_NumPad7 -mvKey_NumPad8=internal_dpg.mvKey_NumPad8 -mvKey_NumPad9=internal_dpg.mvKey_NumPad9 -mvKey_NumPadEnter=internal_dpg.mvKey_NumPadEnter -mvKey_NumPadEqual=internal_dpg.mvKey_NumPadEqual -mvKey_Subtract=internal_dpg.mvKey_Subtract -mvKey_Decimal=internal_dpg.mvKey_Decimal -mvKey_Divide=internal_dpg.mvKey_Divide -mvKey_Multiply=internal_dpg.mvKey_Multiply -mvKey_Add=internal_dpg.mvKey_Add -mvKey_F1=internal_dpg.mvKey_F1 -mvKey_F2=internal_dpg.mvKey_F2 -mvKey_F3=internal_dpg.mvKey_F3 -mvKey_F4=internal_dpg.mvKey_F4 -mvKey_F5=internal_dpg.mvKey_F5 -mvKey_F6=internal_dpg.mvKey_F6 -mvKey_F7=internal_dpg.mvKey_F7 -mvKey_F8=internal_dpg.mvKey_F8 -mvKey_F9=internal_dpg.mvKey_F9 -mvKey_F10=internal_dpg.mvKey_F10 -mvKey_F11=internal_dpg.mvKey_F11 -mvKey_F12=internal_dpg.mvKey_F12 -mvKey_F13=internal_dpg.mvKey_F13 -mvKey_F14=internal_dpg.mvKey_F14 -mvKey_F15=internal_dpg.mvKey_F15 -mvKey_F16=internal_dpg.mvKey_F16 -mvKey_F17=internal_dpg.mvKey_F17 -mvKey_F18=internal_dpg.mvKey_F18 -mvKey_F19=internal_dpg.mvKey_F19 -mvKey_F20=internal_dpg.mvKey_F20 -mvKey_F21=internal_dpg.mvKey_F21 -mvKey_F22=internal_dpg.mvKey_F22 -mvKey_F23=internal_dpg.mvKey_F23 -mvKey_F24=internal_dpg.mvKey_F24 -mvKey_NumLock=internal_dpg.mvKey_NumLock -mvKey_ScrollLock=internal_dpg.mvKey_ScrollLock -mvKey_Period=internal_dpg.mvKey_Period -mvKey_Slash=internal_dpg.mvKey_Slash -mvKey_Backslash=internal_dpg.mvKey_Backslash -mvKey_Open_Brace=internal_dpg.mvKey_Open_Brace -mvKey_Close_Brace=internal_dpg.mvKey_Close_Brace -mvKey_Browser_Back=internal_dpg.mvKey_Browser_Back -mvKey_Browser_Forward=internal_dpg.mvKey_Browser_Forward -mvKey_Comma=internal_dpg.mvKey_Comma -mvKey_Minus=internal_dpg.mvKey_Minus -mvKey_Menu=internal_dpg.mvKey_Menu -mvKey_ModSuper=internal_dpg.mvKey_ModSuper -mvKey_ModShift=internal_dpg.mvKey_ModShift -mvKey_ModAlt=internal_dpg.mvKey_ModAlt -mvKey_ModCtrl=internal_dpg.mvKey_ModCtrl -mvKey_Clear=internal_dpg.mvKey_Clear -mvKey_Prior=internal_dpg.mvKey_Prior -mvKey_Next=internal_dpg.mvKey_Next -mvKey_Select=internal_dpg.mvKey_Select -mvKey_Execute=internal_dpg.mvKey_Execute -mvKey_LWin=internal_dpg.mvKey_LWin -mvKey_RWin=internal_dpg.mvKey_RWin -mvKey_Apps=internal_dpg.mvKey_Apps -mvKey_Sleep=internal_dpg.mvKey_Sleep -mvKey_Help=internal_dpg.mvKey_Help -mvKey_Browser_Refresh=internal_dpg.mvKey_Browser_Refresh -mvKey_Browser_Stop=internal_dpg.mvKey_Browser_Stop -mvKey_Browser_Search=internal_dpg.mvKey_Browser_Search -mvKey_Browser_Favorites=internal_dpg.mvKey_Browser_Favorites -mvKey_Browser_Home=internal_dpg.mvKey_Browser_Home -mvKey_Volume_Mute=internal_dpg.mvKey_Volume_Mute -mvKey_Volume_Down=internal_dpg.mvKey_Volume_Down -mvKey_Volume_Up=internal_dpg.mvKey_Volume_Up -mvKey_Media_Next_Track=internal_dpg.mvKey_Media_Next_Track -mvKey_Media_Prev_Track=internal_dpg.mvKey_Media_Prev_Track -mvKey_Media_Stop=internal_dpg.mvKey_Media_Stop -mvKey_Media_Play_Pause=internal_dpg.mvKey_Media_Play_Pause -mvKey_Launch_Mail=internal_dpg.mvKey_Launch_Mail -mvKey_Launch_Media_Select=internal_dpg.mvKey_Launch_Media_Select -mvKey_Launch_App1=internal_dpg.mvKey_Launch_App1 -mvKey_Launch_App2=internal_dpg.mvKey_Launch_App2 -mvKey_Colon=internal_dpg.mvKey_Colon -mvKey_Plus=internal_dpg.mvKey_Plus -mvKey_Tilde=internal_dpg.mvKey_Tilde -mvKey_Quote=internal_dpg.mvKey_Quote -mvKey_F25=internal_dpg.mvKey_F25 -mvAll=internal_dpg.mvAll -mvTool_About=internal_dpg.mvTool_About -mvTool_Debug=internal_dpg.mvTool_Debug -mvTool_Doc=internal_dpg.mvTool_Doc -mvTool_ItemRegistry=internal_dpg.mvTool_ItemRegistry -mvTool_Metrics=internal_dpg.mvTool_Metrics -mvTool_Stack=internal_dpg.mvTool_Stack -mvTool_Style=internal_dpg.mvTool_Style -mvTool_Font=internal_dpg.mvTool_Font -mvFontAtlas=internal_dpg.mvFontAtlas -mvAppUUID=internal_dpg.mvAppUUID -mvInvalidUUID=internal_dpg.mvInvalidUUID -mvDir_None=internal_dpg.mvDir_None -mvDir_Left=internal_dpg.mvDir_Left -mvDir_Right=internal_dpg.mvDir_Right -mvDir_Up=internal_dpg.mvDir_Up -mvDir_Down=internal_dpg.mvDir_Down -mvComboHeight_Small=internal_dpg.mvComboHeight_Small -mvComboHeight_Regular=internal_dpg.mvComboHeight_Regular -mvComboHeight_Large=internal_dpg.mvComboHeight_Large -mvComboHeight_Largest=internal_dpg.mvComboHeight_Largest -mvEventType_Off=internal_dpg.mvEventType_Off -mvEventType_Enter=internal_dpg.mvEventType_Enter -mvEventType_On=internal_dpg.mvEventType_On -mvEventType_Leave=internal_dpg.mvEventType_Leave -mvSetScrollFlags_Now=internal_dpg.mvSetScrollFlags_Now -mvSetScrollFlags_Delayed=internal_dpg.mvSetScrollFlags_Delayed -mvSetScrollFlags_Both=internal_dpg.mvSetScrollFlags_Both -mvScrollDirection_XAxis=internal_dpg.mvScrollDirection_XAxis -mvScrollDirection_YAxis=internal_dpg.mvScrollDirection_YAxis -mvScrollDirection_Horizontal=internal_dpg.mvScrollDirection_Horizontal -mvScrollDirection_Vertical=internal_dpg.mvScrollDirection_Vertical -mvLoadInd_DottedCircle=internal_dpg.mvLoadInd_DottedCircle -mvLoadInd_Ring=internal_dpg.mvLoadInd_Ring -mvPlatform_Windows=internal_dpg.mvPlatform_Windows -mvPlatform_Apple=internal_dpg.mvPlatform_Apple -mvPlatform_Linux=internal_dpg.mvPlatform_Linux -mvColorEdit_AlphaPreviewNone=internal_dpg.mvColorEdit_AlphaPreviewNone -mvColorEdit_AlphaPreview=internal_dpg.mvColorEdit_AlphaPreview -mvColorEdit_AlphaPreviewHalf=internal_dpg.mvColorEdit_AlphaPreviewHalf -mvColorEdit_uint8=internal_dpg.mvColorEdit_uint8 -mvColorEdit_float=internal_dpg.mvColorEdit_float -mvColorEdit_rgb=internal_dpg.mvColorEdit_rgb -mvColorEdit_hsv=internal_dpg.mvColorEdit_hsv -mvColorEdit_hex=internal_dpg.mvColorEdit_hex -mvColorEdit_input_rgb=internal_dpg.mvColorEdit_input_rgb -mvColorEdit_input_hsv=internal_dpg.mvColorEdit_input_hsv -mvPlotColormap_Default=internal_dpg.mvPlotColormap_Default -mvPlotColormap_Deep=internal_dpg.mvPlotColormap_Deep -mvPlotColormap_Dark=internal_dpg.mvPlotColormap_Dark -mvPlotColormap_Pastel=internal_dpg.mvPlotColormap_Pastel -mvPlotColormap_Paired=internal_dpg.mvPlotColormap_Paired -mvPlotColormap_Viridis=internal_dpg.mvPlotColormap_Viridis -mvPlotColormap_Plasma=internal_dpg.mvPlotColormap_Plasma -mvPlotColormap_Hot=internal_dpg.mvPlotColormap_Hot -mvPlotColormap_Cool=internal_dpg.mvPlotColormap_Cool -mvPlotColormap_Pink=internal_dpg.mvPlotColormap_Pink -mvPlotColormap_Jet=internal_dpg.mvPlotColormap_Jet -mvPlotColormap_Twilight=internal_dpg.mvPlotColormap_Twilight -mvPlotColormap_RdBu=internal_dpg.mvPlotColormap_RdBu -mvPlotColormap_BrBG=internal_dpg.mvPlotColormap_BrBG -mvPlotColormap_PiYG=internal_dpg.mvPlotColormap_PiYG -mvPlotColormap_Spectral=internal_dpg.mvPlotColormap_Spectral -mvPlotColormap_Greys=internal_dpg.mvPlotColormap_Greys -mvColorPicker_bar=internal_dpg.mvColorPicker_bar -mvColorPicker_wheel=internal_dpg.mvColorPicker_wheel -mvTabOrder_Reorderable=internal_dpg.mvTabOrder_Reorderable -mvTabOrder_Fixed=internal_dpg.mvTabOrder_Fixed -mvTabOrder_Leading=internal_dpg.mvTabOrder_Leading -mvTabOrder_Trailing=internal_dpg.mvTabOrder_Trailing -mvTimeUnit_Us=internal_dpg.mvTimeUnit_Us -mvTimeUnit_Ms=internal_dpg.mvTimeUnit_Ms -mvTimeUnit_S=internal_dpg.mvTimeUnit_S -mvTimeUnit_Min=internal_dpg.mvTimeUnit_Min -mvTimeUnit_Hr=internal_dpg.mvTimeUnit_Hr -mvTimeUnit_Day=internal_dpg.mvTimeUnit_Day -mvTimeUnit_Mo=internal_dpg.mvTimeUnit_Mo -mvTimeUnit_Yr=internal_dpg.mvTimeUnit_Yr -mvDatePickerLevel_Day=internal_dpg.mvDatePickerLevel_Day -mvDatePickerLevel_Month=internal_dpg.mvDatePickerLevel_Month -mvDatePickerLevel_Year=internal_dpg.mvDatePickerLevel_Year -mvCullMode_None=internal_dpg.mvCullMode_None -mvCullMode_Back=internal_dpg.mvCullMode_Back -mvCullMode_Front=internal_dpg.mvCullMode_Front -mvFontRangeHint_Default=internal_dpg.mvFontRangeHint_Default -mvFontRangeHint_Japanese=internal_dpg.mvFontRangeHint_Japanese -mvFontRangeHint_Korean=internal_dpg.mvFontRangeHint_Korean -mvFontRangeHint_Chinese_Full=internal_dpg.mvFontRangeHint_Chinese_Full -mvFontRangeHint_Chinese_Simplified_Common=internal_dpg.mvFontRangeHint_Chinese_Simplified_Common -mvFontRangeHint_Cyrillic=internal_dpg.mvFontRangeHint_Cyrillic -mvFontRangeHint_Thai=internal_dpg.mvFontRangeHint_Thai -mvFontRangeHint_Vietnamese=internal_dpg.mvFontRangeHint_Vietnamese -mvNode_PinShape_Circle=internal_dpg.mvNode_PinShape_Circle -mvNode_PinShape_CircleFilled=internal_dpg.mvNode_PinShape_CircleFilled -mvNode_PinShape_Triangle=internal_dpg.mvNode_PinShape_Triangle -mvNode_PinShape_TriangleFilled=internal_dpg.mvNode_PinShape_TriangleFilled -mvNode_PinShape_Quad=internal_dpg.mvNode_PinShape_Quad -mvNode_PinShape_QuadFilled=internal_dpg.mvNode_PinShape_QuadFilled -mvNode_Attr_Input=internal_dpg.mvNode_Attr_Input -mvNode_Attr_Output=internal_dpg.mvNode_Attr_Output -mvNode_Attr_Static=internal_dpg.mvNode_Attr_Static -mvPlotBin_Sqrt=internal_dpg.mvPlotBin_Sqrt -mvPlotBin_Sturges=internal_dpg.mvPlotBin_Sturges -mvPlotBin_Rice=internal_dpg.mvPlotBin_Rice -mvPlotBin_Scott=internal_dpg.mvPlotBin_Scott -mvXAxis=internal_dpg.mvXAxis -mvXAxis2=internal_dpg.mvXAxis2 -mvXAxis3=internal_dpg.mvXAxis3 -mvYAxis=internal_dpg.mvYAxis -mvYAxis2=internal_dpg.mvYAxis2 -mvYAxis3=internal_dpg.mvYAxis3 -mvPlotScale_Linear=internal_dpg.mvPlotScale_Linear -mvPlotScale_Time=internal_dpg.mvPlotScale_Time -mvPlotScale_Log10=internal_dpg.mvPlotScale_Log10 -mvPlotScale_SymLog=internal_dpg.mvPlotScale_SymLog -mvPlotMarker_None=internal_dpg.mvPlotMarker_None -mvPlotMarker_Circle=internal_dpg.mvPlotMarker_Circle -mvPlotMarker_Square=internal_dpg.mvPlotMarker_Square -mvPlotMarker_Diamond=internal_dpg.mvPlotMarker_Diamond -mvPlotMarker_Up=internal_dpg.mvPlotMarker_Up -mvPlotMarker_Down=internal_dpg.mvPlotMarker_Down -mvPlotMarker_Left=internal_dpg.mvPlotMarker_Left -mvPlotMarker_Right=internal_dpg.mvPlotMarker_Right -mvPlotMarker_Cross=internal_dpg.mvPlotMarker_Cross -mvPlotMarker_Plus=internal_dpg.mvPlotMarker_Plus -mvPlotMarker_Asterisk=internal_dpg.mvPlotMarker_Asterisk -mvPlot_Location_Center=internal_dpg.mvPlot_Location_Center -mvPlot_Location_North=internal_dpg.mvPlot_Location_North -mvPlot_Location_South=internal_dpg.mvPlot_Location_South -mvPlot_Location_West=internal_dpg.mvPlot_Location_West -mvPlot_Location_East=internal_dpg.mvPlot_Location_East -mvPlot_Location_NorthWest=internal_dpg.mvPlot_Location_NorthWest -mvPlot_Location_NorthEast=internal_dpg.mvPlot_Location_NorthEast -mvPlot_Location_SouthWest=internal_dpg.mvPlot_Location_SouthWest -mvPlot_Location_SouthEast=internal_dpg.mvPlot_Location_SouthEast -mvNodeMiniMap_Location_BottomLeft=internal_dpg.mvNodeMiniMap_Location_BottomLeft -mvNodeMiniMap_Location_BottomRight=internal_dpg.mvNodeMiniMap_Location_BottomRight -mvNodeMiniMap_Location_TopLeft=internal_dpg.mvNodeMiniMap_Location_TopLeft -mvNodeMiniMap_Location_TopRight=internal_dpg.mvNodeMiniMap_Location_TopRight -mvTable_SizingFixedFit=internal_dpg.mvTable_SizingFixedFit -mvTable_SizingFixedSame=internal_dpg.mvTable_SizingFixedSame -mvTable_SizingStretchProp=internal_dpg.mvTable_SizingStretchProp -mvTable_SizingStretchSame=internal_dpg.mvTable_SizingStretchSame -mvTreeLines_None=internal_dpg.mvTreeLines_None -mvTreeLines_Full=internal_dpg.mvTreeLines_Full -mvTreeLines_ToNodes=internal_dpg.mvTreeLines_ToNodes -mvFormat_Float_rgba=internal_dpg.mvFormat_Float_rgba -mvFormat_Float_rgb=internal_dpg.mvFormat_Float_rgb -mvThemeCat_Core=internal_dpg.mvThemeCat_Core -mvThemeCat_Plots=internal_dpg.mvThemeCat_Plots -mvThemeCat_Nodes=internal_dpg.mvThemeCat_Nodes -mvThemeCol_Text=internal_dpg.mvThemeCol_Text -mvThemeCol_TextDisabled=internal_dpg.mvThemeCol_TextDisabled -mvThemeCol_WindowBg=internal_dpg.mvThemeCol_WindowBg -mvThemeCol_ChildBg=internal_dpg.mvThemeCol_ChildBg -mvThemeCol_PopupBg=internal_dpg.mvThemeCol_PopupBg -mvThemeCol_Border=internal_dpg.mvThemeCol_Border -mvThemeCol_BorderShadow=internal_dpg.mvThemeCol_BorderShadow -mvThemeCol_FrameBg=internal_dpg.mvThemeCol_FrameBg -mvThemeCol_FrameBgHovered=internal_dpg.mvThemeCol_FrameBgHovered -mvThemeCol_FrameBgActive=internal_dpg.mvThemeCol_FrameBgActive -mvThemeCol_TitleBg=internal_dpg.mvThemeCol_TitleBg -mvThemeCol_TitleBgActive=internal_dpg.mvThemeCol_TitleBgActive -mvThemeCol_TitleBgCollapsed=internal_dpg.mvThemeCol_TitleBgCollapsed -mvThemeCol_MenuBarBg=internal_dpg.mvThemeCol_MenuBarBg -mvThemeCol_ScrollbarBg=internal_dpg.mvThemeCol_ScrollbarBg -mvThemeCol_ScrollbarGrab=internal_dpg.mvThemeCol_ScrollbarGrab -mvThemeCol_ScrollbarGrabHovered=internal_dpg.mvThemeCol_ScrollbarGrabHovered -mvThemeCol_ScrollbarGrabActive=internal_dpg.mvThemeCol_ScrollbarGrabActive -mvThemeCol_CheckMark=internal_dpg.mvThemeCol_CheckMark -mvThemeCol_SliderGrab=internal_dpg.mvThemeCol_SliderGrab -mvThemeCol_SliderGrabActive=internal_dpg.mvThemeCol_SliderGrabActive -mvThemeCol_Button=internal_dpg.mvThemeCol_Button -mvThemeCol_ButtonHovered=internal_dpg.mvThemeCol_ButtonHovered -mvThemeCol_ButtonActive=internal_dpg.mvThemeCol_ButtonActive -mvThemeCol_Header=internal_dpg.mvThemeCol_Header -mvThemeCol_HeaderHovered=internal_dpg.mvThemeCol_HeaderHovered -mvThemeCol_HeaderActive=internal_dpg.mvThemeCol_HeaderActive -mvThemeCol_Separator=internal_dpg.mvThemeCol_Separator -mvThemeCol_SeparatorHovered=internal_dpg.mvThemeCol_SeparatorHovered -mvThemeCol_SeparatorActive=internal_dpg.mvThemeCol_SeparatorActive -mvThemeCol_ResizeGrip=internal_dpg.mvThemeCol_ResizeGrip -mvThemeCol_ResizeGripHovered=internal_dpg.mvThemeCol_ResizeGripHovered -mvThemeCol_ResizeGripActive=internal_dpg.mvThemeCol_ResizeGripActive -mvThemeCol_InputTextCursor=internal_dpg.mvThemeCol_InputTextCursor -mvThemeCol_TabHovered=internal_dpg.mvThemeCol_TabHovered -mvThemeCol_Tab=internal_dpg.mvThemeCol_Tab -mvThemeCol_TabSelected=internal_dpg.mvThemeCol_TabSelected -mvThemeCol_TabSelectedOverline=internal_dpg.mvThemeCol_TabSelectedOverline -mvThemeCol_TabDimmed=internal_dpg.mvThemeCol_TabDimmed -mvThemeCol_TabDimmedSelected=internal_dpg.mvThemeCol_TabDimmedSelected -mvThemeCol_TabDimmedSelectedOverline=internal_dpg.mvThemeCol_TabDimmedSelectedOverline -mvThemeCol_DockingPreview=internal_dpg.mvThemeCol_DockingPreview -mvThemeCol_DockingEmptyBg=internal_dpg.mvThemeCol_DockingEmptyBg -mvThemeCol_PlotLines=internal_dpg.mvThemeCol_PlotLines -mvThemeCol_PlotLinesHovered=internal_dpg.mvThemeCol_PlotLinesHovered -mvThemeCol_PlotHistogram=internal_dpg.mvThemeCol_PlotHistogram -mvThemeCol_PlotHistogramHovered=internal_dpg.mvThemeCol_PlotHistogramHovered -mvThemeCol_TableHeaderBg=internal_dpg.mvThemeCol_TableHeaderBg -mvThemeCol_TableBorderStrong=internal_dpg.mvThemeCol_TableBorderStrong -mvThemeCol_TableBorderLight=internal_dpg.mvThemeCol_TableBorderLight -mvThemeCol_TableRowBg=internal_dpg.mvThemeCol_TableRowBg -mvThemeCol_TableRowBgAlt=internal_dpg.mvThemeCol_TableRowBgAlt -mvThemeCol_TextSelectedBg=internal_dpg.mvThemeCol_TextSelectedBg -mvThemeCol_TreeLines=internal_dpg.mvThemeCol_TreeLines -mvThemeCol_DragDropTarget=internal_dpg.mvThemeCol_DragDropTarget -mvThemeCol_DragDropTargetBg=internal_dpg.mvThemeCol_DragDropTargetBg -mvThemeCol_UnsavedMarker=internal_dpg.mvThemeCol_UnsavedMarker -mvThemeCol_NavCursor=internal_dpg.mvThemeCol_NavCursor -mvThemeCol_NavWindowingHighlight=internal_dpg.mvThemeCol_NavWindowingHighlight -mvThemeCol_NavWindowingDimBg=internal_dpg.mvThemeCol_NavWindowingDimBg -mvThemeCol_ModalWindowDimBg=internal_dpg.mvThemeCol_ModalWindowDimBg -mvThemeCol_TabActive=internal_dpg.mvThemeCol_TabActive -mvThemeCol_TabUnfocused=internal_dpg.mvThemeCol_TabUnfocused -mvThemeCol_TabUnfocusedActive=internal_dpg.mvThemeCol_TabUnfocusedActive -mvThemeCol_NavHighlight=internal_dpg.mvThemeCol_NavHighlight -mvPlotCol_Line=internal_dpg.mvPlotCol_Line -mvPlotCol_Fill=internal_dpg.mvPlotCol_Fill -mvPlotCol_MarkerOutline=internal_dpg.mvPlotCol_MarkerOutline -mvPlotCol_MarkerFill=internal_dpg.mvPlotCol_MarkerFill -mvPlotCol_ErrorBar=internal_dpg.mvPlotCol_ErrorBar -mvPlotCol_FrameBg=internal_dpg.mvPlotCol_FrameBg -mvPlotCol_PlotBg=internal_dpg.mvPlotCol_PlotBg -mvPlotCol_PlotBorder=internal_dpg.mvPlotCol_PlotBorder -mvPlotCol_LegendBg=internal_dpg.mvPlotCol_LegendBg -mvPlotCol_LegendBorder=internal_dpg.mvPlotCol_LegendBorder -mvPlotCol_LegendText=internal_dpg.mvPlotCol_LegendText -mvPlotCol_TitleText=internal_dpg.mvPlotCol_TitleText -mvPlotCol_InlayText=internal_dpg.mvPlotCol_InlayText -mvPlotCol_AxisText=internal_dpg.mvPlotCol_AxisText -mvPlotCol_AxisGrid=internal_dpg.mvPlotCol_AxisGrid -mvPlotCol_AxisTick=internal_dpg.mvPlotCol_AxisTick -mvPlotCol_AxisBg=internal_dpg.mvPlotCol_AxisBg -mvPlotCol_AxisBgHovered=internal_dpg.mvPlotCol_AxisBgHovered -mvPlotCol_AxisBgActive=internal_dpg.mvPlotCol_AxisBgActive -mvPlotCol_Selection=internal_dpg.mvPlotCol_Selection -mvPlotCol_Crosshairs=internal_dpg.mvPlotCol_Crosshairs -mvNodeCol_NodeBackground=internal_dpg.mvNodeCol_NodeBackground -mvNodeCol_NodeBackgroundHovered=internal_dpg.mvNodeCol_NodeBackgroundHovered -mvNodeCol_NodeBackgroundSelected=internal_dpg.mvNodeCol_NodeBackgroundSelected -mvNodeCol_NodeOutline=internal_dpg.mvNodeCol_NodeOutline -mvNodeCol_TitleBar=internal_dpg.mvNodeCol_TitleBar -mvNodeCol_TitleBarHovered=internal_dpg.mvNodeCol_TitleBarHovered -mvNodeCol_TitleBarSelected=internal_dpg.mvNodeCol_TitleBarSelected -mvNodeCol_Link=internal_dpg.mvNodeCol_Link -mvNodeCol_LinkHovered=internal_dpg.mvNodeCol_LinkHovered -mvNodeCol_LinkSelected=internal_dpg.mvNodeCol_LinkSelected -mvNodeCol_Pin=internal_dpg.mvNodeCol_Pin -mvNodeCol_PinHovered=internal_dpg.mvNodeCol_PinHovered -mvNodeCol_BoxSelector=internal_dpg.mvNodeCol_BoxSelector -mvNodeCol_BoxSelectorOutline=internal_dpg.mvNodeCol_BoxSelectorOutline -mvNodeCol_GridBackground=internal_dpg.mvNodeCol_GridBackground -mvNodeCol_GridLine=internal_dpg.mvNodeCol_GridLine -mvNodesCol_GridLinePrimary=internal_dpg.mvNodesCol_GridLinePrimary -mvNodesCol_MiniMapBackground=internal_dpg.mvNodesCol_MiniMapBackground -mvNodesCol_MiniMapBackgroundHovered=internal_dpg.mvNodesCol_MiniMapBackgroundHovered -mvNodesCol_MiniMapOutline=internal_dpg.mvNodesCol_MiniMapOutline -mvNodesCol_MiniMapOutlineHovered=internal_dpg.mvNodesCol_MiniMapOutlineHovered -mvNodesCol_MiniMapNodeBackground=internal_dpg.mvNodesCol_MiniMapNodeBackground -mvNodesCol_MiniMapNodeBackgroundHovered=internal_dpg.mvNodesCol_MiniMapNodeBackgroundHovered -mvNodesCol_MiniMapNodeBackgroundSelected=internal_dpg.mvNodesCol_MiniMapNodeBackgroundSelected -mvNodesCol_MiniMapNodeOutline=internal_dpg.mvNodesCol_MiniMapNodeOutline -mvNodesCol_MiniMapLink=internal_dpg.mvNodesCol_MiniMapLink -mvNodesCol_MiniMapLinkSelected=internal_dpg.mvNodesCol_MiniMapLinkSelected -mvNodesCol_MiniMapCanvas=internal_dpg.mvNodesCol_MiniMapCanvas -mvNodesCol_MiniMapCanvasOutline=internal_dpg.mvNodesCol_MiniMapCanvasOutline -mvStyleVar_Alpha=internal_dpg.mvStyleVar_Alpha -mvStyleVar_DisabledAlpha=internal_dpg.mvStyleVar_DisabledAlpha -mvStyleVar_WindowPadding=internal_dpg.mvStyleVar_WindowPadding -mvStyleVar_WindowRounding=internal_dpg.mvStyleVar_WindowRounding -mvStyleVar_WindowBorderSize=internal_dpg.mvStyleVar_WindowBorderSize -mvStyleVar_WindowMinSize=internal_dpg.mvStyleVar_WindowMinSize -mvStyleVar_WindowTitleAlign=internal_dpg.mvStyleVar_WindowTitleAlign -mvStyleVar_ChildRounding=internal_dpg.mvStyleVar_ChildRounding -mvStyleVar_ChildBorderSize=internal_dpg.mvStyleVar_ChildBorderSize -mvStyleVar_PopupRounding=internal_dpg.mvStyleVar_PopupRounding -mvStyleVar_PopupBorderSize=internal_dpg.mvStyleVar_PopupBorderSize -mvStyleVar_FramePadding=internal_dpg.mvStyleVar_FramePadding -mvStyleVar_FrameRounding=internal_dpg.mvStyleVar_FrameRounding -mvStyleVar_FrameBorderSize=internal_dpg.mvStyleVar_FrameBorderSize -mvStyleVar_ItemSpacing=internal_dpg.mvStyleVar_ItemSpacing -mvStyleVar_ItemInnerSpacing=internal_dpg.mvStyleVar_ItemInnerSpacing -mvStyleVar_IndentSpacing=internal_dpg.mvStyleVar_IndentSpacing -mvStyleVar_CellPadding=internal_dpg.mvStyleVar_CellPadding -mvStyleVar_ScrollbarSize=internal_dpg.mvStyleVar_ScrollbarSize -mvStyleVar_ScrollbarRounding=internal_dpg.mvStyleVar_ScrollbarRounding -mvStyleVar_ScrollbarPadding=internal_dpg.mvStyleVar_ScrollbarPadding -mvStyleVar_GrabMinSize=internal_dpg.mvStyleVar_GrabMinSize -mvStyleVar_GrabRounding=internal_dpg.mvStyleVar_GrabRounding -mvStyleVar_ImageBorderSize=internal_dpg.mvStyleVar_ImageBorderSize -mvStyleVar_TabRounding=internal_dpg.mvStyleVar_TabRounding -mvStyleVar_TabBorderSize=internal_dpg.mvStyleVar_TabBorderSize -mvStyleVar_TabMinWidthBase=internal_dpg.mvStyleVar_TabMinWidthBase -mvStyleVar_TabMinWidthShrink=internal_dpg.mvStyleVar_TabMinWidthShrink -mvStyleVar_TabBarBorderSize=internal_dpg.mvStyleVar_TabBarBorderSize -mvStyleVar_TabBarOverlineSize=internal_dpg.mvStyleVar_TabBarOverlineSize -mvStyleVar_TableAngledHeadersAngle=internal_dpg.mvStyleVar_TableAngledHeadersAngle -mvStyleVar_TableAngledHeadersTextAlign=internal_dpg.mvStyleVar_TableAngledHeadersTextAlign -mvStyleVar_TreeLinesSize=internal_dpg.mvStyleVar_TreeLinesSize -mvStyleVar_TreeLinesRounding=internal_dpg.mvStyleVar_TreeLinesRounding -mvStyleVar_ButtonTextAlign=internal_dpg.mvStyleVar_ButtonTextAlign -mvStyleVar_SelectableTextAlign=internal_dpg.mvStyleVar_SelectableTextAlign -mvStyleVar_SeparatorTextBorderSize=internal_dpg.mvStyleVar_SeparatorTextBorderSize -mvStyleVar_SeparatorTextAlign=internal_dpg.mvStyleVar_SeparatorTextAlign -mvStyleVar_SeparatorTextPadding=internal_dpg.mvStyleVar_SeparatorTextPadding -mvStyleVar_DockingSeparatorSize=internal_dpg.mvStyleVar_DockingSeparatorSize -mvPlotStyleVar_LineWeight=internal_dpg.mvPlotStyleVar_LineWeight -mvPlotStyleVar_Marker=internal_dpg.mvPlotStyleVar_Marker -mvPlotStyleVar_MarkerSize=internal_dpg.mvPlotStyleVar_MarkerSize -mvPlotStyleVar_MarkerWeight=internal_dpg.mvPlotStyleVar_MarkerWeight -mvPlotStyleVar_FillAlpha=internal_dpg.mvPlotStyleVar_FillAlpha -mvPlotStyleVar_ErrorBarSize=internal_dpg.mvPlotStyleVar_ErrorBarSize -mvPlotStyleVar_ErrorBarWeight=internal_dpg.mvPlotStyleVar_ErrorBarWeight -mvPlotStyleVar_DigitalBitHeight=internal_dpg.mvPlotStyleVar_DigitalBitHeight -mvPlotStyleVar_DigitalBitGap=internal_dpg.mvPlotStyleVar_DigitalBitGap -mvPlotStyleVar_PlotBorderSize=internal_dpg.mvPlotStyleVar_PlotBorderSize -mvPlotStyleVar_MinorAlpha=internal_dpg.mvPlotStyleVar_MinorAlpha -mvPlotStyleVar_MajorTickLen=internal_dpg.mvPlotStyleVar_MajorTickLen -mvPlotStyleVar_MinorTickLen=internal_dpg.mvPlotStyleVar_MinorTickLen -mvPlotStyleVar_MajorTickSize=internal_dpg.mvPlotStyleVar_MajorTickSize -mvPlotStyleVar_MinorTickSize=internal_dpg.mvPlotStyleVar_MinorTickSize -mvPlotStyleVar_MajorGridSize=internal_dpg.mvPlotStyleVar_MajorGridSize -mvPlotStyleVar_MinorGridSize=internal_dpg.mvPlotStyleVar_MinorGridSize -mvPlotStyleVar_PlotPadding=internal_dpg.mvPlotStyleVar_PlotPadding -mvPlotStyleVar_LabelPadding=internal_dpg.mvPlotStyleVar_LabelPadding -mvPlotStyleVar_LegendPadding=internal_dpg.mvPlotStyleVar_LegendPadding -mvPlotStyleVar_LegendInnerPadding=internal_dpg.mvPlotStyleVar_LegendInnerPadding -mvPlotStyleVar_LegendSpacing=internal_dpg.mvPlotStyleVar_LegendSpacing -mvPlotStyleVar_MousePosPadding=internal_dpg.mvPlotStyleVar_MousePosPadding -mvPlotStyleVar_AnnotationPadding=internal_dpg.mvPlotStyleVar_AnnotationPadding -mvPlotStyleVar_FitPadding=internal_dpg.mvPlotStyleVar_FitPadding -mvPlotStyleVar_PlotDefaultSize=internal_dpg.mvPlotStyleVar_PlotDefaultSize -mvPlotStyleVar_PlotMinSize=internal_dpg.mvPlotStyleVar_PlotMinSize -mvNodeStyleVar_GridSpacing=internal_dpg.mvNodeStyleVar_GridSpacing -mvNodeStyleVar_NodeCornerRounding=internal_dpg.mvNodeStyleVar_NodeCornerRounding -mvNodeStyleVar_NodePadding=internal_dpg.mvNodeStyleVar_NodePadding -mvNodeStyleVar_NodeBorderThickness=internal_dpg.mvNodeStyleVar_NodeBorderThickness -mvNodeStyleVar_LinkThickness=internal_dpg.mvNodeStyleVar_LinkThickness -mvNodeStyleVar_LinkLineSegmentsPerLength=internal_dpg.mvNodeStyleVar_LinkLineSegmentsPerLength -mvNodeStyleVar_LinkHoverDistance=internal_dpg.mvNodeStyleVar_LinkHoverDistance -mvNodeStyleVar_PinCircleRadius=internal_dpg.mvNodeStyleVar_PinCircleRadius -mvNodeStyleVar_PinQuadSideLength=internal_dpg.mvNodeStyleVar_PinQuadSideLength -mvNodeStyleVar_PinTriangleSideLength=internal_dpg.mvNodeStyleVar_PinTriangleSideLength -mvNodeStyleVar_PinLineThickness=internal_dpg.mvNodeStyleVar_PinLineThickness -mvNodeStyleVar_PinHoverRadius=internal_dpg.mvNodeStyleVar_PinHoverRadius -mvNodeStyleVar_PinOffset=internal_dpg.mvNodeStyleVar_PinOffset -mvNodesStyleVar_MiniMapPadding=internal_dpg.mvNodesStyleVar_MiniMapPadding -mvNodesStyleVar_MiniMapOffset=internal_dpg.mvNodesStyleVar_MiniMapOffset -mvInputText=internal_dpg.mvInputText -mvButton=internal_dpg.mvButton -mvRadioButton=internal_dpg.mvRadioButton -mvTabBar=internal_dpg.mvTabBar -mvTab=internal_dpg.mvTab -mvImage=internal_dpg.mvImage -mvMenuBar=internal_dpg.mvMenuBar -mvViewportMenuBar=internal_dpg.mvViewportMenuBar -mvMenu=internal_dpg.mvMenu -mvMenuItem=internal_dpg.mvMenuItem -mvChildWindow=internal_dpg.mvChildWindow -mvGroup=internal_dpg.mvGroup -mvSliderFloat=internal_dpg.mvSliderFloat -mvSliderInt=internal_dpg.mvSliderInt -mvFilterSet=internal_dpg.mvFilterSet -mvDragFloat=internal_dpg.mvDragFloat -mvDragInt=internal_dpg.mvDragInt -mvInputFloat=internal_dpg.mvInputFloat -mvInputInt=internal_dpg.mvInputInt -mvColorEdit=internal_dpg.mvColorEdit -mvClipper=internal_dpg.mvClipper -mvColorPicker=internal_dpg.mvColorPicker -mvTooltip=internal_dpg.mvTooltip -mvCollapsingHeader=internal_dpg.mvCollapsingHeader -mvSeparator=internal_dpg.mvSeparator -mvCheckbox=internal_dpg.mvCheckbox -mvListbox=internal_dpg.mvListbox -mvText=internal_dpg.mvText -mvCombo=internal_dpg.mvCombo -mvPlot=internal_dpg.mvPlot -mvSimplePlot=internal_dpg.mvSimplePlot -mvDrawlist=internal_dpg.mvDrawlist -mvWindowAppItem=internal_dpg.mvWindowAppItem -mvSelectable=internal_dpg.mvSelectable -mvTreeNode=internal_dpg.mvTreeNode -mvProgressBar=internal_dpg.mvProgressBar -mvSpacer=internal_dpg.mvSpacer -mvImageButton=internal_dpg.mvImageButton -mvTimePicker=internal_dpg.mvTimePicker -mvDatePicker=internal_dpg.mvDatePicker -mvColorButton=internal_dpg.mvColorButton -mvFileDialog=internal_dpg.mvFileDialog -mvTabButton=internal_dpg.mvTabButton -mvDrawNode=internal_dpg.mvDrawNode -mvNodeEditor=internal_dpg.mvNodeEditor -mvNode=internal_dpg.mvNode -mvNodeAttribute=internal_dpg.mvNodeAttribute -mvTable=internal_dpg.mvTable -mvTableColumn=internal_dpg.mvTableColumn -mvTableRow=internal_dpg.mvTableRow -mvSyncedTables=internal_dpg.mvSyncedTables -mvDrawLine=internal_dpg.mvDrawLine -mvDrawArrow=internal_dpg.mvDrawArrow -mvDrawTriangle=internal_dpg.mvDrawTriangle -mvDrawImageQuad=internal_dpg.mvDrawImageQuad -mvDrawCircle=internal_dpg.mvDrawCircle -mvDrawEllipse=internal_dpg.mvDrawEllipse -mvDrawBezierCubic=internal_dpg.mvDrawBezierCubic -mvDrawBezierQuadratic=internal_dpg.mvDrawBezierQuadratic -mvDrawQuad=internal_dpg.mvDrawQuad -mvDrawRect=internal_dpg.mvDrawRect -mvDrawText=internal_dpg.mvDrawText -mvDrawPolygon=internal_dpg.mvDrawPolygon -mvDrawPolyline=internal_dpg.mvDrawPolyline -mvDrawImage=internal_dpg.mvDrawImage -mvDragFloatMulti=internal_dpg.mvDragFloatMulti -mvDragIntMulti=internal_dpg.mvDragIntMulti -mvSliderFloatMulti=internal_dpg.mvSliderFloatMulti -mvSliderIntMulti=internal_dpg.mvSliderIntMulti -mvInputIntMulti=internal_dpg.mvInputIntMulti -mvInputFloatMulti=internal_dpg.mvInputFloatMulti -mvDragPoint=internal_dpg.mvDragPoint -mvDragLine=internal_dpg.mvDragLine -mvDragRect=internal_dpg.mvDragRect -mvAnnotation=internal_dpg.mvAnnotation -mvAxisTag=internal_dpg.mvAxisTag -mvLineSeries=internal_dpg.mvLineSeries -mvScatterSeries=internal_dpg.mvScatterSeries -mvStemSeries=internal_dpg.mvStemSeries -mvStairSeries=internal_dpg.mvStairSeries -mvBarSeries=internal_dpg.mvBarSeries -mvBarGroupSeries=internal_dpg.mvBarGroupSeries -mvErrorSeries=internal_dpg.mvErrorSeries -mvInfLineSeries=internal_dpg.mvInfLineSeries -mvHeatSeries=internal_dpg.mvHeatSeries -mvImageSeries=internal_dpg.mvImageSeries -mvPieSeries=internal_dpg.mvPieSeries -mvShadeSeries=internal_dpg.mvShadeSeries -mvLabelSeries=internal_dpg.mvLabelSeries -mvHistogramSeries=internal_dpg.mvHistogramSeries -mvDigitalSeries=internal_dpg.mvDigitalSeries -mv2dHistogramSeries=internal_dpg.mv2dHistogramSeries -mvCandleSeries=internal_dpg.mvCandleSeries -mvAreaSeries=internal_dpg.mvAreaSeries -mvColorMapScale=internal_dpg.mvColorMapScale -mvSlider3D=internal_dpg.mvSlider3D -mvKnobFloat=internal_dpg.mvKnobFloat -mvLoadingIndicator=internal_dpg.mvLoadingIndicator -mvNodeLink=internal_dpg.mvNodeLink -mvTextureRegistry=internal_dpg.mvTextureRegistry -mvStaticTexture=internal_dpg.mvStaticTexture -mvDynamicTexture=internal_dpg.mvDynamicTexture -mvStage=internal_dpg.mvStage -mvDrawLayer=internal_dpg.mvDrawLayer -mvViewportDrawlist=internal_dpg.mvViewportDrawlist -mvFileExtension=internal_dpg.mvFileExtension -mvPlotLegend=internal_dpg.mvPlotLegend -mvPlotAxis=internal_dpg.mvPlotAxis -mvHandlerRegistry=internal_dpg.mvHandlerRegistry -mvKeyDownHandler=internal_dpg.mvKeyDownHandler -mvKeyPressHandler=internal_dpg.mvKeyPressHandler -mvKeyReleaseHandler=internal_dpg.mvKeyReleaseHandler -mvMouseMoveHandler=internal_dpg.mvMouseMoveHandler -mvMouseWheelHandler=internal_dpg.mvMouseWheelHandler -mvMouseClickHandler=internal_dpg.mvMouseClickHandler -mvMouseDoubleClickHandler=internal_dpg.mvMouseDoubleClickHandler -mvMouseDownHandler=internal_dpg.mvMouseDownHandler -mvMouseReleaseHandler=internal_dpg.mvMouseReleaseHandler -mvMouseDragHandler=internal_dpg.mvMouseDragHandler -mvHoverHandler=internal_dpg.mvHoverHandler -mvActiveHandler=internal_dpg.mvActiveHandler -mvFocusHandler=internal_dpg.mvFocusHandler -mvVisibleHandler=internal_dpg.mvVisibleHandler -mvEditedHandler=internal_dpg.mvEditedHandler -mvActivatedHandler=internal_dpg.mvActivatedHandler -mvDeactivatedHandler=internal_dpg.mvDeactivatedHandler -mvDeactivatedAfterEditHandler=internal_dpg.mvDeactivatedAfterEditHandler -mvToggledOpenHandler=internal_dpg.mvToggledOpenHandler -mvClickedHandler=internal_dpg.mvClickedHandler -mvDoubleClickedHandler=internal_dpg.mvDoubleClickedHandler -mvScrollHandler=internal_dpg.mvScrollHandler -mvDragPayload=internal_dpg.mvDragPayload -mvResizeHandler=internal_dpg.mvResizeHandler -mvFont=internal_dpg.mvFont -mvFontRegistry=internal_dpg.mvFontRegistry -mvTheme=internal_dpg.mvTheme -mvThemeColor=internal_dpg.mvThemeColor -mvThemeStyle=internal_dpg.mvThemeStyle -mvThemeComponent=internal_dpg.mvThemeComponent -mvCharRemap=internal_dpg.mvCharRemap -mvValueRegistry=internal_dpg.mvValueRegistry -mvIntValue=internal_dpg.mvIntValue -mvFloatValue=internal_dpg.mvFloatValue -mvFloat4Value=internal_dpg.mvFloat4Value -mvInt4Value=internal_dpg.mvInt4Value -mvBoolValue=internal_dpg.mvBoolValue -mvStringValue=internal_dpg.mvStringValue -mvDoubleValue=internal_dpg.mvDoubleValue -mvDouble4Value=internal_dpg.mvDouble4Value -mvColorValue=internal_dpg.mvColorValue -mvFloatVectValue=internal_dpg.mvFloatVectValue -mvSeriesValue=internal_dpg.mvSeriesValue -mvRawTexture=internal_dpg.mvRawTexture -mvSubPlots=internal_dpg.mvSubPlots -mvColorMap=internal_dpg.mvColorMap -mvColorMapRegistry=internal_dpg.mvColorMapRegistry -mvColorMapButton=internal_dpg.mvColorMapButton -mvColorMapSlider=internal_dpg.mvColorMapSlider -mvTemplateRegistry=internal_dpg.mvTemplateRegistry -mvTableCell=internal_dpg.mvTableCell -mvItemHandlerRegistry=internal_dpg.mvItemHandlerRegistry -mvInputDouble=internal_dpg.mvInputDouble -mvInputDoubleMulti=internal_dpg.mvInputDoubleMulti -mvDragDouble=internal_dpg.mvDragDouble -mvDragDoubleMulti=internal_dpg.mvDragDoubleMulti -mvSliderDouble=internal_dpg.mvSliderDouble -mvSliderDoubleMulti=internal_dpg.mvSliderDoubleMulti -mvCustomSeries=internal_dpg.mvCustomSeries -mvReservedUUID_0=internal_dpg.mvReservedUUID_0 -mvReservedUUID_1=internal_dpg.mvReservedUUID_1 -mvReservedUUID_2=internal_dpg.mvReservedUUID_2 -mvReservedUUID_3=internal_dpg.mvReservedUUID_3 -mvReservedUUID_4=internal_dpg.mvReservedUUID_4 -mvReservedUUID_5=internal_dpg.mvReservedUUID_5 -mvReservedUUID_6=internal_dpg.mvReservedUUID_6 -mvReservedUUID_7=internal_dpg.mvReservedUUID_7 -mvReservedUUID_8=internal_dpg.mvReservedUUID_8 -mvReservedUUID_9=internal_dpg.mvReservedUUID_9 -mvReservedUUID_10=internal_dpg.mvReservedUUID_10 diff --git a/dearpygui/demo.py b/dearpygui/demo.py deleted file mode 100644 index e938e654a..000000000 --- a/dearpygui/demo.py +++ /dev/null @@ -1,3398 +0,0 @@ -import dearpygui.dearpygui as dpg -import math -from math import sin, cos, log10 -import random -import webbrowser - -count_2d_histogram = 50_000 -xybin_2d_histogram = [100, 100] -t_digital_plot = 0 - -def _help(message): - last_item = dpg.last_item() - with dpg.group(horizontal=True) as group: - dpg.move_item(last_item, parent=group) - t = dpg.add_text("(?)", color=[0, 255, 0]) - with dpg.tooltip(t): - dpg.add_text(message) - -def _hyperlink(text, address): - b = dpg.add_button(label=text, callback=lambda:webbrowser.open(address)) - dpg.bind_item_theme(b, "__demo_hyperlinkTheme") - -def _config(sender, keyword, user_data): - widget_type = dpg.get_item_type(sender) - items = user_data - - if widget_type == "mvAppItemType::mvRadioButton": - value = True - else: - keyword = dpg.get_item_label(sender) - value = dpg.get_value(sender) - - if isinstance(user_data, list): - for item in items: - dpg.configure_item(item, **{keyword: value}) - else: - dpg.configure_item(items, **{keyword: value}) - -def _add_config_options(item, columns, *names, **kwargs): - if columns == 1: - if 'before' in kwargs: - for name in names: - dpg.add_checkbox(label=name, callback=_config, user_data=item, before=kwargs['before'], default_value=dpg.get_item_configuration(item)[name]) - else: - for name in names: - dpg.add_checkbox(label=name, callback=_config, user_data=item, default_value=dpg.get_item_configuration(item)[name]) - else: - if 'before' in kwargs: - dpg.push_container_stack(dpg.add_table(header_row=False, before=kwargs['before'])) - else: - dpg.push_container_stack(dpg.add_table(header_row=False)) - - for i in range(columns): - dpg.add_table_column() - - for i in range((len(names)+(columns - 1))//columns): - with dpg.table_row(): - for j in range(columns): - if (i*columns + j) >= len(names): - break - dpg.add_checkbox(label=names[i*columns + j], - callback=_config, user_data=item, - default_value=dpg.get_item_configuration(item)[names[i*columns + j]]) - dpg.pop_container_stack() - -def _add_config_option(item, default_value, *names): - dpg.add_radio_button(names, default_value=default_value, callback=_config, user_data=item) - -def _hsv_to_rgb(h, s, v): - if s == 0.0: return (v, v, v) - i = int(h*6.) # XXX assume int() truncates! - f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6 - if i == 0: return (255*v, 255*t, 255*p) - if i == 1: return (255*q, 255*v, 255*p) - if i == 2: return (255*p, 255*v, 255*t) - if i == 3: return (255*p, 255*q, 255*v) - if i == 4: return (255*t, 255*p, 255*v) - if i == 5: return (255*v, 255*p, 255*q) - -def _create_static_textures(): - - ## create static textures - texture_data1 = [] - for i in range(100*100): - texture_data1.append(255/255) - texture_data1.append(0) - texture_data1.append(255/255) - texture_data1.append(255/255) - - texture_data2 = [] - for i in range(50*50): - texture_data2.append(255/255) - texture_data2.append(255/255) - texture_data2.append(0) - texture_data2.append(255/255) - - texture_data3 = [] - for row in range(50): - for column in range(50): - texture_data3.append(255/255) - texture_data3.append(0) - texture_data3.append(0) - texture_data3.append(255/255) - for column in range(50): - texture_data3.append(0) - texture_data3.append(255/255) - texture_data3.append(0) - texture_data3.append(255/255) - for row in range(50): - for column in range(50): - texture_data3.append(0) - texture_data3.append(0) - texture_data3.append(255/255) - texture_data3.append(255/255) - for column in range(50): - texture_data3.append(255/255) - texture_data3.append(255/255) - texture_data3.append(0) - texture_data3.append(255/255) - - dpg.add_static_texture(100, 100, texture_data1, parent="__demo_texture_container", tag="__demo_static_texture_1", label="Static Texture 1") - dpg.add_static_texture(50, 50, texture_data2, parent="__demo_texture_container", tag="__demo_static_texture_2", label="Static Texture 2") - dpg.add_static_texture(100, 100, texture_data3, parent="__demo_texture_container", tag="__demo_static_texture_3", label="Static Texture 3") - -def _create_dynamic_textures(): - - ## create dynamic textures - texture_data1 = [] - for i in range(100*100): - texture_data1.append(255/255) - texture_data1.append(0) - texture_data1.append(255/255) - texture_data1.append(255/255) - - texture_data2 = [] - for i in range(50*50): - texture_data2.append(255/255) - texture_data2.append(255/255) - texture_data2.append(0) - texture_data2.append(255/255) - - dpg.add_dynamic_texture(100, 100, texture_data1, parent="__demo_texture_container", tag="__demo_dynamic_texture_1") - dpg.add_dynamic_texture(50, 50, texture_data2, parent="__demo_texture_container", tag="__demo_dynamic_texture_2") - -def _update_dynamic_textures(sender, app_data, user_data): - - new_color = app_data - new_color[0] = new_color[0] - new_color[1] = new_color[1] - new_color[2] = new_color[2] - new_color[3] = new_color[3] - - if user_data == 1: - texture_data = [] - for i in range(100*100): - texture_data.append(new_color[0]) - texture_data.append(new_color[1]) - texture_data.append(new_color[2]) - texture_data.append(new_color[3]) - dpg.set_value("__demo_dynamic_texture_1", texture_data) - - elif user_data == 2: - texture_data = [] - for i in range(50*50): - texture_data.append(new_color[0]) - texture_data.append(new_color[1]) - texture_data.append(new_color[2]) - texture_data.append(new_color[3]) - dpg.set_value("__demo_dynamic_texture_2", texture_data) - -def _on_demo_close(sender, app_data, user_data): - dpg.delete_item(sender) - dpg.delete_item("__demo_texture_container") - dpg.delete_item("__demo_colormap_registry") - dpg.delete_item("__demo_hyperlinkTheme") - dpg.delete_item("__demo_theme_progressbar") - dpg.delete_item("stock_theme1") - dpg.delete_item("stock_theme2") - dpg.delete_item("stock_theme3") - dpg.delete_item("stock_theme4") - dpg.delete_item("stem_theme1") - dpg.delete_item("__demo_keyboard_handler") - dpg.delete_item("__demo_mouse_handler") - dpg.delete_item("__demo_filedialog") - dpg.delete_item("__demo_stage1") - dpg.delete_item("__demo_popup1") - dpg.delete_item("__demo_popup2") - dpg.delete_item("__demo_popup3") - dpg.delete_item("__demo_item_reg3") - dpg.delete_item("__demo_item_reg6") - dpg.delete_item("__demo_item_reg7") - dpg.delete_item("demoitemregistry") - for i in range(7): - dpg.delete_item("__demo_theme"+str(i)) - dpg.delete_item("__demo_theme2_"+str(i)) - for i in range(5): - dpg.delete_item("__demo_item_reg1_"+str(i)) - dpg.delete_item("__demo_item_reg2_"+str(i)) - for i in range(3): - dpg.delete_item("__demo_item_reg4_"+str(i)) - for i in range(4): - dpg.delete_item("__demo_item_reg5_"+str(i)) - -def show_demo(): - - dpg.add_texture_registry(label="Demo Texture Container", tag="__demo_texture_container") - dpg.add_colormap_registry(label="Demo Colormap Registry", tag="__demo_colormap_registry") - - with dpg.theme(tag="__demo_hyperlinkTheme"): - with dpg.theme_component(dpg.mvButton): - dpg.add_theme_color(dpg.mvThemeCol_Button, [0, 0, 0, 0]) - dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, [0, 0, 0, 0]) - dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, [29, 151, 236, 25]) - dpg.add_theme_color(dpg.mvThemeCol_Text, [29, 151, 236]) - - def _log(sender, app_data, user_data): - print(f"sender: {sender}, \t app_data: {app_data}, \t user_data: {user_data}") - - _create_static_textures() - _create_dynamic_textures() - - with dpg.window(label="Dear PyGui Demo", width=800, height=800, on_close=_on_demo_close, pos=(100, 100), tag="__demo_id"): - - with dpg.menu_bar(): - - with dpg.menu(label="Menu"): - - dpg.add_text("This menu is just for show!") - dpg.add_menu_item(label="New") - dpg.add_menu_item(label="Open") - - with dpg.menu(label="Open Recent"): - - dpg.add_menu_item(label="harrel.c") - dpg.add_menu_item(label="patty.h") - dpg.add_menu_item(label="nick.py") - - dpg.add_menu_item(label="Save") - dpg.add_menu_item(label="Save As...") - - with dpg.menu(label="Settings"): - - dpg.add_menu_item(label="Option 1", callback=_log) - dpg.add_menu_item(label="Option 2", check=True, callback=_log) - dpg.add_menu_item(label="Option 3", check=True, default_value=True, callback=_log) - - with dpg.child_window(height=60, autosize_x=True): - for i in range(10): - dpg.add_text(f"Scrolling Text{i}") - - dpg.add_slider_float(label="Slider Float") - dpg.add_input_int(label="Input Int") - dpg.add_combo(("Yes", "No", "Maybe"), label="Combo") - - with dpg.menu(label="Tools"): - - dpg.add_menu_item(label="Show About", callback=lambda:dpg.show_tool(dpg.mvTool_About)) - dpg.add_menu_item(label="Show Metrics", callback=lambda:dpg.show_tool(dpg.mvTool_Metrics)) - dpg.add_menu_item(label="Show Documentation", callback=lambda:dpg.show_tool(dpg.mvTool_Doc)) - dpg.add_menu_item(label="Show Debug", callback=lambda:dpg.show_tool(dpg.mvTool_Debug)) - dpg.add_menu_item(label="Show Style Editor", callback=lambda:dpg.show_tool(dpg.mvTool_Style)) - dpg.add_menu_item(label="Show Font Manager", callback=lambda:dpg.show_tool(dpg.mvTool_Font)) - dpg.add_menu_item(label="Show Item Registry", callback=lambda:dpg.show_tool(dpg.mvTool_ItemRegistry)) - dpg.add_menu_item(label="Show Stack Tool", callback=lambda:dpg.show_tool(dpg.mvTool_Stack)) - - with dpg.menu(label="Settings"): - - dpg.add_menu_item(label="Wait For Input", check=True, callback=lambda s, a: dpg.configure_app(wait_for_input=a)) - dpg.add_menu_item(label="Toggle Fullscreen", callback=lambda:dpg.toggle_viewport_fullscreen()) - - with dpg.group(horizontal=True): - dpg.add_loading_indicator(circle_count=4) - with dpg.group(): - dpg.add_text(f'Dear PyGui says hello. ({dpg.get_dearpygui_version()})') - with dpg.group(horizontal=True): - dpg.add_text("The code for the most recent version of this demo can be found here:") - _hyperlink("demo.py", "https://github.com/hoffstadt/DearPyGui/blob/master/dearpygui/demo.py") - - with dpg.collapsing_header(label="Window Options"): - - _add_config_options("__demo_id", 3, - "no_title_bar", "no_scrollbar", "menubar", - "no_move", "no_resize", "no_collapse", - "no_close", "no_background", "no_bring_to_front_on_focus", - "unsaved_document" - ) - - with dpg.collapsing_header(label="Widgets"): - - with dpg.tree_node(label="Basic"): - - with dpg.group(horizontal=True): - dpg.add_button(label="Button", callback=_log) - dpg.add_button(label="Button", callback=_log, small=True) - dpg.add_button(label="Button", callback=_log, arrow=True) # default direction is mvDir_Up - dpg.add_button(label="Button", callback=_log, arrow=True, direction=dpg.mvDir_Left) - dpg.add_button(label="Button", callback=_log, arrow=True, direction=dpg.mvDir_Right) - dpg.add_button(label="Button", callback=_log, arrow=True, direction=dpg.mvDir_Down) - - dpg.add_button(label="Hold me button", callback=_log, repeat=True) - - dpg.add_checkbox(label="checkbox", callback=_log) - dpg.add_radio_button(("radio a", "radio b", "radio c"), callback=_log, horizontal=True) - dpg.add_selectable(label="selectable", callback=_log) - - with dpg.group(horizontal=True): - - for i in range(7): - - with dpg.theme(tag="__demo_theme"+str(i)): - with dpg.theme_component(dpg.mvButton): - dpg.add_theme_color(dpg.mvThemeCol_Button, _hsv_to_rgb(i/7.0, 0.6, 0.6)) - dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, _hsv_to_rgb(i/7.0, 0.8, 0.8)) - dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, _hsv_to_rgb(i/7.0, 0.7, 0.7)) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, i*5) - dpg.add_theme_style(dpg.mvStyleVar_FramePadding, i*3, i*3) - - dpg.add_button(label="Click", callback=_log) - dpg.bind_item_theme(dpg.last_item(), "__demo_theme"+str(i)) - - with dpg.group(horizontal=True): - - dpg.add_text("Press a button: ") - widget = dpg.add_text("0") - dpg.add_button(arrow=True, direction=dpg.mvDir_Left, user_data=widget, callback=lambda s, a, u: dpg.set_value(u, int(dpg.get_value(u))-1)) - dpg.add_button(arrow=True, direction=dpg.mvDir_Right, user_data=widget, callback=lambda s, a, u: dpg.set_value(u, int(dpg.get_value(u))+1)) - - dpg.add_text("hover me") - with dpg.tooltip(dpg.last_item()): - dpg.add_text("I'm a simple tooltip!") - - dpg.add_separator(label="This is a separator with text") - - dpg.add_text("Value", label="Label", show_label=True) - dpg.add_combo(("AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK"), label="combo", default_value="AAAA", callback=_log) - dpg.add_input_text(label="input text", default_value="Hello, world!", callback=_log) - _help( - "USER:\n" - "Hold SHIFT or use mouse to select text.\n" - "CTRL+Left/Right to word jump.\n" - "CTRL+A or double-click to select all.\n" - "CTRL+X,CTRL+C,CTRL+V clipboard.\n" - "CTRL+Z,CTRL+Y undo/redo.\n" - "ESCAPE to revert.\n\n") - dpg.add_input_text(label="input text (w/ hint)", hint="enter text here", callback=_log) - dpg.add_input_int(label="input int", callback=_log) - dpg.add_input_float(label="input float", callback=_log, format="%.06f") - dpg.add_input_float(label="input float scientific", format="%e", callback=_log) - dpg.add_input_floatx(label="input floatx", callback=_log, default_value=[1,2,3,4]) - dpg.add_input_double(label="input double", callback=_log, format="%.14f") - dpg.add_input_doublex(label="input doublex", callback=_log, default_value=[1,2,3,4], format="%.14f") - dpg.add_drag_int(label="drag int", callback=_log) - _help( - "Click and drag to edit value.\n" - "Hold SHIFT/ALT for faster/slower edit.\n" - "Double-click or CTRL+click to input value.") - dpg.add_drag_int(label="drag int 0..100", format="%d%%", callback=_log) - dpg.add_drag_float(label="drag float", callback=_log) - dpg.add_drag_float(label="drag small float", default_value=0.0067, format="%.06f ns", callback=_log) - dpg.add_slider_int(label="slider int", max_value=3, callback=_log) - _help("CTRL+click to enter value.") - dpg.add_slider_float(label="slider float", max_value=1.0, format="ratio = %.3f", callback=_log) - dpg.add_slider_double(label="slider double", max_value=1.0, format="ratio = %.14f", callback=_log) - dpg.add_slider_int(label="slider angle", min_value=-360, max_value=360, format="%d deg", callback=_log) - dpg.add_color_edit((102, 179, 0, 128), label="color edit 4", callback=_log) - _help( - "Click on the colored square to open a color picker.\n" - "Click and hold to use drag and drop.\n" - "Right-click on the colored square to show options.\n" - "CTRL+click on individual component to input value.\n") - dpg.add_color_edit(default_value=(.5, 1, .25, .1), label="color edit 4", callback=_log) - dpg.add_listbox(("Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon"), label="listbox", num_items=4, callback=_log) - dpg.add_color_button() - - with dpg.tree_node(label="Combo"): - - items = ("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z") - combo_id = dpg.add_combo(items, label="combo", height_mode=dpg.mvComboHeight_Small, tag="combo_demo") - _add_config_options(combo_id, 1, "popup_align_left", "no_arrow_button", "no_preview", "fit_width") - def change_combo_height(sender, app_data, user_data): - if app_data == "mvComboHeight_Small": - dpg.configure_item("combo_demo", height_mode=dpg.mvComboHeight_Small) - elif app_data == "mvComboHeight_Regular": - dpg.configure_item("combo_demo", height_mode=dpg.mvComboHeight_Regular) - elif app_data == "mvComboHeight_Large": - dpg.configure_item("combo_demo", height_mode=dpg.mvComboHeight_Large) - elif app_data == "mvComboHeight_Largest": - dpg.configure_item("combo_demo", height_mode=dpg.mvComboHeight_Largest) - dpg.add_radio_button(("mvComboHeight_Small", "mvComboHeight_Regular", "mvComboHeight_Large", "mvComboHeight_Largest"), callback=change_combo_height, user_data=combo_id, horizontal=True) - - with dpg.tree_node(label="Color Picker & Edit"): - - _color_picker_id = dpg.generate_uuid() - _color_edit_id = dpg.generate_uuid() - - def _color_picker_configs(sender, value, user_data): - - _old_config = dpg.get_item_configuration(user_data) - - if user_data ==_color_picker_id: - picker_mode = _old_config["picker_mode"] - else: - display_mode = _old_config["display_mode"] - alpha_preview = _old_config["alpha_preview"] - display_type = _old_config["display_type"] - input_mode = _old_config["input_mode"] - - # picker_mode - if value == "mvColorPicker_bar": - picker_mode=dpg.mvColorPicker_bar - elif value == "mvColorPicker_wheel": - picker_mode = dpg.mvColorPicker_wheel - - # alpha_preview - elif value == "mvColorEdit_AlphaPreviewNone": - alpha_preview=dpg.mvColorEdit_AlphaPreviewNone - elif value == "mvColorEdit_AlphaPreview": - alpha_preview = dpg.mvColorEdit_AlphaPreview - elif value == "mvColorEdit_AlphaPreviewHalf": - alpha_preview = dpg.mvColorEdit_AlphaPreviewHalf - - # display_type - elif value == "mvColorEdit_uint8": - display_type=dpg.mvColorEdit_uint8 - elif value == "mvColorEdit_float": - display_type = dpg.mvColorEdit_float - - # display_type - elif value == "mvColorEdit_uint8": - display_type=dpg.mvColorEdit_uint8 - elif value == "mvColorEdit_float": - display_type = dpg.mvColorEdit_float - - # display_mode - elif value == "mvColorEdit_rgb": - display_mode=dpg.mvColorEdit_rgb - elif value == "mvColorEdit_hsv": - display_mode = dpg.mvColorEdit_hsv - elif value == "mvColorEdit_hex": - display_mode = dpg.mvColorEdit_hex - - if user_data ==_color_picker_id: - dpg.configure_item(user_data, - picker_mode=picker_mode, - alpha_preview=alpha_preview, - display_type=display_type, - input_mode=input_mode - ) - else: - dpg.configure_item(user_data, - alpha_preview=alpha_preview, - display_type=display_type, - input_mode=input_mode, - display_mode=display_mode - ) - - dpg.add_text("Color Picker") - - with dpg.group(horizontal=True) as _before_id: - dpg.add_text("picker_mode:") - dpg.add_radio_button(("mvColorPicker_bar", "mvColorPicker_wheel"), callback=_color_picker_configs, - user_data=_color_picker_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("alpha_preview:") - dpg.add_radio_button(("mvColorEdit_AlphaPreviewNone", "mvColorEdit_AlphaPreview", "mvColorEdit_AlphaPreviewHalf"), callback=_color_picker_configs, - user_data=_color_picker_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("display_type:") - dpg.add_radio_button(("mvColorEdit_uint8", "mvColorEdit_float"), callback=_color_picker_configs, - user_data=_color_picker_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("input_mode:") - dpg.add_radio_button(("mvColorEdit_input_rgb", "mvColorEdit_input_hsv"), callback=_color_picker_configs, - user_data=_color_picker_id, horizontal=True) - - dpg.add_color_picker((255, 0, 255, 200), label="Color Picker", alpha_preview=dpg.mvColorEdit_AlphaPreviewNone, no_alpha=False, alpha_bar=True, - width=200, tag=_color_picker_id) - - _add_config_options(_color_picker_id, 3, - "no_alpha", "no_side_preview", "display_rgb", - "display_hsv", "display_hex", - "no_small_preview", "no_inputs", "no_tooltip", - "no_label", "alpha_bar", before=_before_id) - - dpg.add_separator() - - dpg.add_text("Color Edit") - - with dpg.group(horizontal=True): - _before_id = dpg.add_text("alpha_preview:") - dpg.add_radio_button(("mvColorEdit_AlphaPreviewNone", "mvColorEdit_AlphaPreview", "mvColorEdit_AlphaPreviewHalf"), callback=_color_picker_configs, - user_data=_color_edit_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("display_type:") - dpg.add_radio_button(("mvColorEdit_uint8", "mvColorEdit_float"), callback=_color_picker_configs, - user_data=_color_edit_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("display_mode:") - dpg.add_radio_button(("mvColorEdit_rgb", "mvColorEdit_hsv", "mvColorEdit_hex"), callback=_color_picker_configs, - user_data=_color_edit_id, horizontal=True) - - with dpg.group(horizontal=True): - dpg.add_text("input_mode:") - dpg.add_radio_button(("mvColorEdit_input_rgb", "mvColorEdit_input_hsv"), callback=_color_picker_configs, - user_data=_color_edit_id, horizontal=True) - - dpg.add_color_edit((255, 0, 255, 255), label="Color Edit", - width=200, tag=_color_edit_id) - - _add_config_options(_color_edit_id, 3, - "no_alpha", "no_picker", - "no_options", "no_inputs", "no_small_preview", - "no_tooltip", "no_label", - "no_drag_drop", "alpha_bar", before=_before_id) - - with dpg.tree_node(label="Colormaps"): - dpg.add_text("Notes") - dpg.add_text("Colormaps belong to a mvColorMapRegistry.", bullet=True, indent=20) - with dpg.group(horizontal=True): - dpg.add_text("Showing the registry will help with debugging. Press ", bullet=True, indent=20) - dpg.add_button(label="here", small=True, callback=lambda:dpg.show_item("__demo_colormap_registry")) - dpg.add_text("Colormaps are applied with 'bind_colormap(item_id, colormap_id)", bullet=True, indent=20) - dpg.add_text("Colormaps can be applied to mvPlot, mvColorMapButton, mvColorMapSlider, mvColorMapScale", bullet=True, indent=20) - dpg.add_text("Colormaps can be sampled with 'sample_colormap(colormap_id, t)' (0 10: - dpg.set_x_scroll(user_data[1], x_scroll-10) - elif user_data[0] == "left": - dpg.set_x_scroll(user_data[1], 0) - - if user_data[0] == "right" and x_scroll < max_scroll-10: - dpg.set_x_scroll(user_data[1], x_scroll+10) - elif user_data[0] == "right": - dpg.set_x_scroll(user_data[1], max_scroll) - - with dpg.group(horizontal=True): - dpg.add_button(label="<<", small=True, user_data=["left", _child_id], callback=_scroll_programmatically) - dpg.add_text("Scroll from code") - dpg.add_button(label=">>", small=True, user_data=["right", _child_id], callback=_scroll_programmatically) - _text_id = dpg.add_text("0/0") - with dpg.item_handler_registry(tag="__demo_item_reg3"): - dpg.add_item_visible_handler(user_data=[_text_id, _child_id], callback=_update_xscroll_info) - dpg.bind_item_handler_registry(_text_id, dpg.last_container()) - - with dpg.collapsing_header(label="Textures & Images"): - - with dpg.tree_node(label="Help"): - - dpg.add_separator() - dpg.add_text("ABOUT TEXTURES:") - dpg.add_text("Textures are buffers of RGBA data.", bullet=True, indent=20) - dpg.add_text("Textures are used by 'image based' widgets:", bullet=True, indent=20) - dpg.add_text("add_image", bullet=True, indent=50) - dpg.add_text("add_image_button", bullet=True, indent=50) - dpg.add_text("draw_image", bullet=True, indent=50) - dpg.add_text("add_image_series", bullet=True, indent=50) - dpg.add_text("Textures are themselves widgets.", bullet=True, indent=20) - dpg.add_text("Textures must be a child of a texture container widget.", bullet=True, indent=20) - dpg.add_text("Textures can be either static or dynamic (see following sections).", bullet=True, indent=20) - - dpg.add_separator() - dpg.add_text("PROGRAMMER GUIDE:") - dpg.add_text("'image based' widgets hold a reference to a texture widget.", bullet=True, indent=20) - dpg.add_text("Deleting the texture widget will not affect widget's using it.", bullet=True, indent=50) - dpg.add_text("Textures are only free'd from the GPU when the reference count reaches 0.", bullet=True, indent=50) - dpg.add_text("The texture container widget is a root (has no parent).", bullet=True, indent=20) - dpg.add_text("The texture container widget is hidden by default.", bullet=True, indent=20) - with dpg.group(horizontal=True): - dpg.add_text("'Showing' it, opens a manager to inspect the textures within.", bullet=True, indent=50) - dpg.add_button(label="Press Here", small=True, callback=lambda:dpg.configure_item("__demo_texture_container", show=True)) - dpg.add_separator() - - with dpg.tree_node(label="Static Textures"): - - dpg.add_separator() - dpg.add_text("ABOUT STATIC TEXTURES:") - dpg.add_text("Can NOT be modified after creation.", bullet=True, indent=20) - dpg.add_text("Can be loaded from a file using the 'file' keyword.", bullet=True, indent=20) - dpg.add_separator() - - with dpg.group(horizontal=True): - - with dpg.group(): - dpg.add_text("Image Button") - dpg.add_image_button("__demo_static_texture_1") - - with dpg.group(): - dpg.add_text("Image") - dpg.add_image("__demo_static_texture_2") - - with dpg.group(): - dpg.add_text("Image (texture size)") - dpg.add_image("__demo_static_texture_3") - - with dpg.group(): - dpg.add_text("Image (2x texture size)") - dpg.add_image("__demo_static_texture_3", width=200, height=200) - - dpg.add_image(dpg.mvFontAtlas) - - with dpg.tree_node(label="Dynamic Textures"): - - dpg.add_separator() - dpg.add_text("ABOUT DYNAMIC TEXTURES:") - dpg.add_text("Can be modified after creation with 'set_value'.", bullet=True, indent=20) - dpg.add_text("New data must be the same dimensions as the original", bullet=True, indent=20) - dpg.add_separator() - - with dpg.group(horizontal=True): - - with dpg.group(): - dpg.add_color_picker((255, 0, 255, 255), label="Texture 1", - no_side_preview=True, alpha_bar=True, width=200, - callback=_update_dynamic_textures, user_data=1) - dpg.add_text("Image Button") - dpg.add_image_button("__demo_dynamic_texture_1", width=100, height=100) - - - with dpg.group(): - dpg.add_color_picker((255, 255, 0, 255), label="Texture 2", - no_side_preview=True, alpha_bar=True, width=200, - callback=_update_dynamic_textures, user_data=2) - dpg.add_text("Image") - dpg.add_image("__demo_dynamic_texture_2") - - with dpg.tree_node(label="Image Series (plots)"): - - with dpg.plot(label="Image Plot", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x axis") - with dpg.plot_axis(dpg.mvYAxis, label="y axis"): - dpg.add_image_series(dpg.mvFontAtlas, [300, 300], [400, 400], label="font atlas") - dpg.add_image_series("__demo_static_texture_1", [0, 0], [100, 100], label="static 1") - dpg.add_image_series("__demo_static_texture_2", [150, 150], [200, 200], label="static 2") - dpg.add_image_series("__demo_static_texture_3", [200, -150], [300, -50], label="static 3") - dpg.add_image_series("__demo_dynamic_texture_1", [-200, 100], [-100, 200], label="dynamic 1") - dpg.add_image_series("__demo_dynamic_texture_2", [-200, -100], [-150, -50], label="dynamic 2") - - with dpg.tree_node(label="Drawlists"): - - with dpg.drawlist(width=400, height=300): - dpg.draw_rectangle((0, 0), (400, 300), color=(100, 100, 100, 250), thickness=2) - dpg.draw_image("__demo_static_texture_3", [0, 0], [100, 100]) - dpg.draw_image("__demo_dynamic_texture_1", [200, 100], [300, 200]) - - with dpg.collapsing_header(label="Popups & Modal Windows"): - - with dpg.tree_node(label="Popups"): - - popup_values = ["Bream", "Haddock", "Mackerel", "Pollock", "Tilefish"] - - dpg.add_text("This is a light wrapper over a window.", bullet=True) - dpg.add_text("For more control over a modal|popup window use a normal window with the modal|popup keyword and set the item handler and mouse events manually.", bullet=True) - dpg.add_text("By default a popup will shrink fit the items it contains.This is useful for context windows, and simple modal window popups.", bullet=True) - dpg.add_text("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it.", bullet=True) - with dpg.group(horizontal=True): - b = dpg.add_button(label="Right Click...") - t = dpg.add_text("") - with dpg.popup(b, tag="__demo_popup1"): - dpg.add_text("Aquariam") - dpg.add_separator() - for i in popup_values: - dpg.add_selectable(label=i, user_data=[t, i], callback=lambda s, a, u: dpg.set_value(u[0], u[1])) - dpg.add_text("A Popup with minimum size that cannot be moved", bullet=True) - with dpg.group(horizontal=True): - b = dpg.add_button(label="Right Click...") - t = dpg.add_text("") - with dpg.popup(b, tag="__demo_popup2", no_move=True, min_size=[300,400]): - dpg.add_text("Aquariam") - dpg.add_separator() - for i in popup_values: - dpg.add_selectable(label=i, user_data=[t, i], callback=lambda s, a, u: dpg.set_value(u[0], u[1])) - - with dpg.tree_node(label="Modals"): - dpg.add_text("Modal windows are like popups but the user cannot close them by clicking outside.") - dpg.add_text("This popup uses left click") - dpg.add_button(label="Left Click...") - with dpg.popup(dpg.last_item(), modal=True, mousebutton=dpg.mvMouseButton_Left, tag="__demo_popup3"): - dpg.add_text("All those beautiful files will be deleted.\nThis operation cannot be undone!") - dpg.add_separator() - dpg.add_checkbox(label="Don't ask me next time") - with dpg.group(horizontal=True): - dpg.add_button(label="OK", width=75, callback=lambda: dpg.configure_item("__demo_popup3", show=False)) - dpg.add_button(label="Cancel", width=75, callback=lambda: dpg.configure_item("__demo_popup3", show=False)) - - with dpg.tree_node(label="File/Directory Selector"): - - with dpg.file_dialog(label="Demo File Dialog", width=300, height=400, show=False, callback=lambda s, a, u : print(s, a, u), tag="__demo_filedialog"): - dpg.add_file_extension(".*", color=(255, 255, 255, 255)) - dpg.add_file_extension("Source files (*.cpp *.h *.hpp){.cpp,.h,.hpp}", color=(0, 255, 255, 255)) - dpg.add_file_extension(".cpp", color=(255, 255, 0, 255)) - dpg.add_file_extension(".h", color=(255, 0, 255, 255), custom_text="header") - dpg.add_file_extension("Python(.py){.py}", color=(0, 255, 0, 255)) - #dpg.add_button(label="Button on file dialog") - - dpg.add_button(label="Show File Selector", user_data=dpg.last_container(), callback=lambda s, a, u: dpg.configure_item(u, show=True)) - - with dpg.collapsing_header(label="Tooltips"): - - dpg.add_text("Hover me for a fancy tooltip") - with dpg.tooltip(dpg.last_item()): - dpg.add_simple_plot(label="", default_value=(0.3, 0.9, 2.5, 8.9), height = 80) - - with dpg.collapsing_header(label="Tables"): - - with dpg.tree_node(label="Basic"): - - # basic usage of the table api - with dpg.table(header_row=False): - - # use add_table_column to add columns to the table, - # table columns use slot 0 - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - # add_table_next_column will jump to the next row - # once it reaches the end of the columns - # table next column use slot 1 - for i in range(4): - - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Row{i} Column{j}") - - with dpg.tree_node(label="Borders, background") as section: - - with dpg.table(header_row=False, row_background=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True) as table_id: - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Row{i} Column{j}") - - _add_config_options(table_id, 2, - "row_background", "borders_innerH", "borders_innerV", - "borders_outerH", "borders_outerV", "header_row", before=table_id) - - with dpg.tree_node(label="Colors"): - - dpg.add_text("Highlighting Rows, Columns, Cells:") - with dpg.table(header_row=False, row_background=True) as table_id: - - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - for i in range(6): - with dpg.table_row(): - for j in range(6): - dpg.add_text(f"R{i} C{j}") - - for i in range(6): - dpg.highlight_table_row(table_id, i, [255, 0, 0, 100]) - - dpg.highlight_table_column(table_id, 4, [0, 255, 0, 100]) - - dpg.highlight_table_cell(table_id, 1, 1, [0, 0, 255, 100]) - dpg.highlight_table_cell(table_id, 2, 1, [0, 0, 255, 100]) - dpg.highlight_table_cell(table_id, 1, 2, [0, 0, 255, 100]) - dpg.highlight_table_cell(table_id, 2, 2, [0, 0, 255, 100]) - - _add_config_options(table_id, 1, "row_background", before=table_id) - - dpg.add_text("Coloring rows:") - with dpg.table(header_row=False, row_background=True) as table_id: - - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - for i in range(6): - with dpg.table_row(): - for j in range(6): - dpg.add_text(f"R{i} C{j}") - - dpg.highlight_table_cell(table_id, 1, 1, [0, 255, 0, 100]) - dpg.highlight_table_cell(table_id, 2, 1, [0, 255, 0, 100]) - dpg.highlight_table_cell(table_id, 1, 2, [0, 255, 0, 100]) - dpg.highlight_table_cell(table_id, 2, 2, [0, 255, 0, 100]) - - for i in range(6): - dpg.set_table_row_color(table_id, i, [255, 0, 0, i*255/8]) - - with dpg.tree_node(label="Resizable, stretch"): - - with dpg.table(header_row=False, resizable=True, - borders_outerH=True, borders_innerV=True, borders_outerV=True) as table_id: - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Row{i} Column{j}") - - _add_config_options(table_id, 1, - "borders_innerV", "borders_outerV", "resizable", before=table_id) - - with dpg.tree_node(label="Resizable, fixed"): - - dpg.add_text("Only available if scrollX/scrollY are disabled and stretch columns are not used") - with dpg.table(header_row=False, policy=dpg.mvTable_SizingFixedFit, resizable=True, no_host_extendX=False, - borders_innerV=True, borders_outerV=True,borders_outerH=True) as table_id: - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Row{i} Column{j}") - - _add_config_options(table_id, 1, "no_host_extendX", before=table_id) - - with dpg.tree_node(label="Resizable, mixed"): - - with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True, - resizable=True, no_host_extendX=False, hideable=True, - borders_innerV=True, borders_outerV=True, borders_innerH=True, borders_outerH=True): - - dpg.add_table_column(label="AAA", width_fixed=True) - dpg.add_table_column(label="BBB", width_fixed=True) - dpg.add_table_column(label="CCC", width_stretch=True, init_width_or_weight=0.0) - - for i in range(5): - with dpg.table_row(): - for j in range(3): - if j == 2: - dpg.add_text(f"Stretch {i}, {j}") - else: - dpg.add_text(f"Fixed {i}, {j}") - - with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True, - resizable=True, no_host_extendX=False, hideable=True, - borders_innerV=True, borders_outerV=True, borders_innerH=True, borders_outerH=True): - - dpg.add_table_column(label="AAA", width_fixed=True) - dpg.add_table_column(label="BBB", width_fixed=True) - dpg.add_table_column(label="CCC", width_stretch=True, init_width_or_weight=0.0) - dpg.add_table_column(label="DDD", width_stretch=True, init_width_or_weight=0.0) - - for i in range(5): - with dpg.table_row(): - for j in range(4): - if j == 2 or j == 3: - dpg.add_text(f"Stretch {i},{j}") - else: - dpg.add_text(f"Fixed {i}, {j}") - - with dpg.tree_node(label="Columns Options"): - - with dpg.table(header_row=True, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, row_background=True, hideable=True, reorderable=True, - resizable=True, sortable=True, policy=dpg.mvTable_SizingFixedFit, - scrollX=True, scrollY=True): - - c1 = dpg.add_table_column(label="One", default_sort=True) - c2 = dpg.add_table_column(label="Two") - c3 = dpg.add_table_column(label="Three", default_hide=True) - - for i in range(8): - with dpg.table_row(): - dpg.add_text("Indented One", indent=5*i) - dpg.add_text("Hello Two") - dpg.add_text("Hello Three") - - # options table - with dpg.table(header_row=False, show=True): - - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - options = ( - "default_hide", - "default_sort", - "width_stretch", - "width_fixed", - "no_resize", - "no_reorder", - "no_hide", - "no_clip", - "no_sort", - "no_sort_ascending", - "no_sort_descending", - "no_header_width", - "prefer_sort_ascending", - "prefer_sort_descending") - - with dpg.table_row(): - with dpg.table_cell(): - dpg.add_text("One") - _add_config_options(c1, 1, *options) - with dpg.table_cell(): - dpg.add_text("Two") - _add_config_options(c2, 1, *options) - with dpg.table_cell(): - dpg.add_text("Three") - _add_config_options(c3, 1, *options) - - with dpg.tree_node(label="Columns widths"): - - with dpg.table(header_row=True, resizable=True, - borders_outerH=True, borders_innerH=True, - borders_outerV=True): - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two") - dpg.add_table_column(label="Three") - - with dpg.table_row(): - for i in range(3): - _text_id = dpg.add_text("(w: 0.0f)") - with dpg.item_handler_registry(tag="__demo_item_reg4_"+str(i)): - dpg.add_item_visible_handler(user_data = _text_id, callback=lambda s, a, u:dpg.set_value(u, "(w: " + str(dpg.get_item_state(u)["content_region_avail"][0]) + ")")) - dpg.bind_item_handler_registry(_text_id, dpg.last_container()) - - for i in range(3): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Hello {i}, {j}") - - with dpg.table(header_row=False) as table_id: - - dpg.add_table_column(width_fixed=True, init_width_or_weight=100) - dpg.add_table_column(width_fixed=True, init_width_or_weight=200) - dpg.add_table_column(width_fixed=True, init_width_or_weight=300) - dpg.add_table_column(width_fixed=True, init_width_or_weight=400) - - with dpg.table_row(): - for i in range(4): - _text_id = dpg.add_text("(w: 0.0f)") - with dpg.item_handler_registry(tag="__demo_item_reg5_"+str(i)): - dpg.add_item_visible_handler(user_data = _text_id, callback=lambda s, a, u:dpg.set_value(u, "(w: " + str(dpg.get_item_state(u)["content_region_avail"][0]) + ")")) - dpg.bind_item_handler_registry(_text_id, dpg.last_container()) - - for i in range(4): - with dpg.table_row(): - for j in range(4): - dpg.add_text(f"Hello {i}, {j}") - - _add_config_options(table_id, 1, - "no_keep_columns_visible", "borders_innerV", "borders_outerV", before=table_id) - - with dpg.tree_node(label="Row height"): - - with dpg.table(header_row=False, borders_outerH=True, borders_outerV=True): - - dpg.add_table_column() - - for i in range(10): - with dpg.table_row(height=i*5 + 25): - dpg.add_text("height = " + str(i*5 + 25)) - - with dpg.tree_node(label="Padding"): - - with dpg.table(header_row=False, resizable=True, - hideable=True, reorderable=True, borders_outerV=True, borders_innerH=True) as table_id: - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two") - dpg.add_table_column(label="three") - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_button(label=f"Hello {i}, {j}", width=-1) - - _add_config_options(table_id, 3, - "pad_outerX", "no_pad_outerX", "no_pad_innerX", - "borders_outerV", "borders_innerV", "header_row", before=table_id) - - with dpg.tree_node(label="Angled headers"): - - with dpg.table(header_row=True, resizable=True, - reorderable=True) as table_id: - - dpg.add_table_column(label="One", angled_header=True) - dpg.add_table_column(label="Two", angled_header=True) - dpg.add_table_column(label="three", angled_header=True) - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Hello {i}, {j}") - - with dpg.tree_node(label="Reorderable, hideable, with headers"): - - with dpg.table(header_row=True, resizable=True, - hideable=True, reorderable=True) as table_id: - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two") - dpg.add_table_column(label="three") - - for i in range(5): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Hello {i}, {j}") - - _add_config_options(table_id, 3, - "hideable", "reorderable", "resizable", before=table_id) - - with dpg.tree_node(label="Outer Size"): - - with dpg.table(header_row=False, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=150) as table_id: - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two") - dpg.add_table_column(label="three") - - for i in range(10): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Cell {i}, {j}") - - _add_config_options(table_id, 3, - "no_host_extendX", "no_host_extendY", "resizable", before=table_id) - - dpg.add_text("Using explicit size:") - with dpg.table(header_row=False, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=300, width=300): - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two") - dpg.add_table_column(label="three") - - for i in range(6): - with dpg.table_row(): - for j in range(3): - dpg.add_text(f"Cell {i}, {j}") - - with dpg.tree_node(label="Scrolling, Clipping"): - - # without clipping - dpg.add_text("Without Clipper") - with dpg.table(header_row=True, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=300, - scrollY=True): - - dpg.add_table_column(label="1") - dpg.add_table_column(label="2") - dpg.add_table_column(label="3") - - for i in range(25): - with dpg.table_row(): - dpg.add_input_int(label=" ", step=0) - dpg.add_button(label=f"Cell {i}, 1") - dpg.add_text(f"Cell {i}, 2") - - # with clipping - dpg.add_text("Using Clipper") - with dpg.table(header_row=True, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=300, - scrollY=True, clipper=True) as table_id: - - dpg.add_table_column(label="1") - dpg.add_table_column(label="2") - dpg.add_table_column(label="3") - - for i in range(25): - with dpg.table_row(): - dpg.add_input_int(label=" ", step=0) - dpg.add_button(label=f"Cell {i}, 1") - dpg.add_text(f"Cell {i}, 2") - - dpg.add_checkbox(label="resizable", before=table_id, default_value=True, user_data=table_id, callback=lambda sender, app_data, user_data:dpg.configure_item(user_data, resizable=app_data)) - - # Freezing rows/columns - dpg.add_text("Freezing rows/columns") - with dpg.table(header_row=True, borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, row_background=True, height=300, freeze_rows=1, freeze_columns=1, - scrollY=True, scrollX=True, policy=dpg.mvTable_SizingFixedFit): - - dpg.add_table_column(label="1", width=50) - dpg.add_table_column(label="2", width=50) - dpg.add_table_column(label="3", width=50) - dpg.add_table_column(label="4", width=50) - dpg.add_table_column(label="5", width=50) - dpg.add_table_column(label="6", width=50) - dpg.add_table_column(label="7", width=50) - - for i in range(25): - with dpg.table_row(): - dpg.add_text(f"Cell {i}, 0") - dpg.add_button(label=f"Cell {i}, 1") - dpg.add_text(f"Cell {i}, 2") - dpg.add_text(f"Cell {i}, 3") - dpg.add_text(f"Cell {i}, 4") - dpg.add_text(f"Cell {i}, 5") - dpg.add_text(f"Cell {i}, 6") - - with dpg.tree_node(label="Filtering"): - - # with filtering - dpg.add_text("Using Filter (column 3)") - _filter_table_id = dpg.generate_uuid() - dpg.add_input_text(label="Filter (inc, -exc)", user_data=_filter_table_id, callback=lambda s, a, u: dpg.set_value(u, dpg.get_value(s))) - with dpg.table(header_row=True, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=300, - scrollY=True, tag=_filter_table_id) as table_id: - - dpg.add_table_column(label="1") - dpg.add_table_column(label="2") - dpg.add_table_column(label="3") - - for i in range(25): - with dpg.table_row(filter_key=f"Cell {i}, 1"): - dpg.add_input_int(label=" ", step=0) - dpg.add_button(label=f"Cell {i}, 1") - dpg.add_text(f"Cell {i}, 2") - - dpg.add_checkbox(label="resizable", before=table_id, default_value=True, user_data=table_id, callback=lambda sender, app_data, user_data:dpg.configure_item(user_data, resizable=app_data)) - - with dpg.tree_node(label="Sorting"): - - def _sort_callback(sender, sort_specs): - - # sort_specs scenarios: - # 1. no sorting -> sort_specs == None - # 2. single sorting -> sort_specs == [[column_id, direction]] - # 3. multi sorting -> sort_specs == [[column_id, direction], [column_id, direction], ...] - # - # notes: - # 1. direction is ascending if == 1 - # 2. direction is ascending if == -1 - - # no sorting case - if sort_specs is None: return - - rows = dpg.get_item_children(sender, 1) - - # create a list that can be sorted based on first cell - # value, keeping track of row and value used to sort - sortable_list = [] - for row in rows: - first_cell = dpg.get_item_children(row, 1)[0] - sortable_list.append([row, dpg.get_value(first_cell)]) - - def _sorter(e): - return e[1] - - sortable_list.sort(key=_sorter, reverse=sort_specs[0][1] < 0) - - # create list of just sorted row ids - new_order = [] - for pair in sortable_list: - new_order.append(pair[0]) - - dpg.reorder_items(sender, 1, new_order) - - with dpg.table(header_row=True, no_host_extendX=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, context_menu_in_body=True, row_background=True, - policy=dpg.mvTable_SizingFixedFit, height=500, sortable=True, callback=_sort_callback, - scrollY=True, tag="__demo_sorting_table"): - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two", no_sort=True) - dpg.add_table_column(label="Three", no_sort=True) - - for i in range(25): - with dpg.table_row(): - dpg.add_input_int(label=" ", step=0, default_value=i) - dpg.add_text(f"Cell {i}, 1") - dpg.add_checkbox(label=f"Cell {i}, 2") - - - #dpg.add_checkbox(label="sort_multi", before=table_id, user_data=table_id, callback=lambda sender, app_data, user_data:dpg.configure_item(user_data, sort_multi=app_data)) - dpg.add_checkbox(label="sort_tristate", before="__demo_sorting_table", callback=lambda sender, app_data, user_data:dpg.configure_item("__demo_sorting_table", sort_tristate=app_data)) - - with dpg.tree_node(label="Selecting rows"): - with dpg.theme() as table_theme: - with dpg.theme_component(dpg.mvTable): - dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - dpg.add_theme_color(dpg.mvThemeCol_Header, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - - def clb_selectable(sender, app_data, user_data): - print(f"Row {user_data}") - - with dpg.table(header_row=True) as table_sel_rows: - dpg.add_table_column(label="First") - dpg.add_table_column(label="Second") - dpg.add_table_column(label="Third") - - for i in range(10): - with dpg.table_row(): - for j in range(3): - dpg.add_selectable(label=f"Row{i} Column{j}", span_columns=True, callback=clb_selectable, user_data=i) - dpg.bind_item_theme(table_sel_rows, table_theme) - - with dpg.tree_node(label="Selecting cells"): - with dpg.theme() as table_theme: - with dpg.theme_component(dpg.mvTable): - dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - dpg.add_theme_color(dpg.mvThemeCol_Header, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - - def clb_selectable(sender, app_data, user_data): - print(f"Row {user_data}") - - with dpg.table(header_row=True) as table_sel_cols: - dpg.add_table_column(label="First") - dpg.add_table_column(label="Second") - dpg.add_table_column(label="Third") - - for i in range(10): - with dpg.table_row(): - for j in range(3): - dpg.add_selectable(label=f"Row{i} Column{j}", callback=clb_selectable, user_data=(i,j)) - dpg.bind_item_theme(table_sel_cols, table_theme) - - with dpg.tree_node(label="Sizing Policy"): - - def callback(sender, value, user_data): - - if user_data[8] == "resizable": - for i in range(8): - dpg.configure_item(user_data[i], resizable=value) - - elif user_data[8] == "no_host_extendX": - for i in range(8): - dpg.configure_item(user_data[i], no_host_extendX=value) - - elif user_data[8] == "policy": - - if value == "mvTable_SizingFixedFit": - dpg.configure_item(user_data[user_data[9]], policy=dpg.mvTable_SizingFixedFit) - dpg.configure_item(user_data[user_data[9]+1], policy=dpg.mvTable_SizingFixedFit) - elif value == "mvTable_SizingFixedSame": - dpg.configure_item(user_data[user_data[9]], policy=dpg.mvTable_SizingFixedSame) - dpg.configure_item(user_data[user_data[9]+1], policy=dpg.mvTable_SizingFixedSame) - elif value == "mvTable_SizingStretchProp": - dpg.configure_item(user_data[user_data[9]], policy=dpg.mvTable_SizingStretchProp) - dpg.configure_item(user_data[user_data[9]+1], policy=dpg.mvTable_SizingStretchProp) - elif value == "mvTable_SizingStretchSame": - dpg.configure_item(user_data[user_data[9]], policy=dpg.mvTable_SizingStretchSame) - dpg.configure_item(user_data[user_data[9]+1], policy=dpg.mvTable_SizingStretchSame) - - def create_table_set(policy): - - with dpg.table(header_row=False, policy=policy, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True, row_background=True) as table_id1: - - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - for i in range(8): - with dpg.table_row(): - dpg.add_text("Oh dear") - dpg.add_text("Oh dear") - dpg.add_text("Oh dear") - - with dpg.table(header_row=False, policy=policy, - borders_innerH=True, borders_outerH=True, borders_innerV=False, - borders_outerV=True, row_background=True) as table_id2: - - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - for i in range(3): - with dpg.table_row(): - dpg.add_text("AAAA") - dpg.add_text("BBBBBBBB") - dpg.add_text("CCCCCCCCCCCC") - - return table_id1, table_id2 - - table_id1, table_id12 = create_table_set(dpg.mvTable_SizingFixedFit) - table_id2, table_id22 = create_table_set(dpg.mvTable_SizingFixedSame) - table_id3, table_id32 = create_table_set(dpg.mvTable_SizingStretchProp) - table_id4, table_id42 = create_table_set(dpg.mvTable_SizingStretchSame) - - user_data = [table_id1, table_id12, table_id2, table_id22, table_id3, table_id32, table_id4, table_id42] - - sizing_options = ("mvTable_SizingFixedFit", "mvTable_SizingFixedSame", "mvTable_SizingStretchProp", "mvTable_SizingStretchSame") - - combo1 = dpg.add_combo(sizing_options, label="Sizing Policy", default_value=sizing_options[0], before=table_id1, user_data=user_data + ["policy", 0], callback=callback) - dpg.add_combo(sizing_options, label="Sizing Policy", default_value=sizing_options[1], before=table_id2, user_data=user_data + ["policy", 2], callback=callback) - dpg.add_combo(sizing_options, label="Sizing Policy", default_value=sizing_options[2], before=table_id3, user_data=user_data + ["policy", 4], callback=callback) - dpg.add_combo(sizing_options, label="Sizing Policy", default_value=sizing_options[3], before=table_id4, user_data=user_data + ["policy", 6], callback=callback) - dpg.add_checkbox(label="resizable", before=combo1, user_data=user_data + ["resizable"], callback=callback) - dpg.add_checkbox(label="no_host_extendX", before=combo1, user_data=user_data + ["no_host_extendX"], callback=callback) - - with dpg.collapsing_header(label="Plots"): - - sindatax = [] - sindatay = [] - cosdatay = [] - for i in range(100): - sindatax.append(i/100) - sindatay.append(0.5 + 0.5*sin(50*i/100)) - cosdatay.append(0.5 + 0.75*cos(50*i/100)) - - with dpg.tab_bar(): - - with dpg.tab(label="Series"): - - with dpg.tree_node(label="Line Series"): - # create plot - with dpg.plot(label="Line Series", height=400, width=-1): - - # optionally create legend - dpg.add_plot_legend() - - # REQUIRED: create x and y axes - dpg.add_plot_axis(dpg.mvXAxis, label="x") - - with dpg.plot_axis(dpg.mvYAxis, label="y"): - - # series belong to a y axis - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)") - - with dpg.tree_node(label="Filled Line Series"): - dpg.add_checkbox(label="fill", tag="fill_series_cb", default_value=False, - callback=lambda: dpg.configure_item("filled_line_series", shaded=dpg.get_value("fill_series_cb"))) - dpg.add_checkbox(label="segment", tag="segment_series_cb", default_value=False, - callback=lambda: dpg.configure_item("filled_line_series", segments=dpg.get_value("segment_series_cb"))) - with dpg.plot(label="Filled Line Plot", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_line_series(sindatax, sindatay, tag="filled_line_series", label="0.5 + 0.5 * sin(x)") - - with dpg.tree_node(label="Text point"): - # create plot - with dpg.plot(label="Text point", height=400, width=-1): - - # optionally create legend - dpg.add_plot_legend() - - # REQUIRED: create x and y axes - dpg.add_plot_axis(dpg.mvXAxis, label="x") - - with dpg.plot_axis(dpg.mvYAxis, label="y"): - - # series belong to a y axis - dpg.add_text_point(2., 1.5, label="Text point label") - - with dpg.tree_node(label="Shade Series"): - std_alpha = 0.25 - - def _cb_alpha(_, app_data): - with dpg.theme() as alpha_theme: - with dpg.theme_component(0): - dpg.add_theme_style(dpg.mvPlotStyleVar_FillAlpha, app_data, category=dpg.mvThemeCat_Plots) - dpg.bind_item_theme("shaded_plot_1", alpha_theme) - - dpg.add_drag_float(min_value=0, max_value=1, callback=_cb_alpha, speed=0.01, default_value=std_alpha) - with dpg.theme() as alpha_theme: - with dpg.theme_component(0): - dpg.add_theme_style(dpg.mvPlotStyleVar_FillAlpha, std_alpha, category=dpg.mvThemeCat_Plots) - with dpg.plot(label="Shaded Plot", tag="shaded_plot_1", height=400, width=-1): - xs = [] - ys = [] - ys1 = [] - ys2 = [] - ys3 = [] - ys4 = [] - random.seed(0) - for i in range(1001): - xs.append(i * 0.001) - ys.append(0.25 + 0.25 * sin(25 * xs[i]) * sin(5 * xs[i]) + random.uniform(-0.01, 0.01)) - ys1.append(ys[i] + random.uniform(0.1, 0.12)) - ys2.append(ys[i] - random.uniform(0.1, 0.12)) - ys3.append(0.75 + 0.2 * sin(25 * xs[i])) - ys4.append(0.75 + 0.1 * cos(25 * xs[i])) - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_shade_series(xs, ys1, y2=ys2, label="Uncertain data") - dpg.add_line_series(xs, ys, label="Uncertain data") - dpg.add_shade_series(xs, ys3, y2=ys4, label="Overlapping") - dpg.add_line_series(xs, ys3, label="Overlapping") - dpg.add_line_series(xs, ys4, label="Overlapping") - dpg.bind_item_theme("shaded_plot_1", alpha_theme) - - stock_datax = [] - stock_datay2 = [] - stock_data1 = [] - stock_data2 = [] - stock_data3 = [] - stock_data4 = [] - stock_data5 = [] - for i in range(100): - stock_datax.append(i) - stock_datay2.append(0) - stock_data1.append(400 + 50*abs(random.random())) - stock_data2.append(275 + 75*abs(random.random())) - stock_data3.append(150 + 75*abs(random.random())) - stock_data4.append(500 + 75*abs(random.random())) - stock_data5.append(600 + 75*abs(random.random())) - - with dpg.theme(tag="stock_theme1"): - with dpg.theme_component(0): - dpg.add_theme_color(dpg.mvPlotCol_Line, (0, 0, 255), category=dpg.mvThemeCat_Plots) - dpg.add_theme_color(dpg.mvPlotCol_Fill, (0, 0, 255, 64), category=dpg.mvThemeCat_Plots) - - with dpg.theme(tag="stock_theme2"): - with dpg.theme_component(0): - dpg.add_theme_color(dpg.mvPlotCol_Line, (255, 0, 0), category=dpg.mvThemeCat_Plots) - dpg.add_theme_color(dpg.mvPlotCol_Fill, (255, 0, 0, 64), category=dpg.mvThemeCat_Plots) - - with dpg.theme(tag="stock_theme3"): - with dpg.theme_component(0): - dpg.add_theme_color(dpg.mvPlotCol_Line, (0, 255, 0), category=dpg.mvThemeCat_Plots) - dpg.add_theme_color(dpg.mvPlotCol_Fill, (0, 255, 0, 64), category=dpg.mvThemeCat_Plots) - - with dpg.theme(tag="stock_theme4"): - with dpg.theme_component(0): - dpg.add_theme_color(dpg.mvPlotCol_Fill, (255, 255, 100, 64), category=dpg.mvThemeCat_Plots) - - with dpg.plot(label="Stock Prices", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="Days") - with dpg.plot_axis(dpg.mvYAxis, label="Price"): - dpg.add_line_series(stock_datax, stock_data1, label="Stock 1") - dpg.bind_item_theme(dpg.last_item(), "stock_theme1") - dpg.add_line_series(stock_datax, stock_data2, label="Stock 2") - dpg.bind_item_theme(dpg.last_item(), "stock_theme2") - dpg.add_line_series(stock_datax, stock_data3, label="Stock 3") - dpg.bind_item_theme(dpg.last_item(), "stock_theme3") - dpg.add_shade_series(stock_datax, stock_data1, label="Stock 1") - dpg.bind_item_theme(dpg.last_item(), "stock_theme1") - dpg.add_shade_series(stock_datax, stock_data2, label="Stock 2") - dpg.bind_item_theme(dpg.last_item(), "stock_theme2") - dpg.add_shade_series(stock_datax, stock_data3, label="Stock 3", y2=stock_datay2) - dpg.bind_item_theme(dpg.last_item(), "stock_theme3") - dpg.add_shade_series(stock_datax, stock_data5, y2=stock_data4, label="Shade between lines") - dpg.bind_item_theme(dpg.last_item(), "stock_theme4") - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - with dpg.tree_node(label="Scatter Series"): - - with dpg.plot(label="Scatter Series", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_scatter_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)") - - with dpg.tree_node(label="Stair Series"): - dpg.add_checkbox(label="pre-step", tag="pre_step_cb", default_value=False, - callback=lambda: dpg.configure_item("stair_series", pre_step=dpg.get_value("pre_step_cb"))) - dpg.add_checkbox(label="filled", tag="filled_stairs_cb", default_value=False, - callback=lambda: dpg.configure_item("stair_series", shaded=dpg.get_value("filled_stairs_cb"))) - with dpg.plot(label="Stair Plot", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_stair_series(sindatax, sindatay, tag="stair_series", label="0.5 + 0.5 * sin(x)") - - with dpg.tree_node(label="Bar Series"): - dpg.add_checkbox(label="horizontal", tag="horizontal_bar_cb", default_value=False, - callback=lambda: dpg.configure_item("bar_series", horizontal=dpg.get_value("horizontal_bar_cb"))) - with dpg.plot(label="Bar Series", height=400, width=-1): - - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="Student", no_gridlines=True) - dpg.set_axis_limits(dpg.last_item(), 9, 33) - dpg.set_axis_ticks(dpg.last_item(), (("S1", 11), ("S2", 21), ("S3", 31))) - dpg.add_plot_axis(dpg.mvXAxis2, label="hor_value", no_gridlines=True) - dpg.set_axis_limits(dpg.last_item(), 0, 110) - - - # create y axis - with dpg.plot_axis(dpg.mvYAxis, label="Score"): - dpg.set_axis_limits(dpg.last_item(), 0, 110) - dpg.add_bar_series([10, 20, 30], [100, 75, 90], tag="bar_series", label="Final Exam", weight=1) - dpg.add_bar_series([11, 21, 31], [83, 75, 72], label="Midterm Exam", weight=1) - dpg.add_bar_series([12, 22, 32], [42, 68, 23], label="Course Grade", weight=1) - - - with dpg.tree_node(label="Bar Group Series"): - limits_group_series = [-0.5, 9.5] - - def set_horizontal(sender, app_data, user_data): - dpg.configure_item("bar_group_series", horizontal=app_data) - if app_data: - dpg.set_axis_limits("yaxis_bar_group", *limits_group_series) - dpg.set_axis_ticks("yaxis_bar_group", glabels) - dpg.reset_axis_ticks("xaxis_bar_group") - dpg.set_axis_limits_auto("xaxis_bar_group") - else: - dpg.set_axis_limits("xaxis_bar_group", *limits_group_series) - dpg.set_axis_ticks("xaxis_bar_group", glabels) - dpg.reset_axis_ticks("yaxis_bar_group") - dpg.set_axis_limits_auto("yaxis_bar_group") - - def _callback_stacked(sender, app_data, user_data): - dpg.configure_item("bar_group_series", stacked=app_data) - is_horizontal = dpg.get_item_configuration("bar_group_series")["horizontal"] - if is_horizontal: - dpg.set_axis_limits_auto("xaxis_bar_group") - else: - dpg.set_axis_limits_auto("yaxis_bar_group") - - dpg.add_checkbox(label="Horizontal", default_value=False, callback=set_horizontal) - dpg.add_checkbox(label="Stacked", default_value=False, callback=_callback_stacked) - dpg.add_slider_float(label="Bar Width", default_value=0.67, max_value=1.0, - min_value=0.1, callback=lambda _, val: dpg.configure_item("bar_group_series", group_width=val)) - with dpg.plot(label="Bar Group Series", height=400, width=-1): - dpg.add_plot_legend() - - values_group_series = [83, 67, 23, 89, 83, 78, 91, 82, 85, 90, - 80, 62, 56, 99, 55, 78, 88, 78, 90, 100, - 80, 69, 52, 92, 72, 78, 75, 76, 89, 95] - - ilabels = ["Midterm Exam","Final Exam","Course Grade"] - glabels = (("S1",0), ("S2",1), ("S3",2), ("S4",3), ("S5",4), ("S6",5), ("S7",6), ("S8",7), ("S9",8), ("S10",9)) - groups_c = 3 - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="Student", tag="xaxis_bar_group", no_gridlines=True, auto_fit=True) - dpg.set_axis_limits(dpg.last_item(), *limits_group_series) - dpg.set_axis_ticks(dpg.last_item(), glabels) - - # create y axis - with dpg.plot_axis(dpg.mvYAxis, label="Score", tag="yaxis_bar_group", auto_fit=True): - dpg.set_axis_limits(dpg.last_item(), 0, 110) - dpg.add_bar_group_series(values=values_group_series, label_ids=ilabels, - group_size=groups_c, tag="bar_group_series", label="Final Exam") - - with dpg.tree_node(label="Bar Stacks"): - politicians = (("Trump", 0), ("Bachman", 1), ("Cruz", 2), ("Gingrich", 3), ("Palin", 4), ("Santorum", 5), - ("Walker", 6), ("Perry", 7), ("Ryan", 8), ("McCain", 9), ("Rubio", 10), ("Romney", 11), ("Rand Paul", 12), ("Christie", 13), - ("Biden", 14), ("Kasich", 15), ("Sanders", 16), ("J Bush", 17), ("H Clinton", 18), ("Obama", 19)) - data_reg = [18,26,7,14,10,8,6,11,4,4,3,8,6,8,6,5,0,3,1,2, # Pants on Fire - 43,36,30,21,30,27,25,17,11,22,15,16,16,17,12,12,14,6,13,12, # False - 16,13,28,22,15,21,15,18,30,17,24,18,13,10,14,15,17,22,14,12, # Mostly False - 17,10,13,25,12,22,19,26,23,17,22,27,20,26,29,17,18,22,21,27, # Half True - 5,7,16,10,10,12,23,13,17,20,22,16,23,19,20,26,36,29,27,26, # Mostly True - 1,8,6,8,23,10,12,15,15,20,14,15,22,20,19,25,15,18,24,21] # True - labels_reg = ["Pants on Fire","False","Mostly False","Half True","Mostly True","True"] - - - data_div = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # Pants on Fire (dummy, to order legend logically) - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # False (dummy, to order legend logically) - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # Mostly False (dummy, to order legend logically) - -16,-13,-28,-22,-15,-21,-15,-18,-30,-17,-24,-18,-13,-10,-14,-15,-17,-22,-14,-12, # Mostly False - -43,-36,-30,-21,-30,-27,-25,-17,-11,-22,-15,-16,-16,-17,-12,-12,-14,-6,-13,-12, # False - -18,-26,-7,-14,-10,-8,-6,-11,-4,-4,-3,-8,-6,-8,-6,-5,0,-3,-1,-2, # Pants on Fire - 17,10,13,25,12,22,19,26,23,17,22,27,20,26,29,17,18,22,21,27, # Half True - 5,7,16,10,10,12,23,13,17,20,22,16,23,19,20,26,36,29,27,26, # Mostly True - 1,8,6,8,23,10,12,15,15,20,14,15,22,20,19,25,15,18,24,21] # True - labels_div = ["Pants on Fire","False","Mostly False","Mostly False", - "False","Pants on Fire","Half True","Mostly True","True"] - - def divergent_stack_cb(sender, app_data, user_data): - if app_data: - dpg.configure_item("divergent_stack_series", values=data_div, label_ids=labels_div, group_size=len(labels_div), group_width=0.75, shift=0, stacked=True, horizontal=True) - else: - dpg.configure_item("divergent_stack_series", values=data_reg, label_ids=labels_reg, group_size=len(labels_reg), group_width=0.75, shift=0, stacked=True, horizontal=True) - - dpg.add_checkbox(label="Divergent", tag="divergent_stack_cb", default_value=True, callback=divergent_stack_cb) - with dpg.plot(label="PolitiFact: Who Lies More?", height=400, width=-1): - dpg.add_plot_legend() - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, no_gridlines=True) - # create y axis - with dpg.plot_axis(dpg.mvYAxis) as yaxis: - dpg.set_axis_ticks(yaxis, politicians) - dpg.set_axis_limits(yaxis, -0.5, 19.5) - dpg.add_bar_group_series(tag="divergent_stack_series", values=data_div, label_ids=labels_div, - group_size=len(labels_div), group_width=0.75, shift=0, stacked=True, horizontal=True) - # dpg.add_bar_group_series(values=data_reg, label_ids=labels_reg, - # group_size=20, group_width=0.75, shift=0, stacked=True, horizontal=True) - - with dpg.tree_node(label="Error Series"): - - error1_x = [1, 2, 3, 4, 5] - error1_y = [1, 2, 5, 3, 4] - error1_neg = [0.2, 0.4, 0.2, 0.6, 0.4] - error1_pos = [0.4, 0.2, 0.4, 0.8, 0.6] - - error2_x = [1, 2, 3, 4, 5] - error2_y = [8, 8, 9, 7, 8] - error2_neg = [0.2, 0.4, 0.2, 0.6, 0.4] - error2_pos = [0.4, 0.2, 0.4, 0.8, 0.6] - - dpg.add_text("Anti-aliasing can be enabled from the plot's context menu (see Help).", bullet=True) - - with dpg.plot(label="Error Series", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - - dpg.add_bar_series(error1_x, error1_y, label="Bar", weight=0.25) - dpg.add_error_series(error1_x, error1_y, error1_neg, error1_pos, label="Bar") - dpg.add_line_series(error2_x, error2_y, label="Line") - dpg.add_error_series(error2_x, error2_y, error2_neg, error2_pos, label="Line") - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - with dpg.tree_node(label="Stem Series"): - - with dpg.theme(tag="stem_theme1"): - with dpg.theme_component(0): - dpg.add_theme_color(dpg.mvPlotCol_Line, (0, 255, 0), category=dpg.mvThemeCat_Plots) - dpg.add_theme_style(dpg.mvPlotStyleVar_Marker, dpg.mvPlotMarker_Diamond, category=dpg.mvThemeCat_Plots) - - with dpg.plot(label="Stem Series", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_stem_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)") - dpg.add_stem_series(sindatax, cosdatay, label="0.5 + 0.75 * cos(x)") - dpg.bind_item_theme(dpg.last_item(), "stem_theme1") - - with dpg.tree_node(label="Infinite Lines"): - - infinite_x_data = (3, 5, 6, 7) - infinite_y_data = (3, 5, 6, 7) - - with dpg.plot(label="Infinite Lines", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_inf_line_series(infinite_x_data, label="vertical") - dpg.add_inf_line_series(infinite_y_data, label="horizontal", horizontal=True) - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - - with dpg.tree_node(label="Pie Charts"): - - with dpg.group(horizontal=True): - - # create plot 1 - with dpg.plot(no_title=True, no_mouse_pos=True, width=250, height=250): - - # create legend - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="", no_gridlines=True, no_tick_marks=True, no_tick_labels=True) - dpg.set_axis_limits(dpg.last_item(), 0, 1) - - # create y axis - with dpg.plot_axis(dpg.mvYAxis, label="", no_gridlines=True, no_tick_marks=True, no_tick_labels=True): - dpg.set_axis_limits(dpg.last_item(), 0, 1) - dpg.add_pie_series(0.5, 0.5, 0.5, [0.25, 0.30, 0.30], ["fish", "cow", "chicken"]) - - # plot 2 - with dpg.plot(no_title=True, no_mouse_pos=True, width=250, height=250): - - # create legend - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="", no_gridlines=True, no_tick_marks=True, no_tick_labels=True) - dpg.set_axis_limits(dpg.last_item(), 0, 1) - - # create y axis - with dpg.plot_axis(dpg.mvYAxis, label="", no_gridlines=True, no_tick_marks=True, no_tick_labels=True): - dpg.set_axis_limits(dpg.last_item(), 0, 1) - dpg.add_pie_series(0.5, 0.5, 0.5, [1, 1, 2, 3, 5], ["A", "B", "C", "D", "E"], normalize=True, format="%.0f") - - - with dpg.tree_node(label="Heatmaps"): - - dpg.add_checkbox(label="major col", tag="major_col_heat_cb", default_value=False, - callback=lambda _, a: dpg.configure_item("heat_series", col_major=a)) - - - values = (0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0, - 2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0, - 1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0, - 0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0, - 0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0, - 1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1, - 0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3) - with dpg.group(horizontal=True): - dpg.add_colormap_scale(min_scale=0, max_scale=10, height=400) - with dpg.plot(label="Heat Series", no_mouse_pos=True, height=400, width=-1): - dpg.add_plot_axis(dpg.mvXAxis, label="x", lock_min=True, lock_max=True, no_gridlines=True, no_tick_marks=True) - with dpg.plot_axis(dpg.mvYAxis, label="y", no_gridlines=True, no_tick_marks=True, lock_min=True, lock_max=True): - dpg.add_heat_series(values, 7, 7, tag="heat_series",scale_min=0, scale_max=6.3) - - with dpg.tree_node(label="Histogram Series"): - - x_data = [] - for i in range(10000): - x = random.randrange(1, 11) - x_data.append(x) - - def update_density(user_data, app_data, other_data): - dpg.configure_item("histogram_series", density=app_data) - - dpg.add_checkbox(label="density", tag="density_histograms_cb", default_value=False, - callback=update_density) - dpg.add_checkbox(label="cumulative", tag="cumulative_histograms_cb", default_value=False, - callback=lambda: dpg.configure_item("histogram_series", cumulative=dpg.get_value("cumulative_histograms_cb"))) - - - with dpg.plot(label="Histogram Plot", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.set_axis_limits(xaxis, 1, 10) - dpg.set_axis_ticks(xaxis, (("S1", 1), ("S2", 2), ("S3", 3), ("S4", 4), ("S5", 5), ("S6", 6), ("S7", 7), ("S8", 8), ("S9", 9), ("S10", 10))) - with dpg.plot_axis(dpg.mvYAxis, label="y axis", tag="yaxis_histogram", auto_fit=True) as yaxis: - dpg.add_histogram_series(x_data, tag="histogram_series", label="histogram") - dpg.fit_axis_data(xaxis) - - with dpg.tree_node(label="Histogram 2D Series"): - def update_count(_, app_data): - global count_2d_histogram - count_2d_histogram = app_data - x_dist = [random.gauss(1, 2) for _ in range(count_2d_histogram)] - y_dist = [random.gauss(1, 1) for _ in range(count_2d_histogram)] - max_count = max(*x_dist, *y_dist) - - dpg.configure_item("histogram_2d_series", x=x_dist, y=y_dist) - dpg.configure_item("2d_hist_colormap_scale", max_scale=max_count) - - def update_bins(_, app_data): - global xybin_2d_histogram - xybin_2d_histogram = app_data - dpg.configure_item("histogram_2d_series", xbins=app_data[0], ybins=app_data[1]) - - def _update_density(_, app_data): - dpg.configure_item("histogram_2d_series", density=app_data) - # TODO: Find a way to access max_count 2d histogram - dpg.configure_item("2d_hist_colormap_scale", max_scale=1.0 if app_data else max_count, label="Density" if app_data else "Count") - - dpg.add_slider_int(label="Count", min_value=100, max_value=100000, callback=update_count, - default_value=count_2d_histogram, tag="count_histograms_2d", width=300) - with dpg.group(horizontal=True): - dpg.add_slider_intx(label="Bins", min_value=1, max_value=500, tag="bins", size=2, - callback=update_bins, width=300, default_value=xybin_2d_histogram) - dpg.add_checkbox(label="density", tag="density_histograms_2d_cb", default_value=False, - callback=_update_density) - - max_count = 0.0 - with dpg.group(horizontal=True, tag="histogram_2d_plot_group"): - with dpg.plot(label="Histogram 2D Plot", tag="2d_histogram_plot", height=400, width=650): - x_dist = [random.gauss(1, 2) for _ in range(count_2d_histogram)] - y_dist = [random.gauss(1, 1) for _ in range(count_2d_histogram)] - max_count = float(max(*x_dist, *y_dist)) - - x_axis = dpg.add_plot_axis(dpg.mvXAxis, label="x", auto_fit=True, foreground_grid=True) - dpg.set_axis_limits(dpg.last_item(), -6, 6) - with dpg.plot_axis(dpg.mvYAxis, label="y", auto_fit=True, foreground_grid=True): - dpg.set_axis_limits(dpg.last_item(), -6, 6) - dpg.add_2d_histogram_series(x_dist, y_dist, tag="histogram_2d_series", - label="histogram", xbins=xybin_2d_histogram[0], ybins=xybin_2d_histogram[1], - xmax_range=6, ymax_range=6, ymin_range=-6, - xmin_range=-6) - - dpg.add_colormap_scale(tag="2d_hist_colormap_scale", label="Count", colormap=dpg.mvPlotColormap_Hot, - min_scale=0.0, max_scale=max_count, height=400) - dpg.bind_colormap("2d_histogram_plot", dpg.mvPlotColormap_Hot) - - with dpg.tree_node(label="Digital Plots"): - dpg.add_text(default_value="Digital plots do not respond to Y drag and zoom, so that", - bullet=True) - dpg.add_text(default_value="you can drag analog plots over the rising/falling digital edge.", - indent=20) - paused = False - data_digital = [[], []] - data_analog = [[], []] - show_digital = [True, False] - show_analog = [True, False] - - def change_val(arr, ind, val): - arr[ind] = val - - with dpg.group(horizontal=True): - dpg.add_checkbox(label="digital_0", callback=lambda s, a: change_val(show_digital, 0, a), - default_value=True) - dpg.add_checkbox(label="digital_1", callback=lambda s, a: change_val(show_digital, 1, a), - default_value=False) - dpg.add_checkbox(label="analog_0", callback=lambda s, a: change_val(show_analog, 0, a), - default_value=True) - dpg.add_checkbox(label="analog_1", callback=lambda s, a: change_val(show_analog, 1, a), - default_value=False) - - with dpg.plot(tag="_demo_digital_plot", width=500): - # TODO: better handling of show/hide (more consistency between checkboxes and legend) - dpg.add_plot_axis(dpg.mvXAxis, label="x", tag="x_axis_digital") - dpg.set_axis_limits(dpg.last_item(), -10, 0) - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.set_axis_limits(dpg.last_item(), -2, 1.5) - dpg.add_digital_series([], [], label="digital_0", tag="digital_0") - dpg.add_digital_series([], [], label="digital_1", tag="digital_1") - dpg.add_line_series([], [], label="analog_0", tag="analog_0") - dpg.add_line_series([], [], label="analog_1", tag="analog_1") - - def _update_plot(): - global t_digital_plot - if not paused: - t_digital_plot += dpg.get_delta_time() - dpg.set_axis_limits('x_axis_digital', t_digital_plot - 10, t_digital_plot) - if show_digital[0]: - data_digital[0].append([t_digital_plot, 1 if sin(t_digital_plot) > 0.45 else 0]) - dpg.set_value("digital_0", [*zip(*data_digital[0])]) - if show_digital[1]: - data_digital[1].append([t_digital_plot, 1 if sin(t_digital_plot) < 0.45 else 0]) - dpg.set_value("digital_1", [*zip(*data_digital[1])]) - if show_analog[0]: - data_analog[0].append([t_digital_plot, sin(t_digital_plot)]) - dpg.set_value("analog_0", [*zip(*data_analog[0])]) - if show_analog[1]: - data_analog[1].append([t_digital_plot, cos(t_digital_plot)]) - dpg.set_value("analog_1", [*zip(*data_analog[1])]) - - with dpg.item_handler_registry(tag="__demo_digital_plot_ref"): - dpg.add_item_visible_handler(callback=_update_plot) - dpg.bind_item_handler_registry("_demo_digital_plot", dpg.last_container()) - - - with dpg.tree_node(label="Image Series"): - - with dpg.plot(label="Image Plot", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y axis"): - dpg.add_image_series(2, [300, 300], [400, 400], label="font atlas") - dpg.add_image_series("__demo_static_texture_2", [150, 150], [200, 200], label="static 2") - dpg.add_image_series("__demo_dynamic_texture_1", [-200, 100], [-100, 200], label="dynamic 1") - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - with dpg.tree_node(label="Candle Stick Series"): - - dates = [1546300800,1546387200,1546473600,1546560000,1546819200,1546905600,1546992000,1547078400,1547164800,1547424000,1547510400,1547596800,1547683200,1547769600,1547942400,1548028800,1548115200,1548201600,1548288000,1548374400,1548633600,1548720000,1548806400,1548892800,1548979200,1549238400,1549324800,1549411200,1549497600,1549584000,1549843200,1549929600,1550016000,1550102400,1550188800,1550361600,1550448000,1550534400,1550620800,1550707200,1550793600,1551052800,1551139200,1551225600,1551312000,1551398400,1551657600,1551744000,1551830400,1551916800,1552003200,1552262400,1552348800,1552435200,1552521600,1552608000,1552867200,1552953600,1553040000,1553126400,1553212800,1553472000,1553558400,1553644800,1553731200,1553817600,1554076800,1554163200,1554249600,1554336000,1554422400,1554681600,1554768000,1554854400,1554940800,1555027200,1555286400,1555372800,1555459200,1555545600,1555632000,1555891200,1555977600,1556064000,1556150400,1556236800,1556496000,1556582400,1556668800,1556755200,1556841600,1557100800,1557187200,1557273600,1557360000,1557446400,1557705600,1557792000,1557878400,1557964800,1558051200,1558310400,1558396800,1558483200,1558569600,1558656000,1558828800,1558915200,1559001600,1559088000,1559174400,1559260800,1559520000,1559606400,1559692800,1559779200,1559865600,1560124800,1560211200,1560297600,1560384000,1560470400,1560729600,1560816000,1560902400,1560988800,1561075200,1561334400,1561420800,1561507200,1561593600,1561680000,1561939200,1562025600,1562112000,1562198400,1562284800,1562544000,1562630400,1562716800,1562803200,1562889600,1563148800,1563235200,1563321600,1563408000,1563494400,1563753600,1563840000,1563926400,1564012800,1564099200,1564358400,1564444800,1564531200,1564617600,1564704000,1564963200,1565049600,1565136000,1565222400,1565308800,1565568000,1565654400,1565740800,1565827200,1565913600,1566172800,1566259200,1566345600,1566432000,1566518400,1566777600,1566864000,1566950400,1567036800,1567123200,1567296000,1567382400,1567468800,1567555200,1567641600,1567728000,1567987200,1568073600,1568160000,1568246400,1568332800,1568592000,1568678400,1568764800,1568851200,1568937600,1569196800,1569283200,1569369600,1569456000,1569542400,1569801600,1569888000,1569974400,1570060800,1570147200,1570406400,1570492800,1570579200,1570665600,1570752000,1571011200,1571097600,1571184000,1571270400,1571356800,1571616000,1571702400,1571788800,1571875200,1571961600] - opens = [1284.7,1319.9,1318.7,1328,1317.6,1321.6,1314.3,1325,1319.3,1323.1,1324.7,1321.3,1323.5,1322,1281.3,1281.95,1311.1,1315,1314,1313.1,1331.9,1334.2,1341.3,1350.6,1349.8,1346.4,1343.4,1344.9,1335.6,1337.9,1342.5,1337,1338.6,1337,1340.4,1324.65,1324.35,1349.5,1371.3,1367.9,1351.3,1357.8,1356.1,1356,1347.6,1339.1,1320.6,1311.8,1314,1312.4,1312.3,1323.5,1319.1,1327.2,1332.1,1320.3,1323.1,1328,1330.9,1338,1333,1335.3,1345.2,1341.1,1332.5,1314,1314.4,1310.7,1314,1313.1,1315,1313.7,1320,1326.5,1329.2,1314.2,1312.3,1309.5,1297.4,1293.7,1277.9,1295.8,1295.2,1290.3,1294.2,1298,1306.4,1299.8,1302.3,1297,1289.6,1302,1300.7,1303.5,1300.5,1303.2,1306,1318.7,1315,1314.5,1304.1,1294.7,1293.7,1291.2,1290.2,1300.4,1284.2,1284.25,1301.8,1295.9,1296.2,1304.4,1323.1,1340.9,1341,1348,1351.4,1351.4,1343.5,1342.3,1349,1357.6,1357.1,1354.7,1361.4,1375.2,1403.5,1414.7,1433.2,1438,1423.6,1424.4,1418,1399.5,1435.5,1421.25,1434.1,1412.4,1409.8,1412.2,1433.4,1418.4,1429,1428.8,1420.6,1441,1460.4,1441.7,1438.4,1431,1439.3,1427.4,1431.9,1439.5,1443.7,1425.6,1457.5,1451.2,1481.1,1486.7,1512.1,1515.9,1509.2,1522.3,1513,1526.6,1533.9,1523,1506.3,1518.4,1512.4,1508.8,1545.4,1537.3,1551.8,1549.4,1536.9,1535.25,1537.95,1535.2,1556,1561.4,1525.6,1516.4,1507,1493.9,1504.9,1506.5,1513.1,1506.5,1509.7,1502,1506.8,1521.5,1529.8,1539.8,1510.9,1511.8,1501.7,1478,1485.4,1505.6,1511.6,1518.6,1498.7,1510.9,1510.8,1498.3,1492,1497.7,1484.8,1494.2,1495.6,1495.6,1487.5,1491.1,1495.1,1506.4] - highs = [1284.75,1320.6,1327,1330.8,1326.8,1321.6,1326,1328,1325.8,1327.1,1326,1326,1323.5,1322.1,1282.7,1282.95,1315.8,1316.3,1314,1333.2,1334.7,1341.7,1353.2,1354.6,1352.2,1346.4,1345.7,1344.9,1340.7,1344.2,1342.7,1342.1,1345.2,1342,1350,1324.95,1330.75,1369.6,1374.3,1368.4,1359.8,1359,1357,1356,1353.4,1340.6,1322.3,1314.1,1316.1,1312.9,1325.7,1323.5,1326.3,1336,1332.1,1330.1,1330.4,1334.7,1341.1,1344.2,1338.8,1348.4,1345.6,1342.8,1334.7,1322.3,1319.3,1314.7,1316.6,1316.4,1315,1325.4,1328.3,1332.2,1329.2,1316.9,1312.3,1309.5,1299.6,1296.9,1277.9,1299.5,1296.2,1298.4,1302.5,1308.7,1306.4,1305.9,1307,1297.2,1301.7,1305,1305.3,1310.2,1307,1308,1319.8,1321.7,1318.7,1316.2,1305.9,1295.8,1293.8,1293.7,1304.2,1302,1285.15,1286.85,1304,1302,1305.2,1323,1344.1,1345.2,1360.1,1355.3,1363.8,1353,1344.7,1353.6,1358,1373.6,1358.2,1369.6,1377.6,1408.9,1425.5,1435.9,1453.7,1438,1426,1439.1,1418,1435,1452.6,1426.65,1437.5,1421.5,1414.1,1433.3,1441.3,1431.4,1433.9,1432.4,1440.8,1462.3,1467,1443.5,1444,1442.9,1447,1437.6,1440.8,1445.7,1447.8,1458.2,1461.9,1481.8,1486.8,1522.7,1521.3,1521.1,1531.5,1546.1,1534.9,1537.7,1538.6,1523.6,1518.8,1518.4,1514.6,1540.3,1565,1554.5,1556.6,1559.8,1541.9,1542.9,1540.05,1558.9,1566.2,1561.9,1536.2,1523.8,1509.1,1506.2,1532.2,1516.6,1519.7,1515,1519.5,1512.1,1524.5,1534.4,1543.3,1543.3,1542.8,1519.5,1507.2,1493.5,1511.4,1525.8,1522.2,1518.8,1515.3,1518,1522.3,1508,1501.5,1503,1495.5,1501.1,1497.9,1498.7,1492.1,1499.4,1506.9,1520.9] - lows = [1282.85,1315,1318.7,1309.6,1317.6,1312.9,1312.4,1319.1,1319,1321,1318.1,1321.3,1319.9,1312,1280.5,1276.15,1308,1309.9,1308.5,1312.3,1329.3,1333.1,1340.2,1347,1345.9,1338,1340.8,1335,1332,1337.9,1333,1336.8,1333.2,1329.9,1340.4,1323.85,1324.05,1349,1366.3,1351.2,1349.1,1352.4,1350.7,1344.3,1338.9,1316.3,1308.4,1306.9,1309.6,1306.7,1312.3,1315.4,1319,1327.2,1317.2,1320,1323,1328,1323,1327.8,1331.7,1335.3,1336.6,1331.8,1311.4,1310,1309.5,1308,1310.6,1302.8,1306.6,1313.7,1320,1322.8,1311,1312.1,1303.6,1293.9,1293.5,1291,1277.9,1294.1,1286,1289.1,1293.5,1296.9,1298,1299.6,1292.9,1285.1,1288.5,1296.3,1297.2,1298.4,1298.6,1302,1300.3,1312,1310.8,1301.9,1292,1291.1,1286.3,1289.2,1289.9,1297.4,1283.65,1283.25,1292.9,1295.9,1290.8,1304.2,1322.7,1336.1,1341,1343.5,1345.8,1340.3,1335.1,1341.5,1347.6,1352.8,1348.2,1353.7,1356.5,1373.3,1398,1414.7,1427,1416.4,1412.7,1420.1,1396.4,1398.8,1426.6,1412.85,1400.7,1406,1399.8,1404.4,1415.5,1417.2,1421.9,1415,1413.7,1428.1,1434,1435.7,1427.5,1429.4,1423.9,1425.6,1427.5,1434.8,1422.3,1412.1,1442.5,1448.8,1468.2,1484.3,1501.6,1506.2,1498.6,1488.9,1504.5,1518.3,1513.9,1503.3,1503,1506.5,1502.1,1503,1534.8,1535.3,1541.4,1528.6,1525.6,1535.25,1528.15,1528,1542.6,1514.3,1510.7,1505.5,1492.1,1492.9,1496.8,1493.1,1503.4,1500.9,1490.7,1496.3,1505.3,1505.3,1517.9,1507.4,1507.1,1493.3,1470.5,1465,1480.5,1501.7,1501.4,1493.3,1492.1,1505.1,1495.7,1478,1487.1,1480.8,1480.6,1487,1488.3,1484.8,1484,1490.7,1490.4,1503.1] - closes = [1283.35,1315.3,1326.1,1317.4,1321.5,1317.4,1323.5,1319.2,1321.3,1323.3,1319.7,1325.1,1323.6,1313.8,1282.05,1279.05,1314.2,1315.2,1310.8,1329.1,1334.5,1340.2,1340.5,1350,1347.1,1344.3,1344.6,1339.7,1339.4,1343.7,1337,1338.9,1340.1,1338.7,1346.8,1324.25,1329.55,1369.6,1372.5,1352.4,1357.6,1354.2,1353.4,1346,1341,1323.8,1311.9,1309.1,1312.2,1310.7,1324.3,1315.7,1322.4,1333.8,1319.4,1327.1,1325.8,1330.9,1325.8,1331.6,1336.5,1346.7,1339.2,1334.7,1313.3,1316.5,1312.4,1313.4,1313.3,1312.2,1313.7,1319.9,1326.3,1331.9,1311.3,1313.4,1309.4,1295.2,1294.7,1294.1,1277.9,1295.8,1291.2,1297.4,1297.7,1306.8,1299.4,1303.6,1302.2,1289.9,1299.2,1301.8,1303.6,1299.5,1303.2,1305.3,1319.5,1313.6,1315.1,1303.5,1293,1294.6,1290.4,1291.4,1302.7,1301,1284.15,1284.95,1294.3,1297.9,1304.1,1322.6,1339.3,1340.1,1344.9,1354,1357.4,1340.7,1342.7,1348.2,1355.1,1355.9,1354.2,1362.1,1360.1,1408.3,1411.2,1429.5,1430.1,1426.8,1423.4,1425.1,1400.8,1419.8,1432.9,1423.55,1412.1,1412.2,1412.8,1424.9,1419.3,1424.8,1426.1,1423.6,1435.9,1440.8,1439.4,1439.7,1434.5,1436.5,1427.5,1432.2,1433.3,1441.8,1437.8,1432.4,1457.5,1476.5,1484.2,1519.6,1509.5,1508.5,1517.2,1514.1,1527.8,1531.2,1523.6,1511.6,1515.7,1515.7,1508.5,1537.6,1537.2,1551.8,1549.1,1536.9,1529.4,1538.05,1535.15,1555.9,1560.4,1525.5,1515.5,1511.1,1499.2,1503.2,1507.4,1499.5,1511.5,1513.4,1515.8,1506.2,1515.1,1531.5,1540.2,1512.3,1515.2,1506.4,1472.9,1489,1507.9,1513.8,1512.9,1504.4,1503.9,1512.8,1500.9,1488.7,1497.6,1483.5,1494,1498.3,1494.1,1488.1,1487.5,1495.7,1504.7,1505.3] - - with dpg.plot(label="Candle Series", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="Day", scale=dpg.mvPlotScale_Time) - with dpg.plot_axis(dpg.mvYAxis, label="USD"): - dpg.add_candle_series(dates, opens, closes, lows, highs, label="GOOGL", time_unit=dpg.mvTimeUnit_Day) - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - - with dpg.tab(label="Subplots"): - - with dpg.tree_node(label="Basic"): - - with dpg.subplots(3, 3, label="My Subplots", width=-1, height=-1, row_ratios=[5.0, 1.0, 1.0], column_ratios=[5.0, 1.0, 1.0]) as subplot_id: - - for i in range(9): - with dpg.plot(no_title=True): - dpg.add_plot_axis(dpg.mvXAxis, label="", no_tick_labels=True) - with dpg.plot_axis(dpg.mvYAxis, label="", no_tick_labels=True): - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)") - - _add_config_options(subplot_id, 1, - "no_resize", "no_title", before=subplot_id) - - with dpg.tree_node(label="Item Sharing"): - - with dpg.subplots(2, 3, label="", width=-1, height=-1) as subplot_id: - - dpg.add_plot_legend() - - for i in range(6): - with dpg.plot(no_title=True): - dpg.add_plot_axis(dpg.mvXAxis, label="") - with dpg.plot_axis(dpg.mvYAxis, label=""): - dpg.add_line_series(sindatax, sindatay, label="data" + str(i)) - - _add_config_options(subplot_id, 1, - "column_major", before=subplot_id) - - with dpg.tree_node(label="Linked Axes"): - - with dpg.subplots(2, 2, label="", width=-1, height=-1) as subplot_id: - - dpg.add_plot_legend() - - for i in range(4): - with dpg.plot(no_title=True): - dpg.add_plot_axis(dpg.mvXAxis, label="") - with dpg.plot_axis(dpg.mvYAxis, label=""): - dpg.add_line_series(sindatax, sindatay, label="data" + str(i)) - - _add_config_options(subplot_id, 2, - "no_align", "link_rows", "link_columns", - "link_all_x", "link_all_y", before=subplot_id) - - with dpg.tab(label="Axes"): - - with dpg.tree_node(label="Time Axes"): - - timedatax = [] - timedatay = [] - - time_index = 0 - while time_index < 739497600: - timedatax.append(time_index) - timedatay.append(time_index/(60*60*24)) - time_index+=60*60*24*7 - - dpg.add_text("When time is enabled, x-axis values are interpreted as UNIX timestamps in seconds (e.g. 1599243545).", bullet=True) - dpg.add_text("UNIX timestamps are seconds since 00:00:00 UTC on 1 January 1970", bullet=True) - - with dpg.plot(label="Time Plot", height=400, width=-1): - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="Date", scale=dpg.mvPlotScale_Time) - with dpg.plot_axis(dpg.mvYAxis, label="Days since 1970"): - dpg.add_line_series(timedatax, timedatay, label="Days") - dpg.fit_axis_data(dpg.top_container_stack()) - dpg.fit_axis_data(xaxis) - - with dpg.tree_node(label="Multi Axes Plot"): - def show_hide_axis(axis, value): - dpg.configure_item(axis, show=value) - - dpg.add_checkbox(label="Show Y1", tag="show_y1", default_value=True, callback=lambda:show_hide_axis("y1_axis", dpg.get_value("show_y1"))) - dpg.add_checkbox(label="Show Y2", tag="show_y2", default_value=True, callback=lambda:show_hide_axis("y2_axis", dpg.get_value("show_y2"))) - dpg.add_checkbox(label="Show Y3", tag="show_y3", default_value=True, callback=lambda:show_hide_axis("y3_axis", dpg.get_value("show_y3"))) - dpg.add_checkbox(label="Show X1", tag="show_x1", default_value=True, callback=lambda:show_hide_axis("x1_axis", dpg.get_value("show_x1"))) - dpg.add_checkbox(label="Show X2", tag="show_x2", default_value=True, callback=lambda:show_hide_axis("x2_axis", dpg.get_value("show_x2"))) - dpg.add_checkbox(label="Show X3", tag="show_x3", default_value=True, callback=lambda:show_hide_axis("x3_axis", dpg.get_value("show_x3"))) - - #TODO Dragging a label from left to right is a bit sketchy - with dpg.plot(label="Multi Axes Plot", height=400, width=-1): - - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="x1", tag="x1_axis") - # create y axis 1 - with dpg.plot_axis(dpg.mvYAxis, label="y1", tag="y1_axis"): - dpg.add_line_series(sindatax, sindatay, label="y1") - - dpg.add_plot_axis(dpg.mvXAxis2, label="x2", tag="x2_axis", opposite=True) - # create y axis 2 - with dpg.plot_axis(dpg.mvYAxis2, label="y2", tag="y2_axis", opposite=True): - dpg.add_line_series(sindatax, cosdatay, label="y2") - - dpg.add_plot_axis(dpg.mvXAxis3, label="x3", tag="x3_axis") - # create y axis 3 - with dpg.plot_axis(dpg.mvYAxis3, label="y3", tag="y3_axis"): - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)") - - with dpg.tree_node(label="Ordering Axes Plot"): - dpg.add_checkbox(label="Opposite X", default_value=False, - callback=lambda _, val: dpg.configure_item("x_axis_ordering", opposite=val)) - dpg.add_checkbox(label="Invert X", default_value=False, - callback=lambda _, val: dpg.configure_item("x_axis_ordering", invert=val)) - dpg.add_checkbox(label="Opposite Y", default_value=False, - callback=lambda _, val: dpg.configure_item("y_axis_ordering", opposite=val)) - dpg.add_checkbox(label="Invert Y", default_value=False, - callback=lambda _, val: dpg.configure_item("y_axis_ordering", invert=val)) - - with dpg.plot(label="Ordering Axes Plot", height=400, width=-1): - - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="x", tag="x_axis_ordering") - # create y axis 1 - with dpg.plot_axis(dpg.mvYAxis, label="y", tag="y_axis_ordering"): - dpg.add_line_series(sindatax, sindatay) - - with dpg.tree_node(label="Log Axis Scale"): - xs = [0.0 for i in range(1001)] - ys1 = [0.0 for i in range(1001)] - ys2 = [0.0 for i in range(1001)] - ys3 = [0.0 for i in range(1001)] - for i in range(1,1001): - xs[i] = i*0.1 - ys1[i] = sin(xs[i]) + 1 - ys2[i] = log10(xs[i]) - ys3[i] = pow(10.0, xs[i]) - - with dpg.plot(label="Log Axes Plot", height=400, width=-1): - dpg.add_plot_legend() - - # create x axis - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x1", scale=dpg.mvPlotScale_Log10) - dpg.set_axis_limits(xaxis, 0.1, 100) - # create y axis 1 - with dpg.plot_axis(dpg.mvYAxis) as yaxis: - dpg.add_line_series(xs, xs, label="x") - dpg.add_line_series(xs, ys1, label="sin(x)+1") - dpg.add_line_series(xs, ys2, label="log(x)") - dpg.add_line_series(xs, ys3, label="10^x") - dpg.set_axis_limits(yaxis, 0, 10) - - - with dpg.tree_node(label="Time Axis"): - t_min = 1609459200; # 01/01/2021 @ 12:00:00am (UTC) - t_max = 1640995200; # 01/01/2022 @ 12:00:00am (UTC) - t_temp = t_min - while t_temp < t_max: - xs.append(t_temp) - ys1.append(sin(t_temp)) - ys2.append(cos(t_temp)) - t_temp += 86400 - - with dpg.plot(label="Time Plot", height=400, width=-1): - dpg.add_plot_legend() - - # create x axis - xaxis = dpg.add_plot_axis(dpg.mvXAxis, label="x1", scale=dpg.mvPlotScale_Time) - dpg.set_axis_limits(xaxis, t_min, t_max) - # create y axis 1 - with dpg.plot_axis(dpg.mvYAxis) as yaxis: - dpg.add_line_series(xs, ys1, label="sin(x)+1") - dpg.add_line_series(xs, ys2, label="log(x)") - - with dpg.tree_node(label="Symmetric Log Axis Scale"): - xs = [0.0 for i in range(1000)] - ys1 = [0.0 for i in range(1000)] - ys2 = [0.0 for i in range(1000)] - for i in range(1000): - xs[i] = i*0.1-50 - ys1[i] = sin(xs[i]) - ys2[i] = i*0.002 - 1 - - with dpg.plot(label="Symmetric Log Axes Plot", height=400, width=-1): - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="x1", scale=dpg.mvPlotScale_SymLog) - # create y axis 1 - with dpg.plot_axis(dpg.mvYAxis): - dpg.add_line_series(xs, ys1, label="y1") - dpg.add_line_series(xs, ys2, label="y2") - - - - with dpg.tab(label="Tools"): - - with dpg.tree_node(label="Querying"): - - dpg.add_text("Right click to box select and then click using the cancel button (standard to Left click)") - dpg.add_text("Double left click to delete the last drag rect drawn.") - dpg.add_slider_int(min_value=0, max_value=100, default_value=1, label="Min query rects", callback=lambda _, val: dpg.configure_item("query_plot_1", min_query_rects=val)) - dpg.add_slider_int(min_value=0, max_value=100, default_value=1, label="Max query rects", callback=lambda _, val: dpg.configure_item("query_plot_1", max_query_rects=val)) - - def query(sender, app_data, user_data): - if not len(app_data): - return - dpg.set_axis_limits(user_data[0], app_data[0][0], app_data[0][2]) - dpg.set_axis_limits(user_data[1], app_data[0][3], app_data[0][1]) - - # plot 1 - with dpg.plot(no_title=True, height=400, tag="query_plot_1", callback=query, query=True, no_menus=True, width=-1) as plot_id: - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_line_series(sindatax, sindatay) - - dpg.add_text("This plot takes care only of the first query rect") - # plot 2 - with dpg.plot(no_title=True, height=400, no_menus=True, width=-1, tag="plot2"): - xaxis_id2 = dpg.add_plot_axis(dpg.mvXAxis, label="x") - yaxis_id2 = dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.add_line_series(sindatax, sindatay, parent=yaxis_id2) - - # set plot 1 user data to axis so the query callback has access - dpg.configure_item(plot_id, user_data=(xaxis_id2,yaxis_id2)) - - with dpg.tree_node(label="Drag Lines/Points"): - - with dpg.plot(label="Drag Lines/Points", height=400, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y") - - # drag lines/points belong to the plot NOT axis - dpg.add_drag_line(label="dline1", color=[255, 0, 0, 255]) - dpg.add_drag_line(color=[255, 255, 0, 255], vertical=False) - dpg.add_drag_point(label="dpoint1", color=[255, 0, 255, 255]) - dpg.add_drag_point(label="dpoint2", color=[255, 0, 255, 255]) - - with dpg.tree_node(label="Drag Rects"): - - def drag_query(sender, app_data, user_data): - dpg.set_axis_limits(user_data[0], app_data[0][0], app_data[0][2]) - dpg.set_axis_limits(user_data[1], app_data[0][3], app_data[0][1]) - - with dpg.plot(label="Drag Rects", height=400, width=-1, callback=drag_query) as plot_drag: - - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - dpg.add_line_series(sindatax, sindatay) - # drag rects belong to the plot NOT axis - dpg.add_drag_rect(label="drag rect 1", tag="drag_rect", color=[255, 0, 0, 255], default_value=(-1,1)) - - with dpg.plot(no_title=True, height=400, no_menus=True, width=-1, tag="drag_plot2"): - xaxis_drag2 = dpg.add_plot_axis(dpg.mvXAxis, label="x") - yaxis_drag2 = dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.add_line_series(sindatax, sindatay, parent=yaxis_drag2) - - # set plot 1 user data to axis so the query callback has access - dpg.configure_item(plot_drag, user_data=(xaxis_drag2,yaxis_drag2)) - - with dpg.tree_node(label="Annotations"): - - with dpg.plot(label="Annotations", height=400, width=-1): - - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent=dpg.last_item()) - - # annotations belong to the plot NOT axis - dpg.add_plot_annotation(label="BL", default_value=(0.25, 0.25), offset=(-15, 15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="BR", default_value=(0.75, 0.25), offset=(15, 15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="TR not clampled", default_value=(0.75, 0.75), offset=(-15, -15), color=[255, 255, 0, 255], clamped=False) - dpg.add_plot_annotation(label="TL", default_value=(0.25, 0.75), offset=(-15, -15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="Center", default_value=(0.5, 0.5), color=[255, 255, 0, 255]) - - with dpg.tree_node(label="Tags"): - with dpg.plot(height=400, width=-1): - with dpg.plot_axis(dpg.mvXAxis): - dpg.add_axis_tag(default_value=0.25, color=(255, 255, 0, 255)) - with dpg.plot_axis(dpg.mvYAxis): - dpg.add_axis_tag(default_value=0.75, color=(255, 255, 0, 255)) - dpg.add_drag_line(vertical=False, label="Drag", default_value=0.25, color=(255, 0, 0, 255), no_fit=True) - with dpg.plot_axis(dpg.mvXAxis2): - dpg.add_axis_tag(default_value=0.5, color=(0, 255, 255, 255), label="MyTag") - with dpg.plot_axis(dpg.mvYAxis2): - dpg.add_axis_tag(default_value=0.5, color=(0, 255, 255, 255), label="Tag: 42") - - with dpg.tree_node(label="Drag & Drop"): - - sindatax = [] - sindatay = [] - for i in range(100): - sindatax.append(i/100) - sindatay.append(0.5 + 0.5*sin(50*i/100)) - - with dpg.group(horizontal=True): - with dpg.group(): - - dpg.add_text("Sources:") - - dpg.add_button(label="Source 1") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=(sindatax, sindatay, "Source 1"), payload_type="plotting"): - dpg.add_text("Source 1") - dpg.add_simple_plot(label="", default_value=sindatay) - - def _legend_drop(sender, app_data, user_data): - parent = dpg.get_item_info(sender)["parent"] - yaxis2 = dpg.get_item_info(parent)["children"][1][2] - dpg.add_line_series(app_data[0], app_data[1], label=app_data[2], parent=yaxis2) - dpg.add_button(label="Delete Series", user_data = dpg.last_item(), parent=dpg.last_item(), callback=lambda s, a, u: dpg.delete_item(u)) - - def _plot_drop(sender, app_data, user_data): - yaxis1 = dpg.get_item_info(sender)["children"][1][0] - dpg.add_line_series(app_data[0], app_data[1], label=app_data[2], parent=yaxis1) - dpg.add_button(label="Delete Series", user_data = dpg.last_item(), parent=dpg.last_item(), callback=lambda s, a, u: dpg.delete_item(u)) - - def _axis_drop(sender, app_data, user_data): - dpg.add_line_series(app_data[0], app_data[1], label=app_data[2], parent=sender) - dpg.add_button(label="Delete Series", user_data = dpg.last_item(), parent=dpg.last_item(), callback=lambda s, a, u: dpg.delete_item(u)) - - with dpg.plot(label="Drag/Drop Plot", height=400, width=-1, drop_callback=_plot_drop, payload_type="plotting"): - dpg.add_plot_legend(drop_callback=_legend_drop, payload_type="plotting") - dpg.add_plot_axis(dpg.mvXAxis, label="x") - - # create y axes with drop callbacks - dpg.add_plot_axis(dpg.mvYAxis, label="y1", drop_callback=_axis_drop, payload_type="plotting") - dpg.add_plot_axis(dpg.mvYAxis2, label="y2", drop_callback=_axis_drop, payload_type="plotting") - dpg.add_plot_axis(dpg.mvYAxis3, label="y3", drop_callback=_axis_drop, payload_type="plotting") - - - - with dpg.tree_node(label="Legend Options"): - def add_remove_location(type, add): - if add: - dpg.configure_item("plot_legend", - location = dpg.get_item_configuration("plot_legend")['location'] + type) - else: - dpg.configure_item("plot_legend", - location = dpg.get_item_configuration("plot_legend")['location'] - type) - with dpg.group(horizontal=True): - dpg.add_checkbox(label="North", tag="north_legend", - callback=lambda: add_remove_location(dpg.mvPlot_Location_North, dpg.get_value("north_legend"))) - dpg.add_checkbox(label="East", tag="east_legend", - callback=lambda: add_remove_location(dpg.mvPlot_Location_East, dpg.get_value("east_legend"))) - dpg.add_checkbox(label="West", tag="west_legend", - callback=lambda: add_remove_location(dpg.mvPlot_Location_West, dpg.get_value("west_legend"))) - dpg.add_checkbox(label="South", tag="south_legend", - callback=lambda: add_remove_location(dpg.mvPlot_Location_South, dpg.get_value("south_legend"))) - dpg.add_checkbox(label="Horizontal", tag="horizontal_legend", - callback=lambda: dpg.configure_item("plot_legend", horizontal=dpg.get_value("horizontal_legend"))) - dpg.add_checkbox(label="Outside", tag="outside_legend", - callback=lambda: dpg.configure_item("plot_legend", outside=dpg.get_value("outside_legend"))) - dpg.add_checkbox(label="Sort", tag="sort_legend", - callback=lambda: dpg.configure_item("plot_legend", sort=dpg.get_value("sort_legend"))) - - with dpg.plot(): - dpg.add_plot_legend(tag="plot_legend", location=0, outside=False, sort=False, horizontal=False) - with dpg.plot_axis(dpg.mvYAxis): - dpg.add_line_series(sindatax, sindatay, label="2") - dpg.add_line_series(sindatax, sindatay, label="1") - dpg.add_line_series(sindatax, sindatay, label="3") - - with dpg.tree_node(label="Legend Popups"): - vals=[] - frequency = 0.1 - amplitude = 0.5 - color = (1,1,0,1) - alpha = 1.0 - line = False - thickness = 1 - markers = False - shaded = False - x = [i for i in range(101)] - vals = [0.0 for i in range(101)] - for i in range(101): - vals[i] = amplitude * sin(frequency * i) - - def recalculate_vals(amplitude, frequency): - for i in range(101): - vals[i] = amplitude * sin(frequency * i) - dpg.configure_item("bar_custom_legend", y=vals) - - with dpg.plot(label="Line Series"): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - - with dpg.plot_axis(dpg.mvYAxis): - dpg.add_bar_series(x, vals, tag="bar_custom_legend", label="Right Click Me!") - with dpg.group(parent=dpg.last_item()): - dpg.add_slider_float(label="Frequency", default_value=frequency, min_value=0.01, max_value=5.0, - tag="frequency", callback=lambda: recalculate_vals(dpg.get_value("amplitude"), dpg.get_value("frequency"))) - dpg.add_slider_float(label="Amplitude", default_value=amplitude, min_value=0.01, max_value=5.0, - tag="amplitude", callback=lambda: recalculate_vals(dpg.get_value("amplitude"), dpg.get_value("frequency"))) - dpg.add_separator() - - with dpg.tab(label="Custom"): - - with dpg.tree_node(label="Custom Context Menus"): - - dpg.add_text("Right-click the series in the legend.", bullet=True) - dpg.add_text("Series are containers. Children will show up in the custom context menu.", bullet=True) - - # create plot - with dpg.plot(label="Line Series", height=400, width=-1): - - dpg.add_plot_legend() - - dpg.add_plot_axis(dpg.mvXAxis, label="x") - with dpg.plot_axis(dpg.mvYAxis, label="y"): - - # series 1 - dpg.add_line_series(sindatax, sindatay, label="series 1") - dpg.add_button(label="Delete Series 1", user_data = dpg.last_item(), parent=dpg.last_item(), callback=lambda s, a, u: dpg.delete_item(u)) - - # series 2 - dpg.add_line_series(sindatax, sindatay, label="series 2") - dpg.add_button(label="Delete Series 2", user_data = dpg.last_item(), parent=dpg.last_item(), callback=lambda s, a, u: dpg.delete_item(u)) - - with dpg.tree_node(label="Custom Rendering"): - - # create plot - with dpg.plot(label="Custom Rendering", height=400, width=-1): - - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y") - - dpg.draw_line((0, 0), (1, 2), color=(255, 0, 0, 255), thickness=0.01) - dpg.draw_text((0, 0), "Origin", color=(250, 250, 250, 255), size=0.1) - - with dpg.tree_node(label="Custom Series"): - - def _custom_series_callback(sender, app_data): - _helper_data = app_data[0] - transformed_x = app_data[1] - transformed_y = app_data[2] - mouse_x_plot_space = _helper_data["MouseX_PlotSpace"] - mouse_y_plot_space = _helper_data["MouseY_PlotSpace"] - mouse_x_pixel_space = _helper_data["MouseX_PixelSpace"] - mouse_y_pixel_space = _helper_data["MouseY_PixelSpace"] - dpg.delete_item(sender, children_only=True, slot=2) - dpg.push_container_stack(sender) - dpg.configure_item("demo_custom_series", tooltip=False) - for i in range(0, len(transformed_x)): - dpg.draw_text((transformed_x[i]+15, transformed_y[i]-15), str(i), size=20) - dpg.draw_circle((transformed_x[i], transformed_y[i]), 15, fill=(50+i*5, 50+i*50, 0, 255)) - if mouse_x_pixel_space < transformed_x[i]+15 and mouse_x_pixel_space > transformed_x[i]-15 and mouse_y_pixel_space > transformed_y[i]-15 and mouse_y_pixel_space < transformed_y[i]+15: - dpg.draw_circle((transformed_x[i], transformed_y[i]), 30) - dpg.configure_item("demo_custom_series", tooltip=True) - dpg.set_value("demo_custom_series_text", "Current Point: " + str(i)) - dpg.pop_container_stack() - - # create plot - dpg.add_text("Hover an item for a custom tooltip!") - with dpg.plot(label="Custom Series", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis) - with dpg.plot_axis(dpg.mvYAxis): - with dpg.custom_series([0.0, 1.0, 2.0, 4.0, 5.0], [0.0, 10.0, 20.0, 40.0, 50.0], 2, label="Custom Series", callback=_custom_series_callback, tag="demo_custom_series"): - dpg.add_text("Current Point: ", tag="demo_custom_series_text") - dpg.fit_axis_data(dpg.top_container_stack()) - - with dpg.tab(label="Help"): - - dpg.add_text("Plotting User Guide") - dpg.add_text("Left click and drag within the plot area to pan X and Y axes.", bullet=True) - dpg.add_text("Left click and drag on an axis to pan an individual axis.", bullet=True, indent=20) - dpg.add_text("Scoll in the plot area to zoom both X and Y axes.", bullet=True) - dpg.add_text("Scroll on an axis to zoom an individual axis.", bullet=True, indent=20) - dpg.add_text("Right click and drag to box select data.", bullet=True) - dpg.add_text("Hold Alt to expand box selection horizontally.", bullet=True, indent=20) - dpg.add_text("Hold Shift to expand box selection vertically.", bullet=True, indent=20) - dpg.add_text("Left click while box selecting to cancel the selection.", bullet=True, indent=20) - dpg.add_text("Double left click to fit all visible data.", bullet=True) - dpg.add_text("Double left click on an axis to fit the individual axis", bullet=True, indent=20) - dpg.add_text("Double right click to open the plot context menu.", bullet=True) - dpg.add_text("Click legend label icons to show/hide plot items.", bullet=True) - dpg.add_text("IMPORTANT: By default, anti-aliased lines are turned OFF.", bullet=True) - - with dpg.collapsing_header(label="Node Editor"): - - dpg.add_text("Ctrl+Click to remove a link.", bullet=True) - - with dpg.node_editor(callback=lambda sender, app_data: dpg.add_node_link(app_data[0], app_data[1], parent=sender), - delink_callback=lambda sender, app_data: dpg.delete_item(app_data), minimap=True, minimap_location=dpg.mvNodeMiniMap_Location_BottomRight): - - with dpg.node(label="Node 1", pos=[10, 10]): - - with dpg.node_attribute(): - dpg.add_input_float(label="F1", width=150) - - with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Output): - dpg.add_input_float(label="F2", width=150) - - with dpg.node(label="Node 2", pos=[300, 10]): - - with dpg.node_attribute() as na2: - dpg.add_input_float(label="F3", width=200) - - with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Output): - dpg.add_input_float(label="F4", width=200) - - with dpg.node(label="Node 3", pos=[25, 150]): - with dpg.node_attribute(): - dpg.add_input_text(label="T5", width=200) - with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Static): - dpg.add_simple_plot(label="Node Plot", default_value=(0.3, 0.9, 2.5, 8.9), width=200, height=80, histogram=True) - - with dpg.collapsing_header(label= "Filtering"): - - dpg.add_text("Filter usage:\n" - " \"\" display all lines\n" - " \"xxx\" display lines containing \"xxx\"\n" - " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" - " \"-xxx\" hide lines containing \"xxx\"") - - dpg.add_input_text(label="Filter (inc, -exc)", callback=lambda s, a: dpg.set_value("__demo_filter", a)) - with dpg.filter_set(tag="__demo_filter"): - dpg.add_text("aaa1.c", filter_key="aaa1.c", bullet=True) - dpg.add_text("bbb1.c", filter_key="bbb1.c", bullet=True) - dpg.add_text("ccc1.c", filter_key="ccc1.c", bullet=True) - dpg.add_text("aaa2.cpp", filter_key="aaa2.cpp", bullet=True) - dpg.add_text("bbb2.cpp", filter_key="bbb2.cpp", bullet=True) - dpg.add_text("ccc2.cpp", filter_key="ccc2.cpp", bullet=True) - dpg.add_text("abc.h", filter_key="abc.h", bullet=True) - dpg.add_text("hello, world", filter_key="hello, world", bullet=True) - - with dpg.collapsing_header(label="Drawing API"): - - with dpg.tree_node(label="Basic"): - draw_thickness = 3.0 - draw_size = 36 - draw_spacing = 10 - draw_rounding = draw_size/5.0 - draw_color = [255, 255, 0] - with dpg.drawlist(width=300, height=200): - draw_x = 4 - draw_y = 4 - for i in range(2): - - _draw_t = draw_thickness - if i == 0: - _draw_t = 1.0 - dpg.draw_circle([draw_x + draw_size*0.5, draw_y + draw_size*0.5], draw_size*0.5, thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_rectangle([draw_x, draw_y], [draw_size + draw_x, draw_size + draw_y], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_rectangle([draw_x, draw_y], [draw_size + draw_x, draw_size + draw_y], rounding=draw_rounding, thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_triangle([draw_x+draw_size*0.5,draw_y], [draw_x+draw_size, draw_y+draw_size-0.5], [draw_x, draw_y+draw_size-0.5], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_line([draw_x, draw_y], [draw_x + draw_size, draw_y], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_line([draw_x, draw_y], [draw_x, draw_y + draw_size], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_line([draw_x, draw_y], [draw_x + draw_size, draw_y + draw_size], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_bezier_quadratic([draw_x, draw_y + draw_size * 0.6], - [draw_x + draw_size*0.5, draw_y - draw_size * 0.4], - [draw_x + draw_size, draw_y + draw_size], thickness=_draw_t, color=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_bezier_cubic([draw_x, draw_y], - [draw_x + draw_size*1.3, draw_y + draw_size * 0.3], - [draw_x+draw_size - draw_size*1.3, draw_y + draw_size - draw_size*0.3], - [draw_x + draw_size, draw_y + draw_size], thickness=_draw_t, color=draw_color) - draw_x = 4 - draw_y = draw_y + draw_size + draw_spacing - - _draw_t = 0.0 - - dpg.draw_circle([draw_x + draw_size*0.5, draw_y + draw_size*0.5], draw_size*0.5, thickness=_draw_t, color=draw_color, fill=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_rectangle([draw_size + draw_x, draw_size + draw_y], [draw_x, draw_y], thickness=_draw_t, color=draw_color, fill=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_rectangle([draw_x, draw_y], [draw_size + draw_x, draw_size + draw_y], rounding=draw_rounding, thickness=_draw_t, color=draw_color, fill=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_triangle([draw_x+draw_size*0.5,draw_y], [draw_x+draw_size, draw_y+draw_size-0.5], [draw_x, draw_y+draw_size-0.5], thickness=_draw_t, color=draw_color, fill=draw_color) - draw_x = draw_x + draw_spacing + draw_size - dpg.draw_rectangle([draw_size + draw_x, draw_size + draw_y], [draw_x, draw_y], color=[0, 0, 0, 0], thickness=_draw_t, corner_colors=[[0, 0, 0], [255, 0, 0], [0, 255, 0], [255, 255, 0]], multicolor=True) - - with dpg.tree_node(label="Draw Nodes & 3D transforms"): - - with dpg.group(horizontal=True): - with dpg.drawlist(width=500, height=500, tag="_demo_advanced_drawing"): - - with dpg.draw_layer(): - - dpg.draw_circle([250, 250], 150, color=[0, 255, 0]) - dpg.draw_circle([250, 250], 200, color=[0, 255, 255]) - with dpg.draw_node(tag="_drawing_sun"): - dpg.apply_transform(dpg.last_item(), dpg.create_translation_matrix([250, 250])) - dpg.draw_circle([0, 0], 15, color=[255, 255, 0], fill=[255, 255, 0]) - with dpg.draw_node(tag="_drawing_planet1", user_data=45.0): - dpg.apply_transform(dpg.last_item(), dpg.create_rotation_matrix(math.pi*45.0/180.0 , [0, 0, -1])*dpg.create_translation_matrix([150, 0])) - dpg.draw_circle([0, 0], 10, color=[0, 255, 0], fill=[0, 255, 0]) - dpg.draw_circle([0, 0], 25, color=[255, 0, 255]) - with dpg.draw_node(tag="_drawing_moon1", user_data=45.0): - dpg.apply_transform(dpg.last_item(), dpg.create_rotation_matrix(math.pi*45.0/180.0 , [0, 0, -1])*dpg.create_translation_matrix([25, 0])) - dpg.draw_circle([0, 0], 5, color=[255, 0, 255], fill=[255, 0, 255]) - - with dpg.draw_node(tag="_drawing_planet2", user_data=0.0): - dpg.apply_transform(dpg.last_item(), dpg.create_rotation_matrix(math.pi*0.0/180.0 , [0, 0, -1])*dpg.create_translation_matrix([200, 0])) - dpg.draw_circle([0, 0], 10, color=[0, 255, 255], fill=[0, 255, 255]) - dpg.draw_circle([0, 0], 25, color=[255, 0, 255]) - dpg.draw_circle([0, 0], 45, color=[255, 255, 255]) - with dpg.draw_node(tag="_drawing_moon2", user_data=45.0): - dpg.apply_transform(dpg.last_item(), dpg.create_rotation_matrix(math.pi*45.0/180.0 , [0, 0, -1])*dpg.create_translation_matrix([25, 0])) - dpg.draw_circle([0, 0], 5, color=[255, 0, 255], fill=[255, 0, 255]) - - with dpg.draw_node(tag="_drawing_moon3", user_data=120.0): - dpg.apply_transform(dpg.last_item(), dpg.create_rotation_matrix(math.pi*120.0/180.0 , [0, 0, -1])*dpg.create_translation_matrix([45, 0])) - dpg.draw_circle([0, 0], 5, color=[255, 255, 255], fill=[255, 255, 255]) - - def _demo_live_drawing(): - planet_rot1 = dpg.get_item_user_data("_drawing_planet1") + 1.0 - planet_rot2 = dpg.get_item_user_data("_drawing_planet2") + 2.0 - moon_rot1 = dpg.get_item_user_data("_drawing_moon1") + 3.0 - moon_rot2 = dpg.get_item_user_data("_drawing_moon2") + 7.0 - moon_rot3 = dpg.get_item_user_data("_drawing_moon3") + 10.0 - dpg.apply_transform("_drawing_planet1", dpg.create_rotation_matrix(math.pi*planet_rot1/180.0 , [0, 0, -1])*dpg.create_translation_matrix([150, 0])) - dpg.apply_transform("_drawing_planet2", dpg.create_rotation_matrix(math.pi*planet_rot2/180.0 , [0, 0, -1])*dpg.create_translation_matrix([200, 0])) - dpg.apply_transform("_drawing_moon1", dpg.create_rotation_matrix(math.pi*moon_rot1/180.0 , [0, 0, -1])*dpg.create_translation_matrix([25, 0])) - dpg.apply_transform("_drawing_moon2", dpg.create_rotation_matrix(math.pi*moon_rot2/180.0 , [0, 0, -1])*dpg.create_translation_matrix([25, 0])) - dpg.apply_transform("_drawing_moon3", dpg.create_rotation_matrix(math.pi*moon_rot3/180.0 , [0, 0, 1])*dpg.create_translation_matrix([45, 0])) - dpg.set_item_user_data("_drawing_planet1", planet_rot1) - dpg.set_item_user_data("_drawing_planet2", planet_rot2) - dpg.set_item_user_data("_drawing_moon1", moon_rot1) - dpg.set_item_user_data("_drawing_moon2", moon_rot2) - dpg.set_item_user_data("_drawing_moon3", moon_rot3) - - with dpg.item_handler_registry(tag="__demo_item_reg6"): - dpg.add_item_visible_handler(callback=_demo_live_drawing) - dpg.bind_item_handler_registry("_demo_advanced_drawing", dpg.last_container()) - - - size = 5 - demo_verticies = [ - [-size, -size, -size], # 0 near side - [ size, -size, -size], # 1 - [-size, size, -size], # 2 - [ size, size, -size], # 3 - [-size, -size, size], # 4 far side - [ size, -size, size], # 5 - [-size, size, size], # 6 - [ size, size, size], # 7 - [-size, -size, -size], # 8 left side - [-size, size, -size], # 9 - [-size, -size, size], # 10 - [-size, size, size], # 11 - [ size, -size, -size], # 12 right side - [ size, size, -size], # 13 - [ size, -size, size], # 14 - [ size, size, size], # 15 - [-size, -size, -size], # 16 bottom side - [ size, -size, -size], # 17 - [-size, -size, size], # 18 - [ size, -size, size], # 19 - [-size, size, -size], # 20 top side - [ size, size, -size], # 21 - [-size, size, size], # 22 - [ size, size, size], # 23 - ] - - demo_colors = [ - [255, 0, 0, 150], - [255, 255, 0, 150], - [255, 255, 255, 150], - [255, 0, 255, 150], - [ 0, 255, 0, 150], - [ 0, 255, 255, 150], - [ 0, 0, 255, 150], - [ 0, 125, 0, 150], - [128, 0, 0, 150], - [128, 70, 0, 150], - [128, 255, 255, 150], - [128, 0, 128, 150] - ] - - with dpg.drawlist(width=500, height=500, tag="_demo_advanced_drawing_3d"): - - with dpg.draw_layer(depth_clipping=False, cull_mode=dpg.mvCullMode_Back, perspective_divide=True): - dpg.set_clip_space(dpg.last_item(), 0, 0, 500, 500, -1.0, 1.0) - with dpg.draw_node(tag="_demo_3dNode1", user_data=[0, 0, 0]): - dpg.draw_triangle(demo_verticies[1], demo_verticies[2], demo_verticies[0], color=[0,0,0.0], fill=demo_colors[0]) - dpg.draw_triangle(demo_verticies[1], demo_verticies[3], demo_verticies[2], color=[0,0,0.0], fill=demo_colors[1]) - dpg.draw_triangle(demo_verticies[7], demo_verticies[5], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[2]) - dpg.draw_triangle(demo_verticies[6], demo_verticies[7], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[3]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[10], demo_verticies[8], color=[0,0,0.0], fill=demo_colors[4]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[11], demo_verticies[10], color=[0,0,0.0], fill=demo_colors[5]) - dpg.draw_triangle(demo_verticies[15], demo_verticies[13], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[6]) - dpg.draw_triangle(demo_verticies[14], demo_verticies[15], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[7]) - dpg.draw_triangle(demo_verticies[18], demo_verticies[17], demo_verticies[16], color=[0,0,0.0], fill=demo_colors[8]) - dpg.draw_triangle(demo_verticies[19], demo_verticies[17], demo_verticies[18], color=[0,0,0.0], fill=demo_colors[9]) - dpg.draw_triangle(demo_verticies[21], demo_verticies[23], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[10]) - dpg.draw_triangle(demo_verticies[23], demo_verticies[22], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[11]) - - with dpg.group(horizontal=True): - - with dpg.drawlist(width=500, height=500): - - with dpg.draw_layer(depth_clipping=False, cull_mode=dpg.mvCullMode_Front, perspective_divide=True): - dpg.set_clip_space(dpg.last_item(), 0, 0, 500, 500, -1.0, 1.0) - with dpg.draw_node(tag="_demo_3dNode2", user_data=[0, 0, 0]): - dpg.draw_triangle(demo_verticies[1], demo_verticies[2], demo_verticies[0], color=[0,0,0.0], fill=demo_colors[0]) - dpg.draw_triangle(demo_verticies[1], demo_verticies[3], demo_verticies[2], color=[0,0,0.0], fill=demo_colors[1]) - dpg.draw_triangle(demo_verticies[7], demo_verticies[5], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[2]) - dpg.draw_triangle(demo_verticies[6], demo_verticies[7], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[3]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[10], demo_verticies[8], color=[0,0,0.0], fill=demo_colors[4]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[11], demo_verticies[10], color=[0,0,0.0], fill=demo_colors[5]) - dpg.draw_triangle(demo_verticies[15], demo_verticies[13], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[6]) - dpg.draw_triangle(demo_verticies[14], demo_verticies[15], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[7]) - dpg.draw_triangle(demo_verticies[18], demo_verticies[17], demo_verticies[16], color=[0,0,0.0], fill=demo_colors[8]) - dpg.draw_triangle(demo_verticies[19], demo_verticies[17], demo_verticies[18], color=[0,0,0.0], fill=demo_colors[9]) - dpg.draw_triangle(demo_verticies[21], demo_verticies[23], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[10]) - dpg.draw_triangle(demo_verticies[23], demo_verticies[22], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[11]) - - with dpg.drawlist(width=500, height=500): - - with dpg.draw_layer(depth_clipping=False, cull_mode=dpg.mvCullMode_None, perspective_divide=True): - dpg.set_clip_space(dpg.last_item(), 0, 0, 500, 500, -1.0, 1.0) - with dpg.draw_node(tag="_demo_3dNode3", user_data=[0, 0, 0]): - dpg.draw_triangle(demo_verticies[1], demo_verticies[2], demo_verticies[0], color=[0,0,0.0], fill=demo_colors[0]) - dpg.draw_triangle(demo_verticies[1], demo_verticies[3], demo_verticies[2], color=[0,0,0.0], fill=demo_colors[1]) - dpg.draw_triangle(demo_verticies[7], demo_verticies[5], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[2]) - dpg.draw_triangle(demo_verticies[6], demo_verticies[7], demo_verticies[4], color=[0,0,0.0], fill=demo_colors[3]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[10], demo_verticies[8], color=[0,0,0.0], fill=demo_colors[4]) - dpg.draw_triangle(demo_verticies[9], demo_verticies[11], demo_verticies[10], color=[0,0,0.0], fill=demo_colors[5]) - dpg.draw_triangle(demo_verticies[15], demo_verticies[13], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[6]) - dpg.draw_triangle(demo_verticies[14], demo_verticies[15], demo_verticies[12], color=[0,0,0.0], fill=demo_colors[7]) - dpg.draw_triangle(demo_verticies[18], demo_verticies[17], demo_verticies[16], color=[0,0,0.0], fill=demo_colors[8]) - dpg.draw_triangle(demo_verticies[19], demo_verticies[17], demo_verticies[18], color=[0,0,0.0], fill=demo_colors[9]) - dpg.draw_triangle(demo_verticies[21], demo_verticies[23], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[10]) - dpg.draw_triangle(demo_verticies[23], demo_verticies[22], demo_verticies[20], color=[0,0,0.0], fill=demo_colors[11]) - - def _demo_live_3D_drawing(): - view_matrix = dpg.create_fps_matrix([0, 0, 50], 0.0, 0.0) - proj_matrix = dpg.create_perspective_matrix(math.pi*45.0/180.0, 500/500, 0.1, 100) - cube_rot = dpg.get_item_user_data("_demo_3dNode1") - cube_rot[0] = cube_rot[0] + 1.0 - cube_rot[1] = cube_rot[1] + 2.0 - cube_rot[2] = cube_rot[2] + 3.0 - model_matrix = dpg.create_rotation_matrix(math.pi*cube_rot[0]/180.0 , [1, 0, 0])*\ - dpg.create_rotation_matrix(math.pi*cube_rot[1]/180.0 , [0, 1, 0])*\ - dpg.create_rotation_matrix(math.pi*cube_rot[2]/180.0 , [0, 0, 1]) - dpg.apply_transform("_demo_3dNode1", proj_matrix*view_matrix*model_matrix) - dpg.apply_transform("_demo_3dNode2", proj_matrix*view_matrix*model_matrix) - dpg.apply_transform("_demo_3dNode3", proj_matrix*view_matrix*model_matrix) - dpg.set_item_user_data("_demo_3dNode1", cube_rot) - - with dpg.item_handler_registry(tag="__demo_item_reg7"): - dpg.add_item_visible_handler(callback=_demo_live_3D_drawing) - dpg.bind_item_handler_registry("_demo_advanced_drawing_3d", dpg.last_container()) - - with dpg.collapsing_header(label="Inputs & Events"): - - with dpg.tree_node(label="Global"): - - with dpg.handler_registry(show=False, tag="__demo_keyboard_handler"): - k_down = dpg.add_key_down_handler(key=dpg.mvKey_A) - k_release = dpg.add_key_release_handler(key=dpg.mvKey_A) - k_press = dpg.add_key_press_handler(key=dpg.mvKey_A) - - with dpg.handler_registry(show=False, tag="__demo_mouse_handler"): - m_wheel = dpg.add_mouse_wheel_handler() - m_click = dpg.add_mouse_click_handler(button=dpg.mvMouseButton_Left) - m_double_click = dpg.add_mouse_double_click_handler(button=dpg.mvMouseButton_Left) - m_release = dpg.add_mouse_release_handler(button=dpg.mvMouseButton_Left) - m_drag = dpg.add_mouse_drag_handler(button=dpg.mvMouseButton_Left) - m_down = dpg.add_mouse_down_handler(button=dpg.mvMouseButton_Left) - m_move = dpg.add_mouse_move_handler() - - dpg.add_checkbox(label="Activate Keyboard Handlers (A key)", callback=lambda s, a: dpg.configure_item("__demo_keyboard_handler", show=a)) - dpg.add_checkbox(label="Activate Mouse Handlers (left button)", callback=lambda s, a: dpg.configure_item("__demo_mouse_handler", show=a)) - kh_down = dpg.add_text("Key id: seconds:", label="Key Down Handler:", show_label=True) - kh_release = dpg.add_text("Key id:", label="Key Release Handler:", show_label=True) - kh_press = dpg.add_text("Key id:", label="Key Press Handler:", show_label=True) - mh_click = dpg.add_text("Mouse id:", label="Mouse Click Handler", show_label=True) - mh_double = dpg.add_text("Mouse id:", label="Mouse Double Click Handler", show_label=True) - mh_down = dpg.add_text("Mouse id: seconds:", label="Mouse Down Handler", show_label=True) - mh_release = dpg.add_text("Mouse id:", label="Mouse Release Handler", show_label=True) - mh_wheel = dpg.add_text("Mouse id:", label="Mouse Wheel Handler", show_label=True) - mh_move = dpg.add_text("Mouse pos:", label="Mouse Move Handler", show_label=True) - mh_drag = dpg.add_text("Mouse id: delta:", label="Mouse Drag Handler", show_label=True) - - with dpg.tree_node(label="Item"): - - dpg.add_text("Interact with following widgets and check output!") - dpg.add_text("Note: Only the click, hover are added. Others are commented out. Check the code!") - cb = dpg.add_checkbox(label="Check me!", tag="democheck") - - with dpg.item_handler_registry(tag="demoitemregistry"): - dpg.add_item_clicked_handler(0, callback=lambda s, a, u: print(f"clicked_handler: {s} '\t' {a} '\t' {u}")) - dpg.add_item_clicked_handler(1, callback=lambda s, a, u: print(f"clicked_handler: {s} '\t' {a} '\t' {u}")) - dpg.add_item_hover_handler(callback=lambda s, a, u: print(f"hover_handler: {s} '\t' {a} '\t' {u}")) - dpg.bind_item_handler_registry(cb, "demoitemregistry") - - def _event_handler(sender, data): - type=dpg.get_item_info(sender)["type"] - if type=="mvAppItemType::mvKeyDownHandler": - dpg.set_value(kh_down, f"Key id: {data[0]}, Seconds:{data[1]}") - elif type=="mvAppItemType::mvKeyReleaseHandler": - dpg.set_value(kh_release, f"Key id: {data}") - elif type=="mvAppItemType::mvKeyPressHandler": - dpg.set_value(kh_press, f"Key id: {data} + Shift: {dpg.is_key_down(dpg.mvKey_LShift)}") - elif type=="mvAppItemType::mvMouseClickHandler": - dpg.set_value(mh_click, f"Mouse id: {data} + Shift: {dpg.is_key_down(dpg.mvKey_LShift)}") - elif type=="mvAppItemType::mvMouseDoubleClickHandler": - dpg.set_value(mh_double, f"Mouse id: {data}") - elif type=="mvAppItemType::mvMouseDownHandler": - dpg.set_value(mh_down, f"Mouse id: {data[0]}, Seconds:{data[1]}") - elif type=="mvAppItemType::mvMouseReleaseHandler": - dpg.set_value(mh_release, f"Mouse id: {data}") - elif type=="mvAppItemType::mvMouseWheelHandler": - dpg.set_value(mh_wheel, f"Mouse id: {data}") - elif type=="mvAppItemType::mvMouseMoveHandler": - dpg.set_value(mh_move, f"Mouse pos: {data}") - elif type=="mvAppItemType::mvMouseDragHandler": - dpg.set_value(mh_drag, f"Mouse id: {data[0]}, Delta:{[data[1], data[2]]}") - - for handler in dpg.get_item_children("__demo_keyboard_handler", 1): - dpg.set_item_callback(handler, _event_handler) - - for handler in dpg.get_item_children("__demo_mouse_handler", 1): - dpg.set_item_callback(handler, _event_handler) - - with dpg.collapsing_header(label="Drag & Drop"): - - with dpg.tree_node(label="Help"): - - dpg.add_text("Adding a drag_payload to a widget makes it source.", bullet=True) - dpg.add_text("Adding a drop_callback to a widget makes it target.", bullet=True) - dpg.add_text("Compatibility is determined by the 'payload_type'.", bullet=True) - dpg.add_text("The 'payload_type' must be less than 32 characters.", bullet=True) - dpg.add_text("A 'drag_callback' can be used to notify a source during a DND event.", bullet=True) - dpg.add_text("A 'drag_payload' is a container. Its children are what is shown when dragging.", bullet=True) - - with dpg.tree_node(label="Simple"): - - with dpg.group(horizontal=True, xoffset=200): - with dpg.group(): - - dpg.add_text("Int Sources:") - - dpg.add_button(label="Source 1: 25") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=25, payload_type="ints"): - dpg.add_text("25") - - dpg.add_button(label="Source 2: 33") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=33, payload_type="ints"): - dpg.add_text("33") - - dpg.add_button(label="Source 3: 111") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=111, payload_type="ints"): - dpg.add_text("111") - - with dpg.group(): - - dpg.add_text("Float Sources:") - dpg.add_button(label="Source 1: 43.7") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=43.7, payload_type="floats"): - dpg.add_text("43.7") - - dpg.add_button(label="Source 2: 99.8") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=99.8, payload_type="floats"): - dpg.add_text("99.8") - - dpg.add_button(label="Source 3: -23.4") - with dpg.drag_payload(parent=dpg.last_item(), drag_data=-23.4, payload_type="floats"): - dpg.add_text("-23.4") - - with dpg.group(): - - dpg.add_text("Targets:") - - dpg.add_input_int(label="Int Target", payload_type="ints", width=100, step=0, drop_callback=lambda s, a: dpg.set_value(s, a)) - dpg.add_input_float(label="Float Target", payload_type="floats", width=100, step=0, drop_callback=lambda s, a: dpg.set_value(s, a)) - - with dpg.collapsing_header(label="Advanced"): - - with dpg.tree_node(label="Help (READ ME FIRST)"): - dpg.add_text("These topics are for advanced users.", bullet=True) - dpg.add_text("Make sure you know what you are doing.", bullet=True) #Can we remove this? - - with dpg.tree_node(label="Staging"): - - dpg.add_text("Staging can be used to create items without traditional parents.", bullet=True) - dpg.add_text("A stage is a root container that will not attempt to render its children.", bullet=True) - dpg.add_text("Regular parent deduction rules still apply.", bullet=True) - dpg.add_text("Staging can be useful for wrapping a set of items.", bullet=True) - dpg.add_text("You can use most DPG commands on staged items.", bullet=True) - dpg.add_text("You can place any item into a stage.", bullet=True) - dpg.add_text("Items can be unstaged with 'move_item' and 'unstage'.", bullet=True) - dpg.add_text("'unstage' will also delete the stage.", bullet=True) - dpg.add_text("A 'stage is a special container that when used with `unstage` will delete itself.", bullet=True) - - def _unstage_items(sender, app_data, user_data): - - # push the child back onto the container stack - dpg.push_container_stack(user_data[1]) - - # this will 'unpack' the staging container (regular parent deduction rules apply) - dpg.unstage(user_data[0]) - - # pop the child back off the container stack - dpg.pop_container_stack() - - # when unstaging a stage, it 'unpacks' itself - with dpg.stage(tag="__demo_stage1"): - dpg.add_button(label="Staged Button 1") - dpg.add_button(label="Staged Button 2") - dpg.add_button(label="Staged Button 3") - - ub1 = dpg.add_button(label="Unstage buttons", callback=_unstage_items) - child_id = dpg.add_child_window(height=200, width=200) - dpg.set_item_user_data(ub1, ["__demo_stage1", child_id]) - - with dpg.tree_node(label="Manual Mutex Control"): - - dpg.add_text("DPG has a 'rendering' thread and a 'callback' thread.", bullet=True) - dpg.add_text("Only 1 thread can hold the mutex.", bullet=True) - dpg.add_text("The rendering thread grabs the mutex right before drawing.", bullet=True) - dpg.add_text("The callback thread grabs the mutex when you call a DPG command.", bullet=True) - dpg.add_text("If a callback calls multiple DPG commands, they will most likely execute over a few frames.", bullet=True) - dpg.add_text("To ensure multiple commands run within the same frame, you can lock/unlock the mutex manually.", bullet=True) - - staged_container = dpg.generate_uuid() - - def _callback_auto_mutex(sender, app_data, user_data): - - for i in range(100): - dpg.add_text("Item: " + str(i), parent=user_data) - - def _callback_manual_mutex(sender, app_data, user_data): - - dpg.lock_mutex() # you could also use with dpg.mutex() - dpg.push_container_stack(dpg.add_stage(id=staged_container)) - for i in range(100): - dpg.add_text("Item: " + str(i)) - dpg.pop_container_stack() - dpg.unlock_mutex() - - dpg.set_item_children(user_data, staged_container, 1) - - with dpg.group(horizontal=True): - b1 = dpg.add_button(label="Add 100 items") - b2 = dpg.add_button(label="Add 100 items (mutex)") - b3 = dpg.add_button(label="Delete Items", callback=lambda s, a, u: dpg.delete_item(u, children_only=True)) - dpg.add_child_window(height=500, width=-1) - dpg.configure_item(b1, user_data=dpg.last_item(), callback=_callback_auto_mutex) - dpg.configure_item(b2, user_data=dpg.last_item(), callback=_callback_manual_mutex) - dpg.configure_item(b3, user_data=dpg.last_item()) - if dpg.get_platform() == dpg.mvPlatform_Windows or dpg.get_platform() == dpg.mvPlatform_Linux: - with dpg.tree_node(label="Output Framebuffer"): - def _framebuffer_callback(sender, app_data): - dpg.show_item("__demo_texture_container") - dpg.add_dynamic_texture(app_data.get_width(), app_data.get_height(), app_data, parent="__demo_texture_container") - dpg.add_text("Outputs frame buffer an mvBuffer object, creates a dynamic texture, and shows the texture registry (check final item)") - dpg.add_button(label="Output Framebuffer", callback=lambda:dpg.output_frame_buffer(callback=_framebuffer_callback)) - - -if __name__ == '__main__': - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=600, height=600) - - show_demo() - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/dearpygui/experimental.py b/dearpygui/experimental.py deleted file mode 100644 index f10f31955..000000000 --- a/dearpygui/experimental.py +++ /dev/null @@ -1,9 +0,0 @@ -########################################################## -# Dear PyGui User Interface - Experimental -########################################################## - -import dearpygui.dearpygui as dpg -import dearpygui._dearpygui as internal_dpg - -def test_function(): - print("test function ran") diff --git a/dearpygui/type_info.py b/dearpygui/type_info.py deleted file mode 100644 index acd5a85bd..000000000 --- a/dearpygui/type_info.py +++ /dev/null @@ -1,1419 +0,0 @@ - -########################################################## -# Dear PyGui User Interface -# ~ Version: master -# -# Notes: -# * This file is automatically generated. -# -# Resources: -# * FAQ: https://github.com/hoffstadt/DearPyGui/discussions/categories/frequently-asked-questions-faq -# * Homepage: https://github.com/hoffstadt/DearPyGui -# * Wiki: https://github.com/hoffstadt/DearPyGui/wiki -# * Issues: https://github.com/hoffstadt/DearPyGui/issues -# * Discussions: https://github.com/hoffstadt/DearPyGui/discussions -########################################################## - -def get_all_types(**kwargs) -> list: - """ Return names of all item types as a list.""" - - return [ - "mvAppItemType::mvInputText", - "mvAppItemType::mvButton", - "mvAppItemType::mvRadioButton", - "mvAppItemType::mvTabBar", - "mvAppItemType::mvTab", - "mvAppItemType::mvImage", - "mvAppItemType::mvMenuBar", - "mvAppItemType::mvViewportMenuBar", - "mvAppItemType::mvMenu", - "mvAppItemType::mvMenuItem", - "mvAppItemType::mvChildWindow", - "mvAppItemType::mvGroup", - "mvAppItemType::mvSliderFloat", - "mvAppItemType::mvSliderInt", - "mvAppItemType::mvFilterSet", - "mvAppItemType::mvDragFloat", - "mvAppItemType::mvDragInt", - "mvAppItemType::mvInputFloat", - "mvAppItemType::mvInputInt", - "mvAppItemType::mvColorEdit", - "mvAppItemType::mvClipper", - "mvAppItemType::mvColorPicker", - "mvAppItemType::mvTooltip", - "mvAppItemType::mvCollapsingHeader", - "mvAppItemType::mvSeparator", - "mvAppItemType::mvCheckbox", - "mvAppItemType::mvListbox", - "mvAppItemType::mvText", - "mvAppItemType::mvCombo", - "mvAppItemType::mvPlot", - "mvAppItemType::mvSimplePlot", - "mvAppItemType::mvDrawlist", - "mvAppItemType::mvWindowAppItem", - "mvAppItemType::mvSelectable", - "mvAppItemType::mvTreeNode", - "mvAppItemType::mvProgressBar", - "mvAppItemType::mvSpacer", - "mvAppItemType::mvImageButton", - "mvAppItemType::mvTimePicker", - "mvAppItemType::mvDatePicker", - "mvAppItemType::mvColorButton", - "mvAppItemType::mvFileDialog", - "mvAppItemType::mvTabButton", - "mvAppItemType::mvDrawNode", - "mvAppItemType::mvNodeEditor", - "mvAppItemType::mvNode", - "mvAppItemType::mvNodeAttribute", - "mvAppItemType::mvTable", - "mvAppItemType::mvTableColumn", - "mvAppItemType::mvTableRow", - "mvAppItemType::mvSyncedTables", - "mvAppItemType::mvDrawLine", - "mvAppItemType::mvDrawArrow", - "mvAppItemType::mvDrawTriangle", - "mvAppItemType::mvDrawImageQuad", - "mvAppItemType::mvDrawCircle", - "mvAppItemType::mvDrawEllipse", - "mvAppItemType::mvDrawBezierCubic", - "mvAppItemType::mvDrawBezierQuadratic", - "mvAppItemType::mvDrawQuad", - "mvAppItemType::mvDrawRect", - "mvAppItemType::mvDrawText", - "mvAppItemType::mvDrawPolygon", - "mvAppItemType::mvDrawPolyline", - "mvAppItemType::mvDrawImage", - "mvAppItemType::mvDragFloatMulti", - "mvAppItemType::mvDragIntMulti", - "mvAppItemType::mvSliderFloatMulti", - "mvAppItemType::mvSliderIntMulti", - "mvAppItemType::mvInputIntMulti", - "mvAppItemType::mvInputFloatMulti", - "mvAppItemType::mvDragPoint", - "mvAppItemType::mvDragLine", - "mvAppItemType::mvDragRect", - "mvAppItemType::mvAnnotation", - "mvAppItemType::mvAxisTag", - "mvAppItemType::mvLineSeries", - "mvAppItemType::mvScatterSeries", - "mvAppItemType::mvStemSeries", - "mvAppItemType::mvStairSeries", - "mvAppItemType::mvBarSeries", - "mvAppItemType::mvBarGroupSeries", - "mvAppItemType::mvErrorSeries", - "mvAppItemType::mvInfLineSeries", - "mvAppItemType::mvHeatSeries", - "mvAppItemType::mvImageSeries", - "mvAppItemType::mvPieSeries", - "mvAppItemType::mvShadeSeries", - "mvAppItemType::mvLabelSeries", - "mvAppItemType::mvHistogramSeries", - "mvAppItemType::mvDigitalSeries", - "mvAppItemType::mv2dHistogramSeries", - "mvAppItemType::mvCandleSeries", - "mvAppItemType::mvAreaSeries", - "mvAppItemType::mvColorMapScale", - "mvAppItemType::mvSlider3D", - "mvAppItemType::mvKnobFloat", - "mvAppItemType::mvLoadingIndicator", - "mvAppItemType::mvNodeLink", - "mvAppItemType::mvTextureRegistry", - "mvAppItemType::mvStaticTexture", - "mvAppItemType::mvDynamicTexture", - "mvAppItemType::mvStage", - "mvAppItemType::mvDrawLayer", - "mvAppItemType::mvViewportDrawlist", - "mvAppItemType::mvFileExtension", - "mvAppItemType::mvPlotLegend", - "mvAppItemType::mvPlotAxis", - "mvAppItemType::mvHandlerRegistry", - "mvAppItemType::mvKeyDownHandler", - "mvAppItemType::mvKeyPressHandler", - "mvAppItemType::mvKeyReleaseHandler", - "mvAppItemType::mvMouseMoveHandler", - "mvAppItemType::mvMouseWheelHandler", - "mvAppItemType::mvMouseClickHandler", - "mvAppItemType::mvMouseDoubleClickHandler", - "mvAppItemType::mvMouseDownHandler", - "mvAppItemType::mvMouseReleaseHandler", - "mvAppItemType::mvMouseDragHandler", - "mvAppItemType::mvHoverHandler", - "mvAppItemType::mvActiveHandler", - "mvAppItemType::mvFocusHandler", - "mvAppItemType::mvVisibleHandler", - "mvAppItemType::mvEditedHandler", - "mvAppItemType::mvActivatedHandler", - "mvAppItemType::mvDeactivatedHandler", - "mvAppItemType::mvDeactivatedAfterEditHandler", - "mvAppItemType::mvToggledOpenHandler", - "mvAppItemType::mvClickedHandler", - "mvAppItemType::mvDoubleClickedHandler", - "mvAppItemType::mvScrollHandler", - "mvAppItemType::mvDragPayload", - "mvAppItemType::mvResizeHandler", - "mvAppItemType::mvFont", - "mvAppItemType::mvFontRegistry", - "mvAppItemType::mvTheme", - "mvAppItemType::mvThemeColor", - "mvAppItemType::mvThemeStyle", - "mvAppItemType::mvThemeComponent", - "mvAppItemType::mvCharRemap", - "mvAppItemType::mvValueRegistry", - "mvAppItemType::mvIntValue", - "mvAppItemType::mvFloatValue", - "mvAppItemType::mvFloat4Value", - "mvAppItemType::mvInt4Value", - "mvAppItemType::mvBoolValue", - "mvAppItemType::mvStringValue", - "mvAppItemType::mvDoubleValue", - "mvAppItemType::mvDouble4Value", - "mvAppItemType::mvColorValue", - "mvAppItemType::mvFloatVectValue", - "mvAppItemType::mvSeriesValue", - "mvAppItemType::mvRawTexture", - "mvAppItemType::mvSubPlots", - "mvAppItemType::mvColorMap", - "mvAppItemType::mvColorMapRegistry", - "mvAppItemType::mvColorMapButton", - "mvAppItemType::mvColorMapSlider", - "mvAppItemType::mvTemplateRegistry", - "mvAppItemType::mvTableCell", - "mvAppItemType::mvItemHandlerRegistry", - "mvAppItemType::mvInputDouble", - "mvAppItemType::mvInputDoubleMulti", - "mvAppItemType::mvDragDouble", - "mvAppItemType::mvDragDoubleMulti", - "mvAppItemType::mvSliderDouble", - "mvAppItemType::mvSliderDoubleMulti", - "mvAppItemType::mvCustomSeries", - ] - -def get_allowed_parents(distinct_allow_all: bool = False, **kwargs) -> dict: - """ Return all item type names and collections of applicable parenting types as a mapping. - - This function returns a set of rules defined within Dear PyGui. At runtime, these rules get combined with those from `get_allowed_children()`, and what is allowed here might be disabled there. To get the actual possible combinations of chilren and parent types, see `get_possible_parents()` and `get_possible_children()`. - - Args: - distinct_allow_all (bool): If set to True, entries for the items accepted by any parent will be set to None. This allows to detect and handle such cases specially if needed. If False, all item types will be listed explicitly in such entries, which allows more straightforward processing of the dict. - Returns: - dict - """ - - all_types = None if distinct_allow_all else tuple(get_all_types()) - - return { - "mvAppItemType::mvInputText": all_types, - "mvAppItemType::mvButton": all_types, - "mvAppItemType::mvRadioButton": all_types, - "mvAppItemType::mvTabBar": all_types, - "mvAppItemType::mvTab": ("mvAppItemType::mvTabBar", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvImage": all_types, - "mvAppItemType::mvMenuBar": ("mvAppItemType::mvWindowAppItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvViewportMenuBar": all_types, - "mvAppItemType::mvMenu": all_types, - "mvAppItemType::mvMenuItem": all_types, - "mvAppItemType::mvChildWindow": all_types, - "mvAppItemType::mvGroup": all_types, - "mvAppItemType::mvSliderFloat": all_types, - "mvAppItemType::mvSliderInt": all_types, - "mvAppItemType::mvFilterSet": all_types, - "mvAppItemType::mvDragFloat": all_types, - "mvAppItemType::mvDragInt": all_types, - "mvAppItemType::mvInputFloat": all_types, - "mvAppItemType::mvInputInt": all_types, - "mvAppItemType::mvColorEdit": all_types, - "mvAppItemType::mvClipper": all_types, - "mvAppItemType::mvColorPicker": all_types, - "mvAppItemType::mvTooltip": all_types, - "mvAppItemType::mvCollapsingHeader": all_types, - "mvAppItemType::mvSeparator": all_types, - "mvAppItemType::mvCheckbox": all_types, - "mvAppItemType::mvListbox": all_types, - "mvAppItemType::mvText": all_types, - "mvAppItemType::mvCombo": all_types, - "mvAppItemType::mvPlot": all_types, - "mvAppItemType::mvSimplePlot": all_types, - "mvAppItemType::mvDrawlist": all_types, - "mvAppItemType::mvWindowAppItem": all_types, - "mvAppItemType::mvSelectable": all_types, - "mvAppItemType::mvTreeNode": all_types, - "mvAppItemType::mvProgressBar": all_types, - "mvAppItemType::mvSpacer": all_types, - "mvAppItemType::mvImageButton": all_types, - "mvAppItemType::mvTimePicker": all_types, - "mvAppItemType::mvDatePicker": all_types, - "mvAppItemType::mvColorButton": all_types, - "mvAppItemType::mvFileDialog": all_types, - "mvAppItemType::mvTabButton": ("mvAppItemType::mvTabBar", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvDrawNode": ("mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvNodeEditor": all_types, - "mvAppItemType::mvNode": ("mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvNodeEditor", ), - "mvAppItemType::mvNodeAttribute": ("mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvNode", ), - "mvAppItemType::mvTable": all_types, - "mvAppItemType::mvTableColumn": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTable", ), - "mvAppItemType::mvTableRow": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTable", ), - "mvAppItemType::mvSyncedTables": all_types, - "mvAppItemType::mvDrawLine": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawArrow": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawTriangle": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawImageQuad": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawCircle": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawEllipse": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawBezierCubic": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawBezierQuadratic": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawQuad": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawRect": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawText": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawPolygon": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawPolyline": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDrawImage": ("mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvDrawNode", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ), - "mvAppItemType::mvDragFloatMulti": all_types, - "mvAppItemType::mvDragIntMulti": all_types, - "mvAppItemType::mvSliderFloatMulti": all_types, - "mvAppItemType::mvSliderIntMulti": all_types, - "mvAppItemType::mvInputIntMulti": all_types, - "mvAppItemType::mvInputFloatMulti": all_types, - "mvAppItemType::mvDragPoint": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvDragLine": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvDragRect": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvAnnotation": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvAxisTag": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvLineSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvScatterSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvStemSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvStairSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvBarSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvBarGroupSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvErrorSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvInfLineSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvHeatSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvImageSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvPieSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvShadeSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvLabelSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvHistogramSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvDigitalSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mv2dHistogramSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvCandleSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvAreaSeries": ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvColorMapScale": all_types, - "mvAppItemType::mvSlider3D": all_types, - "mvAppItemType::mvKnobFloat": all_types, - "mvAppItemType::mvLoadingIndicator": all_types, - "mvAppItemType::mvNodeLink": ("mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvNodeEditor", ), - "mvAppItemType::mvTextureRegistry": all_types, - "mvAppItemType::mvStaticTexture": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTextureRegistry", ), - "mvAppItemType::mvDynamicTexture": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTextureRegistry", ), - "mvAppItemType::mvStage": all_types, - "mvAppItemType::mvDrawLayer": ("mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvPlot", "mvAppItemType::mvViewportDrawlist", ), - "mvAppItemType::mvViewportDrawlist": all_types, - "mvAppItemType::mvFileExtension": ("mvAppItemType::mvStage", "mvAppItemType::mvFileDialog", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvPlotLegend": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", "mvAppItemType::mvSubPlots", ), - "mvAppItemType::mvPlotAxis": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvHandlerRegistry": all_types, - "mvAppItemType::mvKeyDownHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvKeyPressHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvKeyReleaseHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseMoveHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseWheelHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseClickHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseDoubleClickHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseDownHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseReleaseHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvMouseDragHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvHandlerRegistry", ), - "mvAppItemType::mvHoverHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvActiveHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvFocusHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvVisibleHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvEditedHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvActivatedHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvDeactivatedHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvDeactivatedAfterEditHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvToggledOpenHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvClickedHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvDoubleClickedHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvScrollHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvDragPayload": ("mvAppItemType::mvButton", "mvAppItemType::mvCheckbox", "mvAppItemType::mvCombo", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvDragInt", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragDouble", "mvAppItemType::mvImage", "mvAppItemType::mvImageButton", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvInputInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputText", "mvAppItemType::mvListbox", "mvAppItemType::mvMenuItem", "mvAppItemType::mvRadioButton", "mvAppItemType::mvSelectable", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvSliderInt", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvTabButton", "mvAppItemType::mvText", "mvAppItemType::mvColorButton", "mvAppItemType::mvColorEdit", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorPicker", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvGroup", "mvAppItemType::mvTreeNode", "mvAppItemType::mvDatePicker", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvSlider3D", "mvAppItemType::mvTimePicker", "mvAppItemType::mvProgressBar", "mvAppItemType::mvNode", "mvAppItemType::mvPlot", ), - "mvAppItemType::mvResizeHandler": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ), - "mvAppItemType::mvFont": ("mvAppItemType::mvFontRegistry", ), - "mvAppItemType::mvFontRegistry": all_types, - "mvAppItemType::mvTheme": all_types, - "mvAppItemType::mvThemeColor": ("mvAppItemType::mvThemeComponent", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvThemeStyle": ("mvAppItemType::mvThemeComponent", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvThemeComponent": ("mvAppItemType::mvTheme", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvCharRemap": ("mvAppItemType::mvFont", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvValueRegistry": all_types, - "mvAppItemType::mvIntValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvFloatValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvFloat4Value": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvInt4Value": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvBoolValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvStringValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvDoubleValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvDouble4Value": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvColorValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvFloatVectValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvSeriesValue": ("mvAppItemType::mvValueRegistry", ), - "mvAppItemType::mvRawTexture": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTextureRegistry", ), - "mvAppItemType::mvSubPlots": all_types, - "mvAppItemType::mvColorMap": ("mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvColorMapRegistry": all_types, - "mvAppItemType::mvColorMapButton": all_types, - "mvAppItemType::mvColorMapSlider": all_types, - "mvAppItemType::mvTemplateRegistry": all_types, - "mvAppItemType::mvTableCell": ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableRow", ), - "mvAppItemType::mvItemHandlerRegistry": all_types, - "mvAppItemType::mvInputDouble": all_types, - "mvAppItemType::mvInputDoubleMulti": all_types, - "mvAppItemType::mvDragDouble": all_types, - "mvAppItemType::mvDragDoubleMulti": all_types, - "mvAppItemType::mvSliderDouble": all_types, - "mvAppItemType::mvSliderDoubleMulti": all_types, - "mvAppItemType::mvCustomSeries": all_types, - } - -def get_allowed_children(distinct_allow_all: bool = False, **kwargs) -> dict: - """ Return all item type names and collections of applicable child types as a mapping. - - This function returns a set of rules defined within Dear PyGui. At runtime, these rules get combined with those from `get_allowed_parents()`, and what is allowed here might be disabled there. To get the actual possible combinations of chilren and parent types, see `get_possible_parents()` and `get_possible_children()`. - - Args: - distinct_allow_all (bool): If set to True, entries for the items accepting all children types will be set to None. This allows to detect and handle such cases specially if needed. If False, all item types will be listed explicitly in such entries, which allows more straightforward processing of the dict. - Returns: - dict - """ - - all_types = None if distinct_allow_all else tuple(get_all_types()) - - return { - "mvAppItemType::mvInputText": all_types, - "mvAppItemType::mvButton": all_types, - "mvAppItemType::mvRadioButton": all_types, - "mvAppItemType::mvTabBar": ("mvAppItemType::mvTab", "mvAppItemType::mvTabButton", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvVisibleHandler", ), - "mvAppItemType::mvTab": all_types, - "mvAppItemType::mvImage": all_types, - "mvAppItemType::mvMenuBar": all_types, - "mvAppItemType::mvViewportMenuBar": all_types, - "mvAppItemType::mvMenu": all_types, - "mvAppItemType::mvMenuItem": all_types, - "mvAppItemType::mvChildWindow": all_types, - "mvAppItemType::mvGroup": all_types, - "mvAppItemType::mvSliderFloat": all_types, - "mvAppItemType::mvSliderInt": all_types, - "mvAppItemType::mvFilterSet": all_types, - "mvAppItemType::mvDragFloat": all_types, - "mvAppItemType::mvDragInt": all_types, - "mvAppItemType::mvInputFloat": all_types, - "mvAppItemType::mvInputInt": all_types, - "mvAppItemType::mvColorEdit": all_types, - "mvAppItemType::mvClipper": all_types, - "mvAppItemType::mvColorPicker": all_types, - "mvAppItemType::mvTooltip": all_types, - "mvAppItemType::mvCollapsingHeader": all_types, - "mvAppItemType::mvSeparator": all_types, - "mvAppItemType::mvCheckbox": all_types, - "mvAppItemType::mvListbox": all_types, - "mvAppItemType::mvText": all_types, - "mvAppItemType::mvCombo": all_types, - "mvAppItemType::mvPlot": ("mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPoint", "mvAppItemType::mvDragRect", "mvAppItemType::mvDragLine", "mvAppItemType::mvAnnotation", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvDragPayload", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvSimplePlot": all_types, - "mvAppItemType::mvDrawlist": ("mvAppItemType::mvDrawLayer", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvWindowAppItem": all_types, - "mvAppItemType::mvSelectable": all_types, - "mvAppItemType::mvTreeNode": all_types, - "mvAppItemType::mvProgressBar": all_types, - "mvAppItemType::mvSpacer": all_types, - "mvAppItemType::mvImageButton": all_types, - "mvAppItemType::mvTimePicker": all_types, - "mvAppItemType::mvDatePicker": all_types, - "mvAppItemType::mvColorButton": all_types, - "mvAppItemType::mvFileDialog": all_types, - "mvAppItemType::mvTabButton": all_types, - "mvAppItemType::mvDrawNode": ("mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvNodeEditor": ("mvAppItemType::mvMenuBar", "mvAppItemType::mvNode", "mvAppItemType::mvNodeLink", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvVisibleHandler", ), - "mvAppItemType::mvNode": ("mvAppItemType::mvNodeAttribute", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvDragPayload", ), - "mvAppItemType::mvNodeAttribute": all_types, - "mvAppItemType::mvTable": ("mvAppItemType::mvTooltip", "mvAppItemType::mvTableRow", "mvAppItemType::mvTableColumn", ), - "mvAppItemType::mvTableColumn": all_types, - "mvAppItemType::mvTableRow": all_types, - "mvAppItemType::mvSyncedTables": all_types, - "mvAppItemType::mvDrawLine": all_types, - "mvAppItemType::mvDrawArrow": all_types, - "mvAppItemType::mvDrawTriangle": all_types, - "mvAppItemType::mvDrawImageQuad": all_types, - "mvAppItemType::mvDrawCircle": all_types, - "mvAppItemType::mvDrawEllipse": all_types, - "mvAppItemType::mvDrawBezierCubic": all_types, - "mvAppItemType::mvDrawBezierQuadratic": all_types, - "mvAppItemType::mvDrawQuad": all_types, - "mvAppItemType::mvDrawRect": all_types, - "mvAppItemType::mvDrawText": all_types, - "mvAppItemType::mvDrawPolygon": all_types, - "mvAppItemType::mvDrawPolyline": all_types, - "mvAppItemType::mvDrawImage": all_types, - "mvAppItemType::mvDragFloatMulti": all_types, - "mvAppItemType::mvDragIntMulti": all_types, - "mvAppItemType::mvSliderFloatMulti": all_types, - "mvAppItemType::mvSliderIntMulti": all_types, - "mvAppItemType::mvInputIntMulti": all_types, - "mvAppItemType::mvInputFloatMulti": all_types, - "mvAppItemType::mvDragPoint": all_types, - "mvAppItemType::mvDragLine": all_types, - "mvAppItemType::mvDragRect": all_types, - "mvAppItemType::mvAnnotation": all_types, - "mvAppItemType::mvAxisTag": all_types, - "mvAppItemType::mvLineSeries": all_types, - "mvAppItemType::mvScatterSeries": all_types, - "mvAppItemType::mvStemSeries": all_types, - "mvAppItemType::mvStairSeries": all_types, - "mvAppItemType::mvBarSeries": all_types, - "mvAppItemType::mvBarGroupSeries": all_types, - "mvAppItemType::mvErrorSeries": all_types, - "mvAppItemType::mvInfLineSeries": all_types, - "mvAppItemType::mvHeatSeries": all_types, - "mvAppItemType::mvImageSeries": all_types, - "mvAppItemType::mvPieSeries": all_types, - "mvAppItemType::mvShadeSeries": all_types, - "mvAppItemType::mvLabelSeries": all_types, - "mvAppItemType::mvHistogramSeries": all_types, - "mvAppItemType::mvDigitalSeries": all_types, - "mvAppItemType::mv2dHistogramSeries": all_types, - "mvAppItemType::mvCandleSeries": all_types, - "mvAppItemType::mvAreaSeries": all_types, - "mvAppItemType::mvColorMapScale": all_types, - "mvAppItemType::mvSlider3D": all_types, - "mvAppItemType::mvKnobFloat": all_types, - "mvAppItemType::mvLoadingIndicator": all_types, - "mvAppItemType::mvNodeLink": all_types, - "mvAppItemType::mvTextureRegistry": ("mvAppItemType::mvStaticTexture", "mvAppItemType::mvDynamicTexture", "mvAppItemType::mvRawTexture", ), - "mvAppItemType::mvStaticTexture": all_types, - "mvAppItemType::mvDynamicTexture": all_types, - "mvAppItemType::mvStage": all_types, - "mvAppItemType::mvDrawLayer": ("mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvViewportDrawlist": ("mvAppItemType::mvDrawLayer", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawNode", ), - "mvAppItemType::mvFileExtension": all_types, - "mvAppItemType::mvPlotLegend": all_types, - "mvAppItemType::mvPlotAxis": all_types, - "mvAppItemType::mvHandlerRegistry": ("mvAppItemType::mvKeyDownHandler", "mvAppItemType::mvKeyPressHandler", "mvAppItemType::mvKeyReleaseHandler", "mvAppItemType::mvMouseMoveHandler", "mvAppItemType::mvMouseWheelHandler", "mvAppItemType::mvMouseClickHandler", "mvAppItemType::mvMouseDoubleClickHandler", "mvAppItemType::mvMouseDownHandler", "mvAppItemType::mvMouseReleaseHandler", "mvAppItemType::mvMouseDragHandler", ), - "mvAppItemType::mvKeyDownHandler": all_types, - "mvAppItemType::mvKeyPressHandler": all_types, - "mvAppItemType::mvKeyReleaseHandler": all_types, - "mvAppItemType::mvMouseMoveHandler": all_types, - "mvAppItemType::mvMouseWheelHandler": all_types, - "mvAppItemType::mvMouseClickHandler": all_types, - "mvAppItemType::mvMouseDoubleClickHandler": all_types, - "mvAppItemType::mvMouseDownHandler": all_types, - "mvAppItemType::mvMouseReleaseHandler": all_types, - "mvAppItemType::mvMouseDragHandler": all_types, - "mvAppItemType::mvHoverHandler": all_types, - "mvAppItemType::mvActiveHandler": all_types, - "mvAppItemType::mvFocusHandler": all_types, - "mvAppItemType::mvVisibleHandler": all_types, - "mvAppItemType::mvEditedHandler": all_types, - "mvAppItemType::mvActivatedHandler": all_types, - "mvAppItemType::mvDeactivatedHandler": all_types, - "mvAppItemType::mvDeactivatedAfterEditHandler": all_types, - "mvAppItemType::mvToggledOpenHandler": all_types, - "mvAppItemType::mvClickedHandler": all_types, - "mvAppItemType::mvDoubleClickedHandler": all_types, - "mvAppItemType::mvScrollHandler": all_types, - "mvAppItemType::mvDragPayload": all_types, - "mvAppItemType::mvResizeHandler": all_types, - "mvAppItemType::mvFont": ("mvAppItemType::mvCharRemap", "mvAppItemType::mvTemplateRegistry", ), - "mvAppItemType::mvFontRegistry": ("mvAppItemType::mvFont", ), - "mvAppItemType::mvTheme": ("mvAppItemType::mvThemeComponent", ), - "mvAppItemType::mvThemeColor": all_types, - "mvAppItemType::mvThemeStyle": all_types, - "mvAppItemType::mvThemeComponent": ("mvAppItemType::mvThemeColor", "mvAppItemType::mvThemeStyle", ), - "mvAppItemType::mvCharRemap": all_types, - "mvAppItemType::mvValueRegistry": ("mvAppItemType::mvBoolValue", "mvAppItemType::mvIntValue", "mvAppItemType::mvInt4Value", "mvAppItemType::mvFloatValue", "mvAppItemType::mvFloat4Value", "mvAppItemType::mvStringValue", "mvAppItemType::mvDoubleValue", "mvAppItemType::mvDouble4Value", "mvAppItemType::mvColorValue", "mvAppItemType::mvFloatVectValue", "mvAppItemType::mvSeriesValue", ), - "mvAppItemType::mvIntValue": all_types, - "mvAppItemType::mvFloatValue": all_types, - "mvAppItemType::mvFloat4Value": all_types, - "mvAppItemType::mvInt4Value": all_types, - "mvAppItemType::mvBoolValue": all_types, - "mvAppItemType::mvStringValue": all_types, - "mvAppItemType::mvDoubleValue": all_types, - "mvAppItemType::mvDouble4Value": all_types, - "mvAppItemType::mvColorValue": all_types, - "mvAppItemType::mvFloatVectValue": all_types, - "mvAppItemType::mvSeriesValue": all_types, - "mvAppItemType::mvRawTexture": all_types, - "mvAppItemType::mvSubPlots": ("mvAppItemType::mvPlot", "mvAppItemType::mvPlotLegend", ), - "mvAppItemType::mvColorMap": all_types, - "mvAppItemType::mvColorMapRegistry": ("mvAppItemType::mvColorMap", ), - "mvAppItemType::mvColorMapButton": all_types, - "mvAppItemType::mvColorMapSlider": all_types, - "mvAppItemType::mvTemplateRegistry": all_types, - "mvAppItemType::mvTableCell": all_types, - "mvAppItemType::mvItemHandlerRegistry": ("mvAppItemType::mvActivatedHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvScrollHandler", ), - "mvAppItemType::mvInputDouble": all_types, - "mvAppItemType::mvInputDoubleMulti": all_types, - "mvAppItemType::mvDragDouble": all_types, - "mvAppItemType::mvDragDoubleMulti": all_types, - "mvAppItemType::mvSliderDouble": all_types, - "mvAppItemType::mvSliderDoubleMulti": all_types, - "mvAppItemType::mvCustomSeries": all_types, - } - -def get_possible_parents(**kwargs) -> dict: - """ Return a dict that for every item type lists all types that can be used as a parent. - - Unlike `get_allowed_parents()`, this function returns the actual set of all possible parent-child relationthips that results from applying *both* `get_allowed_parents()` and `get_allowed_children()`, represented as a child-to-parents map. It also takes `is_container()` into account. - """ - - set0 = ("mvAppItemType::mvTab", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvFilterSet", "mvAppItemType::mvClipper", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvTreeNode", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvStage", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPayload", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvCustomSeries", ) - set1 = ("mvAppItemType::mvTabBar", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set2 = ("mvAppItemType::mvChildWindow", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set3 = ("mvAppItemType::mvTab", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvFilterSet", "mvAppItemType::mvClipper", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvTreeNode", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTable", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvStage", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPayload", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvCustomSeries", ) - set4 = ("mvAppItemType::mvTab", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvFilterSet", "mvAppItemType::mvClipper", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvTreeNode", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvStage", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPayload", "mvAppItemType::mvSubPlots", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvCustomSeries", ) - set5 = ("mvAppItemType::mvPlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvDrawNode", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", ) - set6 = ("mvAppItemType::mvNodeEditor", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set7 = ("mvAppItemType::mvNode", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set8 = ("mvAppItemType::mvTable", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set9 = ("mvAppItemType::mvPlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvDrawNode", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ) - set10 = ("mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvDrawNode", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvCustomSeries", ) - set11 = ("mvAppItemType::mvPlot", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set12 = ("mvAppItemType::mvPlotAxis", "mvAppItemType::mvTemplateRegistry", ) - set13 = ("mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set14 = ("mvAppItemType::mvPlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvTemplateRegistry", ) - set15 = ("mvAppItemType::mvFileDialog", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - set16 = ("mvAppItemType::mvPlot", "mvAppItemType::mvStage", "mvAppItemType::mvSubPlots", "mvAppItemType::mvTemplateRegistry", ) - set17 = ("mvAppItemType::mvStage", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvTemplateRegistry", ) - set18 = ("mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", ) - set19 = ("mvAppItemType::mvGroup", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvPlot", "mvAppItemType::mvTreeNode", "mvAppItemType::mvNode", ) - set20 = ("mvAppItemType::mvFontRegistry", ) - set21 = ("mvAppItemType::mvThemeComponent", "mvAppItemType::mvTemplateRegistry", ) - set22 = ("mvAppItemType::mvTheme", "mvAppItemType::mvTemplateRegistry", ) - set23 = ("mvAppItemType::mvFont", "mvAppItemType::mvTemplateRegistry", ) - set24 = ("mvAppItemType::mvValueRegistry", ) - set25 = ("mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvTemplateRegistry", ) - set26 = ("mvAppItemType::mvTab", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvFilterSet", "mvAppItemType::mvClipper", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvTreeNode", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvStage", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPayload", "mvAppItemType::mvFont", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvCustomSeries", ) - set27 = ("mvAppItemType::mvTableRow", "mvAppItemType::mvStage", "mvAppItemType::mvTemplateRegistry", ) - - return { - "mvAppItemType::mvInputText": set0, - "mvAppItemType::mvButton": set0, - "mvAppItemType::mvRadioButton": set0, - "mvAppItemType::mvTabBar": set0, - "mvAppItemType::mvTab": set1, - "mvAppItemType::mvImage": set0, - "mvAppItemType::mvMenuBar": set2, - "mvAppItemType::mvViewportMenuBar": set0, - "mvAppItemType::mvMenu": set0, - "mvAppItemType::mvMenuItem": set0, - "mvAppItemType::mvChildWindow": set0, - "mvAppItemType::mvGroup": set0, - "mvAppItemType::mvSliderFloat": set0, - "mvAppItemType::mvSliderInt": set0, - "mvAppItemType::mvFilterSet": set0, - "mvAppItemType::mvDragFloat": set0, - "mvAppItemType::mvDragInt": set0, - "mvAppItemType::mvInputFloat": set0, - "mvAppItemType::mvInputInt": set0, - "mvAppItemType::mvColorEdit": set0, - "mvAppItemType::mvClipper": set0, - "mvAppItemType::mvColorPicker": set0, - "mvAppItemType::mvTooltip": set3, - "mvAppItemType::mvCollapsingHeader": set0, - "mvAppItemType::mvSeparator": set0, - "mvAppItemType::mvCheckbox": set0, - "mvAppItemType::mvListbox": set0, - "mvAppItemType::mvText": set0, - "mvAppItemType::mvCombo": set0, - "mvAppItemType::mvPlot": set4, - "mvAppItemType::mvSimplePlot": set0, - "mvAppItemType::mvDrawlist": set0, - "mvAppItemType::mvWindowAppItem": set0, - "mvAppItemType::mvSelectable": set0, - "mvAppItemType::mvTreeNode": set0, - "mvAppItemType::mvProgressBar": set0, - "mvAppItemType::mvSpacer": set0, - "mvAppItemType::mvImageButton": set0, - "mvAppItemType::mvTimePicker": set0, - "mvAppItemType::mvDatePicker": set0, - "mvAppItemType::mvColorButton": set0, - "mvAppItemType::mvFileDialog": set0, - "mvAppItemType::mvTabButton": set1, - "mvAppItemType::mvDrawNode": set5, - "mvAppItemType::mvNodeEditor": set0, - "mvAppItemType::mvNode": set6, - "mvAppItemType::mvNodeAttribute": set7, - "mvAppItemType::mvTable": set0, - "mvAppItemType::mvTableColumn": set8, - "mvAppItemType::mvTableRow": set8, - "mvAppItemType::mvSyncedTables": set0, - "mvAppItemType::mvDrawLine": set9, - "mvAppItemType::mvDrawArrow": set9, - "mvAppItemType::mvDrawTriangle": set9, - "mvAppItemType::mvDrawImageQuad": set10, - "mvAppItemType::mvDrawCircle": set9, - "mvAppItemType::mvDrawEllipse": set9, - "mvAppItemType::mvDrawBezierCubic": set9, - "mvAppItemType::mvDrawBezierQuadratic": set9, - "mvAppItemType::mvDrawQuad": set9, - "mvAppItemType::mvDrawRect": set9, - "mvAppItemType::mvDrawText": set9, - "mvAppItemType::mvDrawPolygon": set9, - "mvAppItemType::mvDrawPolyline": set9, - "mvAppItemType::mvDrawImage": set9, - "mvAppItemType::mvDragFloatMulti": set0, - "mvAppItemType::mvDragIntMulti": set0, - "mvAppItemType::mvSliderFloatMulti": set0, - "mvAppItemType::mvSliderIntMulti": set0, - "mvAppItemType::mvInputIntMulti": set0, - "mvAppItemType::mvInputFloatMulti": set0, - "mvAppItemType::mvDragPoint": set11, - "mvAppItemType::mvDragLine": set11, - "mvAppItemType::mvDragRect": set11, - "mvAppItemType::mvAnnotation": set11, - "mvAppItemType::mvAxisTag": set12, - "mvAppItemType::mvLineSeries": set12, - "mvAppItemType::mvScatterSeries": set12, - "mvAppItemType::mvStemSeries": set12, - "mvAppItemType::mvStairSeries": set12, - "mvAppItemType::mvBarSeries": set12, - "mvAppItemType::mvBarGroupSeries": set12, - "mvAppItemType::mvErrorSeries": set12, - "mvAppItemType::mvInfLineSeries": set12, - "mvAppItemType::mvHeatSeries": set12, - "mvAppItemType::mvImageSeries": set12, - "mvAppItemType::mvPieSeries": set12, - "mvAppItemType::mvShadeSeries": set12, - "mvAppItemType::mvLabelSeries": set12, - "mvAppItemType::mvHistogramSeries": set12, - "mvAppItemType::mvDigitalSeries": set12, - "mvAppItemType::mv2dHistogramSeries": set12, - "mvAppItemType::mvCandleSeries": set12, - "mvAppItemType::mvAreaSeries": set12, - "mvAppItemType::mvColorMapScale": set0, - "mvAppItemType::mvSlider3D": set0, - "mvAppItemType::mvKnobFloat": set0, - "mvAppItemType::mvLoadingIndicator": set0, - "mvAppItemType::mvNodeLink": set6, - "mvAppItemType::mvTextureRegistry": set0, - "mvAppItemType::mvStaticTexture": set13, - "mvAppItemType::mvDynamicTexture": set13, - "mvAppItemType::mvStage": set0, - "mvAppItemType::mvDrawLayer": set14, - "mvAppItemType::mvViewportDrawlist": set0, - "mvAppItemType::mvFileExtension": set15, - "mvAppItemType::mvPlotLegend": set16, - "mvAppItemType::mvPlotAxis": set11, - "mvAppItemType::mvHandlerRegistry": set0, - "mvAppItemType::mvKeyDownHandler": set17, - "mvAppItemType::mvKeyPressHandler": set17, - "mvAppItemType::mvKeyReleaseHandler": set17, - "mvAppItemType::mvMouseMoveHandler": set17, - "mvAppItemType::mvMouseWheelHandler": set17, - "mvAppItemType::mvMouseClickHandler": set17, - "mvAppItemType::mvMouseDoubleClickHandler": set17, - "mvAppItemType::mvMouseDownHandler": set17, - "mvAppItemType::mvMouseReleaseHandler": set17, - "mvAppItemType::mvMouseDragHandler": set17, - "mvAppItemType::mvHoverHandler": set18, - "mvAppItemType::mvActiveHandler": set18, - "mvAppItemType::mvFocusHandler": set18, - "mvAppItemType::mvVisibleHandler": set18, - "mvAppItemType::mvEditedHandler": set18, - "mvAppItemType::mvActivatedHandler": set18, - "mvAppItemType::mvDeactivatedHandler": set18, - "mvAppItemType::mvDeactivatedAfterEditHandler": set18, - "mvAppItemType::mvToggledOpenHandler": set18, - "mvAppItemType::mvClickedHandler": set18, - "mvAppItemType::mvDoubleClickedHandler": set18, - "mvAppItemType::mvScrollHandler": set18, - "mvAppItemType::mvDragPayload": set19, - "mvAppItemType::mvResizeHandler": set18, - "mvAppItemType::mvFont": set20, - "mvAppItemType::mvFontRegistry": set0, - "mvAppItemType::mvTheme": set0, - "mvAppItemType::mvThemeColor": set21, - "mvAppItemType::mvThemeStyle": set21, - "mvAppItemType::mvThemeComponent": set22, - "mvAppItemType::mvCharRemap": set23, - "mvAppItemType::mvValueRegistry": set0, - "mvAppItemType::mvIntValue": set24, - "mvAppItemType::mvFloatValue": set24, - "mvAppItemType::mvFloat4Value": set24, - "mvAppItemType::mvInt4Value": set24, - "mvAppItemType::mvBoolValue": set24, - "mvAppItemType::mvStringValue": set24, - "mvAppItemType::mvDoubleValue": set24, - "mvAppItemType::mvDouble4Value": set24, - "mvAppItemType::mvColorValue": set24, - "mvAppItemType::mvFloatVectValue": set24, - "mvAppItemType::mvSeriesValue": set24, - "mvAppItemType::mvRawTexture": set13, - "mvAppItemType::mvSubPlots": set0, - "mvAppItemType::mvColorMap": set25, - "mvAppItemType::mvColorMapRegistry": set0, - "mvAppItemType::mvColorMapButton": set0, - "mvAppItemType::mvColorMapSlider": set0, - "mvAppItemType::mvTemplateRegistry": set26, - "mvAppItemType::mvTableCell": set27, - "mvAppItemType::mvItemHandlerRegistry": set0, - "mvAppItemType::mvInputDouble": set0, - "mvAppItemType::mvInputDoubleMulti": set0, - "mvAppItemType::mvDragDouble": set0, - "mvAppItemType::mvDragDoubleMulti": set0, - "mvAppItemType::mvSliderDouble": set0, - "mvAppItemType::mvSliderDoubleMulti": set0, - "mvAppItemType::mvCustomSeries": set0, - } - -def get_possible_children(**kwargs) -> dict: - """ Return a dict that for every item type lists all types that can be used for a child item. - - Unlike `get_allowed_children()`, this function returns the actual set of all possible parent-child relationthips that results from applying *both* `get_allowed_parents()` and `get_allowed_children()`, represented as a parent-to-children map. It also takes `is_container()` into account. - """ - - set0 = () - set1 = ("mvAppItemType::mvTab", "mvAppItemType::mvTabButton", ) - set2 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set3 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set4 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvDragPayload", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set5 = ("mvAppItemType::mvDrawNode", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDragPoint", "mvAppItemType::mvDragLine", "mvAppItemType::mvDragRect", "mvAppItemType::mvAnnotation", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvDragPayload", ) - set6 = ("mvAppItemType::mvDrawNode", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDrawLayer", ) - set7 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvDrawNode", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set8 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvFileExtension", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set9 = ("mvAppItemType::mvDrawNode", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", ) - set10 = ("mvAppItemType::mvMenuBar", "mvAppItemType::mvNode", "mvAppItemType::mvNodeLink", ) - set11 = ("mvAppItemType::mvNodeAttribute", "mvAppItemType::mvDragPayload", ) - set12 = ("mvAppItemType::mvTooltip", "mvAppItemType::mvTableColumn", "mvAppItemType::mvTableRow", ) - set13 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set14 = ("mvAppItemType::mvStaticTexture", "mvAppItemType::mvDynamicTexture", "mvAppItemType::mvRawTexture", ) - set15 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvTab", "mvAppItemType::mvImage", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvTabButton", "mvAppItemType::mvDrawNode", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvNode", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTable", "mvAppItemType::mvTableColumn", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvDragPoint", "mvAppItemType::mvDragLine", "mvAppItemType::mvDragRect", "mvAppItemType::mvAnnotation", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvNodeLink", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStaticTexture", "mvAppItemType::mvDynamicTexture", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvFileExtension", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvKeyDownHandler", "mvAppItemType::mvKeyPressHandler", "mvAppItemType::mvKeyReleaseHandler", "mvAppItemType::mvMouseMoveHandler", "mvAppItemType::mvMouseWheelHandler", "mvAppItemType::mvMouseClickHandler", "mvAppItemType::mvMouseDoubleClickHandler", "mvAppItemType::mvMouseDownHandler", "mvAppItemType::mvMouseReleaseHandler", "mvAppItemType::mvMouseDragHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvScrollHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvRawTexture", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set16 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvAxisTag", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set17 = ("mvAppItemType::mvKeyDownHandler", "mvAppItemType::mvKeyPressHandler", "mvAppItemType::mvKeyReleaseHandler", "mvAppItemType::mvMouseMoveHandler", "mvAppItemType::mvMouseWheelHandler", "mvAppItemType::mvMouseClickHandler", "mvAppItemType::mvMouseDoubleClickHandler", "mvAppItemType::mvMouseDownHandler", "mvAppItemType::mvMouseReleaseHandler", "mvAppItemType::mvMouseDragHandler", ) - set18 = ("mvAppItemType::mvCharRemap", "mvAppItemType::mvTemplateRegistry", ) - set19 = ("mvAppItemType::mvFont", ) - set20 = ("mvAppItemType::mvThemeComponent", ) - set21 = ("mvAppItemType::mvThemeColor", "mvAppItemType::mvThemeStyle", ) - set22 = ("mvAppItemType::mvIntValue", "mvAppItemType::mvFloatValue", "mvAppItemType::mvFloat4Value", "mvAppItemType::mvInt4Value", "mvAppItemType::mvBoolValue", "mvAppItemType::mvStringValue", "mvAppItemType::mvDoubleValue", "mvAppItemType::mvDouble4Value", "mvAppItemType::mvColorValue", "mvAppItemType::mvFloatVectValue", "mvAppItemType::mvSeriesValue", ) - set23 = ("mvAppItemType::mvPlot", "mvAppItemType::mvPlotLegend", ) - set24 = ("mvAppItemType::mvColorMap", ) - set25 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvTab", "mvAppItemType::mvImage", "mvAppItemType::mvMenuBar", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvTabButton", "mvAppItemType::mvDrawNode", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvNode", "mvAppItemType::mvNodeAttribute", "mvAppItemType::mvTable", "mvAppItemType::mvTableColumn", "mvAppItemType::mvTableRow", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvDragPoint", "mvAppItemType::mvDragLine", "mvAppItemType::mvDragRect", "mvAppItemType::mvAnnotation", "mvAppItemType::mvAxisTag", "mvAppItemType::mvLineSeries", "mvAppItemType::mvScatterSeries", "mvAppItemType::mvStemSeries", "mvAppItemType::mvStairSeries", "mvAppItemType::mvBarSeries", "mvAppItemType::mvBarGroupSeries", "mvAppItemType::mvErrorSeries", "mvAppItemType::mvInfLineSeries", "mvAppItemType::mvHeatSeries", "mvAppItemType::mvImageSeries", "mvAppItemType::mvPieSeries", "mvAppItemType::mvShadeSeries", "mvAppItemType::mvLabelSeries", "mvAppItemType::mvHistogramSeries", "mvAppItemType::mvDigitalSeries", "mvAppItemType::mv2dHistogramSeries", "mvAppItemType::mvCandleSeries", "mvAppItemType::mvAreaSeries", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvNodeLink", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStaticTexture", "mvAppItemType::mvDynamicTexture", "mvAppItemType::mvStage", "mvAppItemType::mvDrawLayer", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvFileExtension", "mvAppItemType::mvPlotLegend", "mvAppItemType::mvPlotAxis", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvKeyDownHandler", "mvAppItemType::mvKeyPressHandler", "mvAppItemType::mvKeyReleaseHandler", "mvAppItemType::mvMouseMoveHandler", "mvAppItemType::mvMouseWheelHandler", "mvAppItemType::mvMouseClickHandler", "mvAppItemType::mvMouseDoubleClickHandler", "mvAppItemType::mvMouseDownHandler", "mvAppItemType::mvMouseReleaseHandler", "mvAppItemType::mvMouseDragHandler", "mvAppItemType::mvHoverHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvScrollHandler", "mvAppItemType::mvResizeHandler", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvThemeColor", "mvAppItemType::mvThemeStyle", "mvAppItemType::mvThemeComponent", "mvAppItemType::mvCharRemap", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvRawTexture", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMap", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvTableCell", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - set26 = ("mvAppItemType::mvHoverHandler", "mvAppItemType::mvActiveHandler", "mvAppItemType::mvFocusHandler", "mvAppItemType::mvVisibleHandler", "mvAppItemType::mvEditedHandler", "mvAppItemType::mvActivatedHandler", "mvAppItemType::mvDeactivatedHandler", "mvAppItemType::mvDeactivatedAfterEditHandler", "mvAppItemType::mvToggledOpenHandler", "mvAppItemType::mvClickedHandler", "mvAppItemType::mvDoubleClickedHandler", "mvAppItemType::mvScrollHandler", "mvAppItemType::mvResizeHandler", ) - set27 = ("mvAppItemType::mvInputText", "mvAppItemType::mvButton", "mvAppItemType::mvRadioButton", "mvAppItemType::mvTabBar", "mvAppItemType::mvImage", "mvAppItemType::mvViewportMenuBar", "mvAppItemType::mvMenu", "mvAppItemType::mvMenuItem", "mvAppItemType::mvChildWindow", "mvAppItemType::mvGroup", "mvAppItemType::mvSliderFloat", "mvAppItemType::mvSliderInt", "mvAppItemType::mvFilterSet", "mvAppItemType::mvDragFloat", "mvAppItemType::mvDragInt", "mvAppItemType::mvInputFloat", "mvAppItemType::mvInputInt", "mvAppItemType::mvColorEdit", "mvAppItemType::mvClipper", "mvAppItemType::mvColorPicker", "mvAppItemType::mvTooltip", "mvAppItemType::mvCollapsingHeader", "mvAppItemType::mvSeparator", "mvAppItemType::mvCheckbox", "mvAppItemType::mvListbox", "mvAppItemType::mvText", "mvAppItemType::mvCombo", "mvAppItemType::mvPlot", "mvAppItemType::mvSimplePlot", "mvAppItemType::mvDrawlist", "mvAppItemType::mvWindowAppItem", "mvAppItemType::mvSelectable", "mvAppItemType::mvTreeNode", "mvAppItemType::mvProgressBar", "mvAppItemType::mvSpacer", "mvAppItemType::mvImageButton", "mvAppItemType::mvTimePicker", "mvAppItemType::mvDatePicker", "mvAppItemType::mvColorButton", "mvAppItemType::mvFileDialog", "mvAppItemType::mvNodeEditor", "mvAppItemType::mvTable", "mvAppItemType::mvSyncedTables", "mvAppItemType::mvDrawLine", "mvAppItemType::mvDrawArrow", "mvAppItemType::mvDrawTriangle", "mvAppItemType::mvDrawImageQuad", "mvAppItemType::mvDrawCircle", "mvAppItemType::mvDrawEllipse", "mvAppItemType::mvDrawBezierCubic", "mvAppItemType::mvDrawBezierQuadratic", "mvAppItemType::mvDrawQuad", "mvAppItemType::mvDrawRect", "mvAppItemType::mvDrawText", "mvAppItemType::mvDrawPolygon", "mvAppItemType::mvDrawPolyline", "mvAppItemType::mvDrawImage", "mvAppItemType::mvDragFloatMulti", "mvAppItemType::mvDragIntMulti", "mvAppItemType::mvSliderFloatMulti", "mvAppItemType::mvSliderIntMulti", "mvAppItemType::mvInputIntMulti", "mvAppItemType::mvInputFloatMulti", "mvAppItemType::mvColorMapScale", "mvAppItemType::mvSlider3D", "mvAppItemType::mvKnobFloat", "mvAppItemType::mvLoadingIndicator", "mvAppItemType::mvTextureRegistry", "mvAppItemType::mvStage", "mvAppItemType::mvViewportDrawlist", "mvAppItemType::mvHandlerRegistry", "mvAppItemType::mvFontRegistry", "mvAppItemType::mvTheme", "mvAppItemType::mvValueRegistry", "mvAppItemType::mvSubPlots", "mvAppItemType::mvColorMapRegistry", "mvAppItemType::mvColorMapButton", "mvAppItemType::mvColorMapSlider", "mvAppItemType::mvTemplateRegistry", "mvAppItemType::mvItemHandlerRegistry", "mvAppItemType::mvInputDouble", "mvAppItemType::mvInputDoubleMulti", "mvAppItemType::mvDragDouble", "mvAppItemType::mvDragDoubleMulti", "mvAppItemType::mvSliderDouble", "mvAppItemType::mvSliderDoubleMulti", "mvAppItemType::mvCustomSeries", ) - - return { - "mvAppItemType::mvInputText": set0, - "mvAppItemType::mvButton": set0, - "mvAppItemType::mvRadioButton": set0, - "mvAppItemType::mvTabBar": set1, - "mvAppItemType::mvTab": set2, - "mvAppItemType::mvImage": set0, - "mvAppItemType::mvMenuBar": set2, - "mvAppItemType::mvViewportMenuBar": set2, - "mvAppItemType::mvMenu": set2, - "mvAppItemType::mvMenuItem": set0, - "mvAppItemType::mvChildWindow": set3, - "mvAppItemType::mvGroup": set4, - "mvAppItemType::mvSliderFloat": set0, - "mvAppItemType::mvSliderInt": set0, - "mvAppItemType::mvFilterSet": set2, - "mvAppItemType::mvDragFloat": set0, - "mvAppItemType::mvDragInt": set0, - "mvAppItemType::mvInputFloat": set0, - "mvAppItemType::mvInputInt": set0, - "mvAppItemType::mvColorEdit": set0, - "mvAppItemType::mvClipper": set2, - "mvAppItemType::mvColorPicker": set0, - "mvAppItemType::mvTooltip": set2, - "mvAppItemType::mvCollapsingHeader": set4, - "mvAppItemType::mvSeparator": set0, - "mvAppItemType::mvCheckbox": set0, - "mvAppItemType::mvListbox": set0, - "mvAppItemType::mvText": set0, - "mvAppItemType::mvCombo": set0, - "mvAppItemType::mvPlot": set5, - "mvAppItemType::mvSimplePlot": set0, - "mvAppItemType::mvDrawlist": set6, - "mvAppItemType::mvWindowAppItem": set7, - "mvAppItemType::mvSelectable": set0, - "mvAppItemType::mvTreeNode": set4, - "mvAppItemType::mvProgressBar": set0, - "mvAppItemType::mvSpacer": set0, - "mvAppItemType::mvImageButton": set0, - "mvAppItemType::mvTimePicker": set0, - "mvAppItemType::mvDatePicker": set0, - "mvAppItemType::mvColorButton": set0, - "mvAppItemType::mvFileDialog": set8, - "mvAppItemType::mvTabButton": set0, - "mvAppItemType::mvDrawNode": set9, - "mvAppItemType::mvNodeEditor": set10, - "mvAppItemType::mvNode": set11, - "mvAppItemType::mvNodeAttribute": set2, - "mvAppItemType::mvTable": set12, - "mvAppItemType::mvTableColumn": set0, - "mvAppItemType::mvTableRow": set13, - "mvAppItemType::mvSyncedTables": set2, - "mvAppItemType::mvDrawLine": set0, - "mvAppItemType::mvDrawArrow": set0, - "mvAppItemType::mvDrawTriangle": set0, - "mvAppItemType::mvDrawImageQuad": set0, - "mvAppItemType::mvDrawCircle": set0, - "mvAppItemType::mvDrawEllipse": set0, - "mvAppItemType::mvDrawBezierCubic": set0, - "mvAppItemType::mvDrawBezierQuadratic": set0, - "mvAppItemType::mvDrawQuad": set0, - "mvAppItemType::mvDrawRect": set0, - "mvAppItemType::mvDrawText": set0, - "mvAppItemType::mvDrawPolygon": set0, - "mvAppItemType::mvDrawPolyline": set0, - "mvAppItemType::mvDrawImage": set0, - "mvAppItemType::mvDragFloatMulti": set0, - "mvAppItemType::mvDragIntMulti": set0, - "mvAppItemType::mvSliderFloatMulti": set0, - "mvAppItemType::mvSliderIntMulti": set0, - "mvAppItemType::mvInputIntMulti": set0, - "mvAppItemType::mvInputFloatMulti": set0, - "mvAppItemType::mvDragPoint": set0, - "mvAppItemType::mvDragLine": set0, - "mvAppItemType::mvDragRect": set0, - "mvAppItemType::mvAnnotation": set0, - "mvAppItemType::mvAxisTag": set0, - "mvAppItemType::mvLineSeries": set2, - "mvAppItemType::mvScatterSeries": set2, - "mvAppItemType::mvStemSeries": set2, - "mvAppItemType::mvStairSeries": set2, - "mvAppItemType::mvBarSeries": set2, - "mvAppItemType::mvBarGroupSeries": set2, - "mvAppItemType::mvErrorSeries": set2, - "mvAppItemType::mvInfLineSeries": set2, - "mvAppItemType::mvHeatSeries": set2, - "mvAppItemType::mvImageSeries": set2, - "mvAppItemType::mvPieSeries": set2, - "mvAppItemType::mvShadeSeries": set2, - "mvAppItemType::mvLabelSeries": set2, - "mvAppItemType::mvHistogramSeries": set2, - "mvAppItemType::mvDigitalSeries": set2, - "mvAppItemType::mv2dHistogramSeries": set2, - "mvAppItemType::mvCandleSeries": set2, - "mvAppItemType::mvAreaSeries": set2, - "mvAppItemType::mvColorMapScale": set0, - "mvAppItemType::mvSlider3D": set0, - "mvAppItemType::mvKnobFloat": set0, - "mvAppItemType::mvLoadingIndicator": set0, - "mvAppItemType::mvNodeLink": set0, - "mvAppItemType::mvTextureRegistry": set14, - "mvAppItemType::mvStaticTexture": set0, - "mvAppItemType::mvDynamicTexture": set0, - "mvAppItemType::mvStage": set15, - "mvAppItemType::mvDrawLayer": set9, - "mvAppItemType::mvViewportDrawlist": set6, - "mvAppItemType::mvFileExtension": set0, - "mvAppItemType::mvPlotLegend": set2, - "mvAppItemType::mvPlotAxis": set16, - "mvAppItemType::mvHandlerRegistry": set17, - "mvAppItemType::mvKeyDownHandler": set0, - "mvAppItemType::mvKeyPressHandler": set0, - "mvAppItemType::mvKeyReleaseHandler": set0, - "mvAppItemType::mvMouseMoveHandler": set0, - "mvAppItemType::mvMouseWheelHandler": set0, - "mvAppItemType::mvMouseClickHandler": set0, - "mvAppItemType::mvMouseDoubleClickHandler": set0, - "mvAppItemType::mvMouseDownHandler": set0, - "mvAppItemType::mvMouseReleaseHandler": set0, - "mvAppItemType::mvMouseDragHandler": set0, - "mvAppItemType::mvHoverHandler": set0, - "mvAppItemType::mvActiveHandler": set0, - "mvAppItemType::mvFocusHandler": set0, - "mvAppItemType::mvVisibleHandler": set0, - "mvAppItemType::mvEditedHandler": set0, - "mvAppItemType::mvActivatedHandler": set0, - "mvAppItemType::mvDeactivatedHandler": set0, - "mvAppItemType::mvDeactivatedAfterEditHandler": set0, - "mvAppItemType::mvToggledOpenHandler": set0, - "mvAppItemType::mvClickedHandler": set0, - "mvAppItemType::mvDoubleClickedHandler": set0, - "mvAppItemType::mvScrollHandler": set0, - "mvAppItemType::mvDragPayload": set2, - "mvAppItemType::mvResizeHandler": set0, - "mvAppItemType::mvFont": set18, - "mvAppItemType::mvFontRegistry": set19, - "mvAppItemType::mvTheme": set20, - "mvAppItemType::mvThemeColor": set0, - "mvAppItemType::mvThemeStyle": set0, - "mvAppItemType::mvThemeComponent": set21, - "mvAppItemType::mvCharRemap": set0, - "mvAppItemType::mvValueRegistry": set22, - "mvAppItemType::mvIntValue": set0, - "mvAppItemType::mvFloatValue": set0, - "mvAppItemType::mvFloat4Value": set0, - "mvAppItemType::mvInt4Value": set0, - "mvAppItemType::mvBoolValue": set0, - "mvAppItemType::mvStringValue": set0, - "mvAppItemType::mvDoubleValue": set0, - "mvAppItemType::mvDouble4Value": set0, - "mvAppItemType::mvColorValue": set0, - "mvAppItemType::mvFloatVectValue": set0, - "mvAppItemType::mvSeriesValue": set0, - "mvAppItemType::mvRawTexture": set0, - "mvAppItemType::mvSubPlots": set23, - "mvAppItemType::mvColorMap": set0, - "mvAppItemType::mvColorMapRegistry": set24, - "mvAppItemType::mvColorMapButton": set0, - "mvAppItemType::mvColorMapSlider": set0, - "mvAppItemType::mvTemplateRegistry": set25, - "mvAppItemType::mvTableCell": set2, - "mvAppItemType::mvItemHandlerRegistry": set26, - "mvAppItemType::mvInputDouble": set0, - "mvAppItemType::mvInputDoubleMulti": set0, - "mvAppItemType::mvDragDouble": set0, - "mvAppItemType::mvDragDoubleMulti": set0, - "mvAppItemType::mvSliderDouble": set0, - "mvAppItemType::mvSliderDoubleMulti": set0, - "mvAppItemType::mvCustomSeries": set27, - } - -def get_item_type_commands(**kwargs) -> dict: - """ Return the names of item types and their associated functions as a mapping.""" - - return { - "mvAppItemType::mvInputText": "add_input_text", - "mvAppItemType::mvButton": "add_button", - "mvAppItemType::mvRadioButton": "add_radio_button", - "mvAppItemType::mvTabBar": "add_tab_bar", - "mvAppItemType::mvTab": "add_tab", - "mvAppItemType::mvImage": "add_image", - "mvAppItemType::mvMenuBar": "add_menu_bar", - "mvAppItemType::mvViewportMenuBar": "add_viewport_menu_bar", - "mvAppItemType::mvMenu": "add_menu", - "mvAppItemType::mvMenuItem": "add_menu_item", - "mvAppItemType::mvChildWindow": "add_child_window", - "mvAppItemType::mvGroup": "add_group", - "mvAppItemType::mvSliderFloat": "add_slider_float", - "mvAppItemType::mvSliderInt": "add_slider_int", - "mvAppItemType::mvFilterSet": "add_filter_set", - "mvAppItemType::mvDragFloat": "add_drag_float", - "mvAppItemType::mvDragInt": "add_drag_int", - "mvAppItemType::mvInputFloat": "add_input_float", - "mvAppItemType::mvInputInt": "add_input_int", - "mvAppItemType::mvColorEdit": "add_color_edit", - "mvAppItemType::mvClipper": "add_clipper", - "mvAppItemType::mvColorPicker": "add_color_picker", - "mvAppItemType::mvTooltip": "add_tooltip", - "mvAppItemType::mvCollapsingHeader": "add_collapsing_header", - "mvAppItemType::mvSeparator": "add_separator", - "mvAppItemType::mvCheckbox": "add_checkbox", - "mvAppItemType::mvListbox": "add_listbox", - "mvAppItemType::mvText": "add_text", - "mvAppItemType::mvCombo": "add_combo", - "mvAppItemType::mvPlot": "add_plot", - "mvAppItemType::mvSimplePlot": "add_simple_plot", - "mvAppItemType::mvDrawlist": "add_drawlist", - "mvAppItemType::mvWindowAppItem": "add_window", - "mvAppItemType::mvSelectable": "add_selectable", - "mvAppItemType::mvTreeNode": "add_tree_node", - "mvAppItemType::mvProgressBar": "add_progress_bar", - "mvAppItemType::mvSpacer": "add_spacer", - "mvAppItemType::mvImageButton": "add_image_button", - "mvAppItemType::mvTimePicker": "add_time_picker", - "mvAppItemType::mvDatePicker": "add_date_picker", - "mvAppItemType::mvColorButton": "add_color_button", - "mvAppItemType::mvFileDialog": "add_file_dialog", - "mvAppItemType::mvTabButton": "add_tab_button", - "mvAppItemType::mvDrawNode": "add_draw_node", - "mvAppItemType::mvNodeEditor": "add_node_editor", - "mvAppItemType::mvNode": "add_node", - "mvAppItemType::mvNodeAttribute": "add_node_attribute", - "mvAppItemType::mvTable": "add_table", - "mvAppItemType::mvTableColumn": "add_table_column", - "mvAppItemType::mvTableRow": "add_table_row", - "mvAppItemType::mvSyncedTables": "add_synced_tables", - "mvAppItemType::mvDrawLine": "draw_line", - "mvAppItemType::mvDrawArrow": "draw_arrow", - "mvAppItemType::mvDrawTriangle": "draw_triangle", - "mvAppItemType::mvDrawImageQuad": "draw_image_quad", - "mvAppItemType::mvDrawCircle": "draw_circle", - "mvAppItemType::mvDrawEllipse": "draw_ellipse", - "mvAppItemType::mvDrawBezierCubic": "draw_bezier_cubic", - "mvAppItemType::mvDrawBezierQuadratic": "draw_bezier_quadratic", - "mvAppItemType::mvDrawQuad": "draw_quad", - "mvAppItemType::mvDrawRect": "draw_rectangle", - "mvAppItemType::mvDrawText": "draw_text", - "mvAppItemType::mvDrawPolygon": "draw_polygon", - "mvAppItemType::mvDrawPolyline": "draw_polyline", - "mvAppItemType::mvDrawImage": "draw_image", - "mvAppItemType::mvDragFloatMulti": "add_drag_floatx", - "mvAppItemType::mvDragIntMulti": "add_drag_intx", - "mvAppItemType::mvSliderFloatMulti": "add_slider_floatx", - "mvAppItemType::mvSliderIntMulti": "add_slider_intx", - "mvAppItemType::mvInputIntMulti": "add_input_intx", - "mvAppItemType::mvInputFloatMulti": "add_input_floatx", - "mvAppItemType::mvDragPoint": "add_drag_point", - "mvAppItemType::mvDragLine": "add_drag_line", - "mvAppItemType::mvDragRect": "add_drag_rect", - "mvAppItemType::mvAnnotation": "add_plot_annotation", - "mvAppItemType::mvAxisTag": "add_axis_tag", - "mvAppItemType::mvLineSeries": "add_line_series", - "mvAppItemType::mvScatterSeries": "add_scatter_series", - "mvAppItemType::mvStemSeries": "add_stem_series", - "mvAppItemType::mvStairSeries": "add_stair_series", - "mvAppItemType::mvBarSeries": "add_bar_series", - "mvAppItemType::mvBarGroupSeries": "add_bar_group_series", - "mvAppItemType::mvErrorSeries": "add_error_series", - "mvAppItemType::mvInfLineSeries": "add_inf_line_series", - "mvAppItemType::mvHeatSeries": "add_heat_series", - "mvAppItemType::mvImageSeries": "add_image_series", - "mvAppItemType::mvPieSeries": "add_pie_series", - "mvAppItemType::mvShadeSeries": "add_shade_series", - "mvAppItemType::mvLabelSeries": "add_text_point", - "mvAppItemType::mvHistogramSeries": "add_histogram_series", - "mvAppItemType::mvDigitalSeries": "add_digital_series", - "mvAppItemType::mv2dHistogramSeries": "add_2d_histogram_series", - "mvAppItemType::mvCandleSeries": "add_candle_series", - "mvAppItemType::mvAreaSeries": "add_area_series", - "mvAppItemType::mvColorMapScale": "add_colormap_scale", - "mvAppItemType::mvSlider3D": "add_3d_slider", - "mvAppItemType::mvKnobFloat": "add_knob_float", - "mvAppItemType::mvLoadingIndicator": "add_loading_indicator", - "mvAppItemType::mvNodeLink": "add_node_link", - "mvAppItemType::mvTextureRegistry": "add_texture_registry", - "mvAppItemType::mvStaticTexture": "add_static_texture", - "mvAppItemType::mvDynamicTexture": "add_dynamic_texture", - "mvAppItemType::mvStage": "add_stage", - "mvAppItemType::mvDrawLayer": "add_draw_layer", - "mvAppItemType::mvViewportDrawlist": "add_viewport_drawlist", - "mvAppItemType::mvFileExtension": "add_file_extension", - "mvAppItemType::mvPlotLegend": "add_plot_legend", - "mvAppItemType::mvPlotAxis": "add_plot_axis", - "mvAppItemType::mvHandlerRegistry": "add_handler_registry", - "mvAppItemType::mvKeyDownHandler": "add_key_down_handler", - "mvAppItemType::mvKeyPressHandler": "add_key_press_handler", - "mvAppItemType::mvKeyReleaseHandler": "add_key_release_handler", - "mvAppItemType::mvMouseMoveHandler": "add_mouse_move_handler", - "mvAppItemType::mvMouseWheelHandler": "add_mouse_wheel_handler", - "mvAppItemType::mvMouseClickHandler": "add_mouse_click_handler", - "mvAppItemType::mvMouseDoubleClickHandler": "add_mouse_double_click_handler", - "mvAppItemType::mvMouseDownHandler": "add_mouse_down_handler", - "mvAppItemType::mvMouseReleaseHandler": "add_mouse_release_handler", - "mvAppItemType::mvMouseDragHandler": "add_mouse_drag_handler", - "mvAppItemType::mvHoverHandler": "add_item_hover_handler", - "mvAppItemType::mvActiveHandler": "add_item_active_handler", - "mvAppItemType::mvFocusHandler": "add_item_focus_handler", - "mvAppItemType::mvVisibleHandler": "add_item_visible_handler", - "mvAppItemType::mvEditedHandler": "add_item_edited_handler", - "mvAppItemType::mvActivatedHandler": "add_item_activated_handler", - "mvAppItemType::mvDeactivatedHandler": "add_item_deactivated_handler", - "mvAppItemType::mvDeactivatedAfterEditHandler": "add_item_deactivated_after_edit_handler", - "mvAppItemType::mvToggledOpenHandler": "add_item_toggled_open_handler", - "mvAppItemType::mvClickedHandler": "add_item_clicked_handler", - "mvAppItemType::mvDoubleClickedHandler": "add_item_double_clicked_handler", - "mvAppItemType::mvScrollHandler": "add_item_scroll_handler", - "mvAppItemType::mvDragPayload": "add_drag_payload", - "mvAppItemType::mvResizeHandler": "add_item_resize_handler", - "mvAppItemType::mvFont": "add_font", - "mvAppItemType::mvFontRegistry": "add_font_registry", - "mvAppItemType::mvTheme": "add_theme", - "mvAppItemType::mvThemeColor": "add_theme_color", - "mvAppItemType::mvThemeStyle": "add_theme_style", - "mvAppItemType::mvThemeComponent": "add_theme_component", - "mvAppItemType::mvCharRemap": "add_char_remap", - "mvAppItemType::mvValueRegistry": "add_value_registry", - "mvAppItemType::mvIntValue": "add_int_value", - "mvAppItemType::mvFloatValue": "add_float_value", - "mvAppItemType::mvFloat4Value": "add_float4_value", - "mvAppItemType::mvInt4Value": "add_int4_value", - "mvAppItemType::mvBoolValue": "add_bool_value", - "mvAppItemType::mvStringValue": "add_string_value", - "mvAppItemType::mvDoubleValue": "add_double_value", - "mvAppItemType::mvDouble4Value": "add_double4_value", - "mvAppItemType::mvColorValue": "add_color_value", - "mvAppItemType::mvFloatVectValue": "add_float_vect_value", - "mvAppItemType::mvSeriesValue": "add_series_value", - "mvAppItemType::mvRawTexture": "add_raw_texture", - "mvAppItemType::mvSubPlots": "add_subplots", - "mvAppItemType::mvColorMap": "add_colormap", - "mvAppItemType::mvColorMapRegistry": "add_colormap_registry", - "mvAppItemType::mvColorMapButton": "add_colormap_button", - "mvAppItemType::mvColorMapSlider": "add_colormap_slider", - "mvAppItemType::mvTemplateRegistry": "add_template_registry", - "mvAppItemType::mvTableCell": "add_table_cell", - "mvAppItemType::mvItemHandlerRegistry": "add_item_handler_registry", - "mvAppItemType::mvInputDouble": "add_input_double", - "mvAppItemType::mvInputDoubleMulti": "add_input_doublex", - "mvAppItemType::mvDragDouble": "add_drag_double", - "mvAppItemType::mvDragDoubleMulti": "add_drag_doublex", - "mvAppItemType::mvSliderDouble": "add_slider_double", - "mvAppItemType::mvSliderDoubleMulti": "add_slider_doublex", - "mvAppItemType::mvCustomSeries": "add_custom_series", - } - -CONTAINERS = frozenset(( - "mvAppItemType::mvTabBar", - "mvAppItemType::mvTab", - "mvAppItemType::mvMenuBar", - "mvAppItemType::mvViewportMenuBar", - "mvAppItemType::mvMenu", - "mvAppItemType::mvChildWindow", - "mvAppItemType::mvGroup", - "mvAppItemType::mvFilterSet", - "mvAppItemType::mvClipper", - "mvAppItemType::mvTooltip", - "mvAppItemType::mvCollapsingHeader", - "mvAppItemType::mvPlot", - "mvAppItemType::mvDrawlist", - "mvAppItemType::mvWindowAppItem", - "mvAppItemType::mvTreeNode", - "mvAppItemType::mvFileDialog", - "mvAppItemType::mvDrawNode", - "mvAppItemType::mvNodeEditor", - "mvAppItemType::mvNode", - "mvAppItemType::mvNodeAttribute", - "mvAppItemType::mvTable", - "mvAppItemType::mvTableRow", - "mvAppItemType::mvSyncedTables", - "mvAppItemType::mvLineSeries", - "mvAppItemType::mvScatterSeries", - "mvAppItemType::mvStemSeries", - "mvAppItemType::mvStairSeries", - "mvAppItemType::mvBarSeries", - "mvAppItemType::mvBarGroupSeries", - "mvAppItemType::mvErrorSeries", - "mvAppItemType::mvInfLineSeries", - "mvAppItemType::mvHeatSeries", - "mvAppItemType::mvImageSeries", - "mvAppItemType::mvPieSeries", - "mvAppItemType::mvShadeSeries", - "mvAppItemType::mvLabelSeries", - "mvAppItemType::mvHistogramSeries", - "mvAppItemType::mvDigitalSeries", - "mvAppItemType::mv2dHistogramSeries", - "mvAppItemType::mvCandleSeries", - "mvAppItemType::mvAreaSeries", - "mvAppItemType::mvTextureRegistry", - "mvAppItemType::mvStage", - "mvAppItemType::mvDrawLayer", - "mvAppItemType::mvViewportDrawlist", - "mvAppItemType::mvPlotLegend", - "mvAppItemType::mvPlotAxis", - "mvAppItemType::mvHandlerRegistry", - "mvAppItemType::mvDragPayload", - "mvAppItemType::mvFont", - "mvAppItemType::mvFontRegistry", - "mvAppItemType::mvTheme", - "mvAppItemType::mvThemeComponent", - "mvAppItemType::mvValueRegistry", - "mvAppItemType::mvSubPlots", - "mvAppItemType::mvColorMapRegistry", - "mvAppItemType::mvTemplateRegistry", - "mvAppItemType::mvTableCell", - "mvAppItemType::mvItemHandlerRegistry", - "mvAppItemType::mvCustomSeries", -)) - -def is_container(item_type: str, **kwargs) -> bool: - """ Return `True` if items of the provided item type can parent other items. - - Args: - item_type (str): Item type. - Returns: - bool - """ - - return item_type in CONTAINERS - -ROOTS = frozenset(( - "mvAppItemType::mvViewportMenuBar", - "mvAppItemType::mvWindowAppItem", - "mvAppItemType::mvFileDialog", - "mvAppItemType::mvTextureRegistry", - "mvAppItemType::mvStage", - "mvAppItemType::mvViewportDrawlist", - "mvAppItemType::mvHandlerRegistry", - "mvAppItemType::mvFontRegistry", - "mvAppItemType::mvTheme", - "mvAppItemType::mvValueRegistry", - "mvAppItemType::mvColorMapRegistry", - "mvAppItemType::mvTemplateRegistry", - "mvAppItemType::mvItemHandlerRegistry", -)) - -def is_root(item_type: str, **kwargs) -> bool: - """ Return `True` if items of the provided item type are root containers. - - Args: - item_type (str): Item type. - Returns: - bool - """ - - return item_type in ROOTS - -def get_applicable_states(**kwargs) -> dict: - """ Return all item type names and collections of applicable child types as a mapping.""" - - return { - "mvAppItemType::mvInputText": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvButton": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvRadioButton": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvTabBar": ("ok", "pos", "visible", ), - "mvAppItemType::mvTab": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvImage": ("ok", "pos", "hovered", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvMenuBar": ("ok", "pos", "visible", ), - "mvAppItemType::mvViewportMenuBar": ("ok", "pos", ), - "mvAppItemType::mvMenu": ("ok", "pos", "hovered", "active", "focused", "activated", "deactivated", "rect_size", "resized", ), - "mvAppItemType::mvMenuItem": ("ok", "pos", ), - "mvAppItemType::mvChildWindow": ("ok", "pos", "hovered", "active", "focused", "deactivated", "rect_size", "resized", "content_region_avail", "scrolled", "is_scrolling", "scroll_pos", "scroll_max", ), - "mvAppItemType::mvGroup": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderFloat": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderInt": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvFilterSet": ("ok", "pos", ), - "mvAppItemType::mvDragFloat": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvDragInt": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvInputFloat": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvInputInt": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvColorEdit": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvClipper": ("ok", "pos", ), - "mvAppItemType::mvColorPicker": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvTooltip": ("ok", "pos", "visible", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvCollapsingHeader": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "toggled_open", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSeparator": ("ok", "pos", ), - "mvAppItemType::mvCheckbox": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvListbox": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", "scrolled", "is_scrolling", "scroll_pos", "scroll_max", ), - "mvAppItemType::mvText": ("ok", "pos", "hovered", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvCombo": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvPlot": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSimplePlot": ("ok", "pos", ), - "mvAppItemType::mvDrawlist": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvWindowAppItem": ("ok", "pos", "hovered", "focused", "visible", "toggled_open", "rect_size", "resized", "scrolled", "is_scrolling", "scroll_pos", "scroll_max", ), - "mvAppItemType::mvSelectable": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "toggled_open", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvTreeNode": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "toggled_open", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvProgressBar": ("ok", "pos", ), - "mvAppItemType::mvSpacer": ("ok", "pos", ), - "mvAppItemType::mvImageButton": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvTimePicker": ("ok", "pos", "visible", "rect_min", "rect_max", "rect_size", "resized", ), - "mvAppItemType::mvDatePicker": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvColorButton": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvFileDialog": ("ok", "pos", ), - "mvAppItemType::mvTabButton": ("ok", "pos", ), - "mvAppItemType::mvDrawNode": ("ok", "pos", ), - "mvAppItemType::mvNodeEditor": ("ok", "pos", "hovered", "visible", "rect_min", "rect_max", "rect_size", "resized", ), - "mvAppItemType::mvNode": ("ok", "pos", "hovered", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "rect_min", "rect_max", "rect_size", "resized", ), - "mvAppItemType::mvNodeAttribute": ("ok", "pos", "hovered", ), - "mvAppItemType::mvTable": ("ok", "pos", "visible", "scrolled", "is_scrolling", "scroll_pos", "scroll_max", ), - "mvAppItemType::mvTableColumn": ("ok", "pos", "hovered", "visible", "rect_size", "resized", ), - "mvAppItemType::mvTableRow": ("ok", "pos", "visible", ), - "mvAppItemType::mvSyncedTables": ("ok", "pos", "visible", ), - "mvAppItemType::mvDrawLine": ("ok", "pos", ), - "mvAppItemType::mvDrawArrow": ("ok", "pos", ), - "mvAppItemType::mvDrawTriangle": ("ok", "pos", ), - "mvAppItemType::mvDrawImageQuad": ("ok", "pos", ), - "mvAppItemType::mvDrawCircle": ("ok", "pos", ), - "mvAppItemType::mvDrawEllipse": ("ok", "pos", ), - "mvAppItemType::mvDrawBezierCubic": ("ok", "pos", ), - "mvAppItemType::mvDrawBezierQuadratic": ("ok", "pos", ), - "mvAppItemType::mvDrawQuad": ("ok", "pos", ), - "mvAppItemType::mvDrawRect": ("ok", "pos", ), - "mvAppItemType::mvDrawText": ("ok", "pos", ), - "mvAppItemType::mvDrawPolygon": ("ok", "pos", ), - "mvAppItemType::mvDrawPolyline": ("ok", "pos", ), - "mvAppItemType::mvDrawImage": ("ok", "pos", ), - "mvAppItemType::mvDragFloatMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvDragIntMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderFloatMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderIntMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvInputIntMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvInputFloatMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvDragPoint": ("ok", "pos", ), - "mvAppItemType::mvDragLine": ("ok", "pos", ), - "mvAppItemType::mvDragRect": ("ok", "pos", ), - "mvAppItemType::mvAnnotation": ("ok", "pos", ), - "mvAppItemType::mvAxisTag": ("ok", "pos", ), - "mvAppItemType::mvLineSeries": ("ok", "pos", ), - "mvAppItemType::mvScatterSeries": ("ok", "pos", ), - "mvAppItemType::mvStemSeries": ("ok", "pos", ), - "mvAppItemType::mvStairSeries": ("ok", "pos", ), - "mvAppItemType::mvBarSeries": ("ok", "pos", ), - "mvAppItemType::mvBarGroupSeries": ("ok", "pos", ), - "mvAppItemType::mvErrorSeries": ("ok", "pos", ), - "mvAppItemType::mvInfLineSeries": ("ok", "pos", ), - "mvAppItemType::mvHeatSeries": ("ok", "pos", ), - "mvAppItemType::mvImageSeries": ("ok", "pos", ), - "mvAppItemType::mvPieSeries": ("ok", "pos", ), - "mvAppItemType::mvShadeSeries": ("ok", "pos", ), - "mvAppItemType::mvLabelSeries": ("ok", "pos", ), - "mvAppItemType::mvHistogramSeries": ("ok", "pos", ), - "mvAppItemType::mvDigitalSeries": ("ok", "pos", ), - "mvAppItemType::mv2dHistogramSeries": ("ok", "pos", ), - "mvAppItemType::mvCandleSeries": ("ok", "pos", ), - "mvAppItemType::mvAreaSeries": ("ok", "pos", ), - "mvAppItemType::mvColorMapScale": ("ok", "pos", "hovered", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSlider3D": ("ok", "pos", "hovered", "visible", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvKnobFloat": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvLoadingIndicator": ("ok", "pos", "hovered", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvNodeLink": ("ok", "pos", "hovered", ), - "mvAppItemType::mvTextureRegistry": ("ok", "pos", ), - "mvAppItemType::mvStaticTexture": ("ok", "pos", ), - "mvAppItemType::mvDynamicTexture": ("ok", "pos", ), - "mvAppItemType::mvStage": ("ok", "pos", ), - "mvAppItemType::mvDrawLayer": ("ok", "pos", ), - "mvAppItemType::mvViewportDrawlist": ("ok", "pos", ), - "mvAppItemType::mvFileExtension": ("ok", "pos", ), - "mvAppItemType::mvPlotLegend": ("ok", "pos", ), - "mvAppItemType::mvPlotAxis": ("ok", "pos", ), - "mvAppItemType::mvHandlerRegistry": ("ok", "pos", ), - "mvAppItemType::mvKeyDownHandler": ("ok", "pos", ), - "mvAppItemType::mvKeyPressHandler": ("ok", "pos", ), - "mvAppItemType::mvKeyReleaseHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseMoveHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseWheelHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseClickHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseDoubleClickHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseDownHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseReleaseHandler": ("ok", "pos", ), - "mvAppItemType::mvMouseDragHandler": ("ok", "pos", ), - "mvAppItemType::mvHoverHandler": ("ok", "pos", ), - "mvAppItemType::mvActiveHandler": ("ok", "pos", ), - "mvAppItemType::mvFocusHandler": ("ok", "pos", ), - "mvAppItemType::mvVisibleHandler": ("ok", "pos", ), - "mvAppItemType::mvEditedHandler": ("ok", "pos", ), - "mvAppItemType::mvActivatedHandler": ("ok", "pos", ), - "mvAppItemType::mvDeactivatedHandler": ("ok", "pos", ), - "mvAppItemType::mvDeactivatedAfterEditHandler": ("ok", "pos", ), - "mvAppItemType::mvToggledOpenHandler": ("ok", "pos", ), - "mvAppItemType::mvClickedHandler": ("ok", "pos", ), - "mvAppItemType::mvDoubleClickedHandler": ("ok", "pos", ), - "mvAppItemType::mvScrollHandler": ("ok", "pos", ), - "mvAppItemType::mvDragPayload": ("ok", "pos", ), - "mvAppItemType::mvResizeHandler": ("ok", "pos", ), - "mvAppItemType::mvFont": ("ok", "pos", ), - "mvAppItemType::mvFontRegistry": ("ok", "pos", ), - "mvAppItemType::mvTheme": ("ok", "pos", ), - "mvAppItemType::mvThemeColor": ("ok", "pos", ), - "mvAppItemType::mvThemeStyle": ("ok", "pos", ), - "mvAppItemType::mvThemeComponent": ("ok", "pos", ), - "mvAppItemType::mvCharRemap": ("ok", "pos", ), - "mvAppItemType::mvValueRegistry": ("ok", "pos", ), - "mvAppItemType::mvIntValue": ("ok", "pos", ), - "mvAppItemType::mvFloatValue": ("ok", "pos", ), - "mvAppItemType::mvFloat4Value": ("ok", "pos", ), - "mvAppItemType::mvInt4Value": ("ok", "pos", ), - "mvAppItemType::mvBoolValue": ("ok", "pos", ), - "mvAppItemType::mvStringValue": ("ok", "pos", ), - "mvAppItemType::mvDoubleValue": ("ok", "pos", ), - "mvAppItemType::mvDouble4Value": ("ok", "pos", ), - "mvAppItemType::mvColorValue": ("ok", "pos", ), - "mvAppItemType::mvFloatVectValue": ("ok", "pos", ), - "mvAppItemType::mvSeriesValue": ("ok", "pos", ), - "mvAppItemType::mvRawTexture": ("ok", "pos", ), - "mvAppItemType::mvSubPlots": ("ok", "pos", ), - "mvAppItemType::mvColorMap": ("ok", "pos", ), - "mvAppItemType::mvColorMapRegistry": ("ok", "pos", ), - "mvAppItemType::mvColorMapButton": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "activated", "deactivated", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvColorMapSlider": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvTemplateRegistry": ("ok", "pos", ), - "mvAppItemType::mvTableCell": ("ok", "pos", ), - "mvAppItemType::mvItemHandlerRegistry": ("ok", "pos", ), - "mvAppItemType::mvInputDouble": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvInputDoubleMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvDragDouble": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvDragDoubleMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderDouble": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvSliderDoubleMulti": ("ok", "pos", "hovered", "active", "focused", "clicked", "left_clicked", "right_clicked", "middle_clicked", "visible", "edited", "activated", "deactivated", "deactivated_after_edit", "rect_min", "rect_max", "rect_size", "resized", "content_region_avail", ), - "mvAppItemType::mvCustomSeries": ("ok", "pos", ), - } - diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index d16386367..000000000 --- a/docs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -build/ \ No newline at end of file diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt new file mode 100644 index 000000000..972813fa9 --- /dev/null +++ b/docs/CHANGELOG.txt @@ -0,0 +1,1266 @@ +Dear PyGui +CHANGELOG + +This document holds the user-facing changelog that we also use in release notes. +We generally fold multiple commits pertaining to the same topic as a single entry. +Changes to the examples/bindings are included within the individual .cpp files in the examples/ folder. + +RELEASE NOTES: https://github.com/hoffstadt/DearPyGui/releases +REPORT ISSUES, ASK QUESTIONS: https://github.com/hoffstadt/DearPyGui/issues +COMMITS HISTORY: https://github.com/hoffstadt/DearPyGui/commits/master +WIKI https://github.com/hoffstadt/DearPyGui/wiki + +WHEN TO UPDATE? + +- Keeping your copy of Dear PyGui updated regularly is recommended. +- It is generally safe to sync to the latest commit in master or docking branches + The library is fairly stable and regressions tends to be fixed fast when reported. + +HOW TO UPDATE? + +- pip or pip3 install dearpygui --upgrade +- Read the `Breaking Changes` section (here in the changelog). +- Please report any issue! + +------------------------------------------------------------------------ + VERSION 0.7.x +------------------------------------------------------------------------ + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.7.x + +Breaking Changes: +- drags: combined drags into a single widget +- sliders: combined sliders into a single widget +- inputs: combined inputs into a single widget +- draw commands: now widgets, with parent, show, before keyword +- drawings: now a container widget +- add_image: image and name keyword order swapped +- add_image_button: image and name keyword order swapped +- modified command: add_menu_item - when used with checkmark it will no longer disable other sibling menui items checkmarks +- removed command: decref_value +- removed command: incref_value +- removed command: add_value +- removed command: add_data +- removed command: delete_data +- removed command: get_data +- removed command: set_render_callback +- removed command: start_dearpygui +- removed command: add_next_column +- removed command: add_column +- removed command: add_columns +- removed command: add_managed_columns +- removed command: managed_columns +- removed command: add_row +- removed command: clear_table +- removed command: delete_column +- removed command: delete_row +- removed command: set_managed_column_width +- removed command: get_managed_column_width +- removed command: set_table_data +- removed command: get_table_data +- removed command: get_table_item +- removed command: set_table_item +- removed command: get_table_selections +- removed command: set_table_selection +- removed command: insert_column +- removed command: insert_row +- removed command: set_headers +- removed command: add_additional_font +- removed command: add_character_remap +- removed command: get_main_window_size +- removed command: get_main_window_size +- removed command: set_main_window_size +- removed command: set_main_window_pos +- removed command: get_main_window_pos +- removed command: set_main_window_resizable +- removed command: set_main_window_title +- removed command: get_viewport_size +- removed command: set_viewport_pos +- removed command: set_viewport_resizable +- removed command: set_viewport_size +- removed command: set_viewport_title +- removed command: set_vsync +- removed command: add_annotation +- removed command: add_drag_line +- removed command: add_drag_point +- removed command: delete_annotation +- removed command: delete_drag_line +- removed command: delete_drag_point + +New Keywords: +- add_window: Added "min_size" keyword #700 +- add_window: Added "max_size" keyword #700 +- add_selectable: Added "width" keyword +- add_selectable: Added "height" keyword +- add_node_attribute: Added "shape" keyword #713 +- add_menu_item: Added "default_value" keyword + +New Commands: +- add_plot_annotation as widget +- add_drag_line as widget +- add_drag_point as widget +- create_viewport +- show_viewport +- maximize_viewport +- minimize_viewport +- configure_viewport +- table +- add_table_column +- clear_data_grid +- insert_grid_column +- delete_grid_column +- delete_grid_row +- insert_grid_row +- get_grid_data +- set_grid_data +- get_grid_item +- set_grid_item +- get_grid_selections +- set_grid_selection +- set_font +- add_font +- removed command: get_viewport_size +- removed command: get_viewport_size +- removed command: set_viewport_size +- removed command: set_viewport_pos +- removed command: get_viewport_pos +- removed command: set_viewport_resizable +- removed command: set_viewport_title + + +Updates: +- item name is now optional +- widget adding functions return ID +- fonts: replaced truetype with free type 2.10.4 +- imgui: updated to v1.82 +- imfiledialog: updated to v0.5.5 +- implot: updated to commit 1d9381a +- value_storage: removed + +Fixes: +- MacOs: fixed obscured windows maxing CPU +- start_dearpygui: fixed primary window not found crash #523 +- callback_error: prevent callback error crash +- numpy: numpy arrays not working with plots + +------------------------------------------------------------------------ + VERSION 0.6.151 +------------------------------------------------------------------------ +Fixes: +- add_text: changed default wrap to -1 +- tree_node: fixed label being ignored in context manager + +------------------------------------------------------------------------ + VERSION 0.6.149 +------------------------------------------------------------------------ + +Fixes: +- callback: fixed method callback issue #506 + +------------------------------------------------------------------------ + VERSION 0.6.148 +------------------------------------------------------------------------ + +Fixes: +- debug tool: fix item position freeze + +------------------------------------------------------------------------ + VERSION 0.6.146 +------------------------------------------------------------------------ + +Upgrades: +- callbacks: number of arguments do not matter anymore + +Fixes: +- images: fixed crashes caused by unfound images + +------------------------------------------------------------------------ + VERSION 0.6.144 +------------------------------------------------------------------------ + +Fixes: +- debug window: the "commands" section works again. + +------------------------------------------------------------------------ + VERSION 0.6.139 +------------------------------------------------------------------------ + +Fixes: +- callback_data: fixed table callback data not sending #496 + +------------------------------------------------------------------------ + VERSION 0.6.137 +------------------------------------------------------------------------ + +Fixes: +- stop_dearpygui: fixed crash and operation of this command #495 + +------------------------------------------------------------------------ + VERSION 0.6.136 +------------------------------------------------------------------------ + +Fixes: +- file_dialog: fixed crash #492 + +------------------------------------------------------------------------ + VERSION 0.6.126 +------------------------------------------------------------------------ + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.126 + +New Keywords: +- add_input_int: Added "min_value" keyword +- add_input_int: Added "max_value" keyword +- add_input_int: Added "clamped" keyword + +Breaking Changes: +- get_thread_count: removed command +- get_threadpool_timeout: removed command +- is_threadpool_high_performance: removed command +- run_async_function: removed command +- set_thread_count: removed command +- set_threadpool_high_performance: removed command +- set_threadpool_timeout: removed command + +Fixes: +- image_button: fixed issue where callbacks didn't work properly on + image buttons using same image #483 + +------------------------------------------------------------------------ + VERSION 0.6.123 +------------------------------------------------------------------------ + +New Commands: +- set_logger_window_title: can now change the logger window title + +Fixes: +- set_value: set_value only works once after adding text #465 +- draw_circle: fixed modify command for fill #464 + +------------------------------------------------------------------------ + VERSION 0.6.122 +------------------------------------------------------------------------ + +New Commands: +- get_item_callback_data: can now retrieve an item's callback data #451 +- set_item_callback_data: can now set an item's callback data #451 + +Updates: +- callback_data: callback_data can now be a callable that will automatically + run and replace the data argument for the callback + +Fixes: +- add_text_point: fixed issue where the y value was incorrect #450 +- constants: added missing docking mvGuiCol_* constants + +------------------------------------------------------------------------ + VERSION 0.6.121 +------------------------------------------------------------------------ + +Fixes: +- logger: fixed issue where logs didn't show up at first +- get_item_label: fixed issue where internal label was returned #428 +- plot: fixed issue where plot ignored label #435 + +------------------------------------------------------------------------ + VERSION 0.6.119 +------------------------------------------------------------------------ + +New Keywords: +- add_input_text: Added "tab_input" + +Fixes: +- delete_row: fixed issue where row 0 couldn't be deleted #421 + +------------------------------------------------------------------------ + VERSION 0.6.117 +------------------------------------------------------------------------ + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.117 + +Updates: +- glfw: updated to 3.3.2 +- implot: updated to 0.9 WIP a9d3347 + +New Keywords: +- plot: Added "equal_aspects" keyword #305 + +Breaking Changes: +- popup keyword: removed unused popup keyword +- set_item_popup: removed command +- get_item_popup: removed command + +Fixes: +- start_dearpygui: can be called more than once now +- textures: fixed texture decrementing and buffer support (numpy) +- drawlist: fixed crash from viewport drawing before starting app +- input text: tabs(\t) can now be input #408 +- drawing api: polygon fill to draw before outline, related to #371 +- collapsing header: quering open/close works now +- numpy: list of int/float can now use numpy #105 +- treenode: changing labels no longer reset state #373 +- collapsing Header: changing labels fixed +- Mac sizing: Partially fixed. #348 #365 +- Logger: Fixed autoscroll mac bug #347 +- Delete Item: does_item_exists now looks at children delete queue + +----------------------------------------------------------------------- + VERSION 0.6.35 +----------------------------------------------------------------------- + +Fixes: +- plots: fixed plot scaling issue #364 +- get_item_width: now works for non-container widgets +- get_item_height: now works for non-container widgets + +----------------------------------------------------------------------- + VERSION 0.6.34 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.34 + +Fixes: +- exit callback: fixed exit callback being called twice +- tooltips: fixed tooltips in managed columns issue #360 + +----------------------------------------------------------------------- + VERSION 0.6.32 +----------------------------------------------------------------------- + +New Commands: +- docking: Added "enable_docking" command + +Fixes: +- tables: fixed color alignment issue +- get_item_width: now works for non-container widgets +- get_item_height: now works for non-container widgets + +----------------------------------------------------------------------- + VERSION 0.6.27 +----------------------------------------------------------------------- + +Fixes: +- set_item_label: fixed label always being empty #354 +- modify_draw_command: fixed issue with draw image uv_max #352 + +----------------------------------------------------------------------- + VERSION 0.6.24 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.24 + +Fixes: +- set_item_label: fixed issue causing resize of window #346 +- set_item_label: fixed issue causing empty labels to not work +- add_texture: fixed compile time add_texture issue introduced in 0.6.18 #350 + +----------------------------------------------------------------------- + VERSION 0.6.18 +----------------------------------------------------------------------- + +Fixes: +- delete_item: fixed issue with windows not working properly +- window_size: fixed issue where sizes were a frame late +- textures: fixed several issues with texture creation + +----------------------------------------------------------------------- + VERSION 0.6.16 +----------------------------------------------------------------------- + +Fixes: +- delete_item: fixed issue with windows not working properly + +----------------------------------------------------------------------- + VERSION 0.6.15 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.15 + +New Keywords: +- plot: Added "format" keyword +- plot: Added "y2axis_no_gridlines" keyword +- plot: Added "y2axis_no_tick_marks" keyword +- plot: Added "y2axis_no_tick_labels" keyword +- plot: Added "y2axis_log_scale" keyword +- plot: Added "y2axis_invert" keyword +- plot: Added "y2axis_lock_min" keyword +- plot: Added "y2axis_lock_max" keyword +- plot: Added "yaxis_no_gridlines" keyword +- plot: Added "y3axis_no_tick_marks" keyword +- plot: Added "y3axis_no_tick_labels" keyword +- plot: Added "y3axis_log_scale" keyword +- plot: Added "y3axis_invert" keyword +- plot: Added "y3axis_lock_min" keyword +- plot: Added "y3axis_lock_max" keyword +- add_area_series: Added "axis" keyword #318 +- add_line_series: Added "axis" keyword #318 +- add_scatter_series: Added "axis" keyword #318 +- add_heat_series: Added "axis" keyword #318 +- add_error_series: Added "axis" keyword #318 +- add_pie_series: Added "axis" keyword #318 +- add_stair_series: Added "axis" keyword #318 +- add_stem_series: Added "axis" keyword #318 +- add_shade_series: Added "axis" keyword #318 +- add_candle_series: Added "axis" keyword #318 +- add_bar_series: Added "axis" keyword #318 + +Fixes: +- set_resize_callback: handler now required +- stub file: added missing tab options +- primary window: will no longer hide logger +- start callback: is ran on the 3rd frame now + +----------------------------------------------------------------------- + VERSION 0.6.10 +----------------------------------------------------------------------- + +New Commands: +- Plot API: Added "get_plot_xlimits" command +- Plot API: Added "get_plot_ylimits" command + +New Keywords: +- add_texture: Added "format" keyword + +Fixes: +- get_value: fixed issue where bools were registered as ints +- value_storage: fixed crashing issue with conflicting types/names + +----------------------------------------------------------------------- + VERSION 0.6.5 +----------------------------------------------------------------------- + +Fixes: +- docs: fixed outdated built in docs #329 +- stub: updated stub file +- shade series: y2 is now keyword only +- image series: fixed crash + +----------------------------------------------------------------------- + VERSION 0.6.0 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.6.0 + +Updates: +- Implot: updated to v0.8 + +Breaking Changes: +- Plotting API: data input separated, [x1, x2, ...] and [y1, y2, ...] + vs [[x1, y1], [x2, y2], ...] +- Drawing API: Removed "set_drawing_origin" +- Drawing API: Removed "set_drawing_scale" +- Drawing API: Removed "get_drawing_origin" +- Drawing API: Removed "get_drawing_scale" +- Drawing API: Y axis is down now. +- Drawing API: Origin is top left corner now. +- Drawing API: pmax keyword in "draw_image" is now required. +- Drawing API: changed "delete_drawing_item" with + "delete_drawing_command". + +New Features: +- Drawing API: Can now drawing to window using window name +- Drawing API: Can now draw to viewport using "##FOREGROUND" and + "##BACKGROUND" as the draw target +- Style API: Can now apply style per widget +- Style API: Can now clear style per widget +- Simple Table: Now alternates colors + +New Commands: +- Style API: Added "set_item_style_var" command +- Style API: Added "clear_item_style_vars" command +- Drawing API: Added "bring_draw_command_forward" command +- Drawing API: Added "bring_draw_command_to_front" command +- Drawing API: Added "send_draw_command_back" command +- Drawing API: Added "send_draw_command_to_back" command +- Drawing API: Added "modify_draw_command" command +- Drawing API: Added "get_draw_command" command +- Plots: Added "add_stair_series" command +- Plots: Added "add_candle_series" command +- Plots: adding a 3rd coordinate to shade series fills area between y's + +New Keywords: +- add_input_int: Added "step" + +Fixes: +- delete_item: fixed false delete item not found warning #327 +- draw_image: fixed draw_image flipping issue #310 +- add_drawing: fixed crash on add_image using invalid path with texture coordinates +- window flags: fixed issues with window flags not being abided by + + +----------------------------------------------------------------------- + VERSION 0.5.66 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.5.66 + +Changes: +- Data Storage: now thread safe +- set_value: now thread safe +- get_value: now thread safe + +New Commands: +- Tab Button: Added "add_tab_button" command + +New Keywords: +- tab: Added "no_reorder" keyword +- tab: Added "leading" keyword +- tab: Added "trailing" keyword +- tab: Added "no_tooltip" keyword + +Fixes: +- tab bar: fixed tab bar callback +- drawing: fixed "originy" issue #309 +- table: fixed spacing issue #297 + +----------------------------------------------------------------------- + VERSION 0.5.62 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.5.62 + +Breaking Changes: +- close_popup: Now requires the name of the popup to be added. + +Fixes: +- primary window: Fixed issue in which primary window messed up other window + settings and flags + +----------------------------------------------------------------------- + VERSION 0.5.53 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.5.53 + +Updates: +- ImGui: Upgraded to v1.79 +- ImGuiFileDialog: Upgraded to v0.5.1 +- Python: Added python 3.9 support + +Fixes: +- start_dearpygui: Is now protected from trying to create a new dearpygui instance before closing the last one issue #289 +- workspace switching: Fixed workspace switching causing crashes #256 +- show_metrics: Fixed show_metrics warning/exception #293 + +----------------------------------------------------------------------- + VERSION 0.5.0 (10/20/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.5.0 + +Breaking Changes: +- show_source: "show_source" removed to prepare for text editor widget in 0.6 + +Updates: +- Standard Windows: metrics/debug/about/style/docs etc. are truely widgets now. +- MacOs: minimum now Mojava + +New Commands: +- Misc: Added "set_managed_column_width" command +- Misc: Added "get_managed_column_width" command +- Misc: Added "add_character_remap" command +- Misc: Added "set_primary_window" command +- Misc: Added "add_metrics_window" command +- Misc: Added "add_debug_window" command +- Misc: Added "add_about_window" command +- Misc: Added "add_style_window" command +- Misc: Added "add_documentation_window" command + +New Keywords: +- start_dearpygui: Added "primary_window" keyword +- add_checkbox: Added "enabled" keyword +- add_radio_button: Added "enabled" keyword +- add_listbox: Added "enabled" keyword +- add_combo: Added "enabled" keyword +- add_input_text: Added "enabled" keyword +- add_input_int: Added "enabled" keyword +- add_input_int2: Added "enabled" keyword +- add_input_int3: Added "enabled" keyword +- add_input_int4: Added "enabled" keyword +- add_input_float: Added "enabled" keyword +- add_input_float2: Added "enabled" keyword +- add_input_float3: Added "enabled" keyword +- add_input_float4: Added "enabled" keyword +- add_drag_int: Added "enabled" keyword +- add_drag_int2: Added "enabled" keyword +- add_drag_int3: Added "enabled" keyword +- add_drag_int4: Added "enabled" keyword +- add_drag_float: Added "enabled" keyword +- add_drag_float2: Added "enabled" keyword +- add_drag_float3: Added "enabled" keyword +- add_drag_float4: Added "enabled" keyword +- add_slider_int: Added "enabled" keyword +- add_slider_int2: Added "enabled" keyword +- add_slider_int3: Added "enabled" keyword +- add_slider_int4: Added "enabled" keyword +- add_slider_float: Added "enabled" keyword +- add_slider_float2: Added "enabled" keyword +- add_slider_float3: Added "enabled" keyword +- add_slider_float4: Added "enabled" keyword +- add_slider_***: Added "no_input" keyword +- add_slider_***: Added "clamped" keyword +- add_drag_***: Added "no_input" keyword +- add_drag***: Added "clamped" keyword + +Changes: +- show_metrics: Moved to simple module +- show_debug: Moved to simple module +- show_documentation: Moved to simple module +- show_style_editor: Moved to simple module +- show_about: Moved to simple module +- add_slider_***: Removed "on_enter" keyword +- add_drag_***: Removed "on_enter" keyword + +Fixes: +- Logger Widgets: can now be called asynronously #279 +- Docs: draw_polygon and draw_polyline, corrected type hinting from list of floats to list of FloatList +- Async: can now use lambdas + +----------------------------------------------------------------------- + VERSION 0.4.609 (10/14/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.609 + +New Commands: +- Items: Added "set_accelerator_callback" command + +Changes: +- Menus: Removed tip keyword #274 + +----------------------------------------------------------------------- + VERSION 0.4.605 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.605 + +Updated: +- Dear Imgui: Revert to Version 1.78 + +Fixes: +- File selector and dialog work again + +----------------------------------------------------------------------- + VERSION 0.4.602 (10/11/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.602 + +Updated: +- Python: Added Python 3.6 Support +- Dear Imgui: Upgraded to Version 1.79 + +Fixes: +- Windows: on_move flag was not being used +- Popup: mouse button keyword now works + +----------------------------------------------------------------------- + VERSION 0.4.5 (10/6/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.5 + +Updates: +- Stub File: stub file is now generated automatically + +Breaking Changes: +- Label Text: changed "value" keyword to "default_value" +- Progress Bar: changed "value" keyword to "default_value" + +Fixes: +- Input Text: Callback_data was not being sent +- Logger: Log messages only showed up after 2nd call +- Tabs: Fixed issue with items on tabs not lining up when using same_line +- Stub file: add_logger added to stub file +- Plots: reset_yticks was resetting x ticks +- Select Directory: fixed callback crash + +----------------------------------------------------------------------- + VERSION 0.4.4 (10/4/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.4 + +Breaking Changes: +- Selectable: changed "disabled" keyword to "enabled" + +New Commands: +- Items: Added "move_item" command +- Logger: Added "add_logger" command + +Changes: +- Examples: Moved examples to https://github.com/Pcothren/DearPyGui-Examples + +New Keywords: +- Line Series: Added "xy_data_format" #246 +- Scatter Series: Added "xy_data_format" #246 +- Button: Added "enabled" +- log: Added "logger" +- log_debug: Added "logger" +- log_error: Added "logger" +- log_info: Added "logger" +- log_warning: Added "logger" +- clear_log: Added "logger" +- get_log_level: Added "logger" +- set_log_level: Added "logger" +- input widgets: Added "readonly" #254 + +Fixes: +- set_table_data: Fixed when less data is passed in than number of columns, now overwrites remaining row items with empty data #259 +- Listbox: Fixed default "num_items" +- Combobox: Fixed hidden name issue #258 +- File Dialog: Fixed issue with typed filenames not returning #257 + +----------------------------------------------------------------------- + VERSION 0.4.3 (10/01/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.3 + +New Keywords: +- Text: Added "source" +- Text: Added "default_value" +- Collapsing Header: Added "open_on_double_click" +- Collapsing Header: Added "open_on_arrow" +- Collapsing Header: Added "leaf" +- Collapsing Header: Added "bullet" +- Tree Node: Added "open_on_double_click" +- Tree Node: Added "open_on_arrow" +- Tree Node: Added "leaf" +- Tree Node: Added "bullet" +- child: Added "autosize_x" +- child: Added "autosize_y" +- child: Added "no_scrollbar" +- child: Added "horizontal_scrollbar" +- child: Added "menubar" +- input_float: Added "step" +- input_float: Added "step_fast" + +Changes: +- Text: Text is wrapped by default now. + +Fixes: +- Collapsing Header: fixed "default_open" which did not work before +- Tree Node: fixed "default_open" which did not work before +- Stub File: added notation in definition for keyword only arguments + +----------------------------------------------------------------------- + VERSION 0.4.2 (9/30/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.2 + +Fixes: +- Standard Windows: fixed show/hide of standard windows +- Windows: fixed run time adding crashes when collapsing + +----------------------------------------------------------------------- + VERSION 0.4.1 (9/30/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.1 + +Fixes: +- Logger: show_item/hide_item now working +- ID Stack: unique labels withing a widget "path" not required anymore +- Demo: updates for colors + +----------------------------------------------------------------------- + VERSION 0.4.0 (9/28/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.4.0 + +Updates: +- ImPlot: upgraded to commit 90cbb56 + +Fixes: +- Other: Too many fixes to count. +- Threadpool: Fixed issue with some tasks going uncompleted +- Popups: Can now be added anywhere (don't have to be right after their parent) +- Tooltips: Can now be added anywhere (don't have to be right after their parent) +- Widgets: Can widths can now be negative (size from the right side of screen) + +Breaking Changes: +- Handlers: removed "handler" from all callbacks except resize +- Data Source: data_source keywords changed to "source" +- Tables: tables no longer use set/get value +- Modules: dearpygui module is now called core +- Modules: wrapper module is now called simple +- Line Series: Removed "fill" keyword (use the new shade series) +- Plots: Removed all flags in favor of keywords +- Plots: x/y_axis_name keyword now required +- Window: For the "add_window" command, we changed start_x,start_y + to x_pos, y_pos +- Window: For the "add_window" command, changed resizable keyword to no_resize +- Window: For the "add_window" command, changed title_bar keyword to no_title_bar +- Window: For the "add_window" command, changed movable keyword to no_move +- Images: Removed secondary data source from images +- Listbox: Changed "height" keyword to "num_items" +- Listbox: "items" keyword now required +- RadioButton: "items" keyword now required +- Combo: "items" keyword now required +- Dummy: "height" and "width" keyword now required +- Simple Plot: "autoscale" keyword removed + +New Commands: +- Demo: Added "show_demo" command to dearpygui.demo +- Widgets: Added "add_color_button" +- Plots: Added "add_drag_point" +- Plots: Added "add_drag_line" +- Plots: Added "delete_drag_line" +- Plots: Added "delete_drag_point" +- Plots: Added "add_annotation" +- Plots: Added "delete_annotation" +- Tables: Added "set_table_data" +- Tables: Added "get_table_data" +- Widgets: Added "add_value" +- Widgets: Added "incref_value" +- Widgets: Added "decref_value" +- Main Window: Added "set_main_window_pos" command #193 +- Inputs: Added "get_plot_mouse_pos" command #225 +- Widgets: Added "add_time_picker" command +- Widgets: Added "add_date_picker" command +- Widgets: Added "get_item_type" command +- Widgets: Added "configure_item" command +- Widgets: Added "get_item_configuration" command +- Widgets: Added "add_pie_series" command +- Plots: Added "add_shade_series" command +- Plots: Added "add_image_series" command +- Plots: Added "add_bar_series" command +- Plots: Added "add_error_series" command +- Plots: Added "add_heat_series" command +- Radio Button: Added "horizontal" keyword to radio button #215 +- Radio Button: Added "update_bounds" keyword to add_*_series commands +- Color Items: Alot of new flags +- Columns: Added "managed_columns" +- Columns: Added "add_columns" +- Columns: Added "add_next_column" +- Selectable: Added "span_columns" keyword + +----------------------------------------------------------------------- + VERSION 0.3.7 (9/14/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.3.7 + +Updates: +- ImPlot: upgraded to commit 4f0a09f + +New Commands: +- Widgets: Added "add_image_button" command +- Plots: Added "add_pie_chart" command +- Plots: Added "add_pie_chart_data" command +- Plots: Added "clear_pie_chart_data" command +- Plots: Added "add_stem_series" command + +Fixes: +- Threadpool: Fixed issue with threads freezing + + +----------------------------------------------------------------------- + VERSION 0.3.5 (9/10/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.3.5 + +New Commands: +- Menu Item: added "check" and "shortcut" keywords #186 +- Widgets: added "is_item_container" #203 +- Widgets: added "get_item_parent" #203 +- Widgets: added "is_item_shown" #203 + +Fixes: +- Other: Fixed get_window_pos for built-in windows #202 +- Other: Fixed get_window_width/height for built-in windows #202 + +----------------------------------------------------------------------- + VERSION 0.3.4 (9/9/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.3.4 + +New Commands: +- Widgets: Added "add_dummy" + +Fixes: +- Colors: Fixed crash when adding a color more than 4 items long +- Window: fixed window changing position while autosizing #196 + + +----------------------------------------------------------------------- + VERSION 0.3.1 (9/7/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.3.1 + +Breaking Changes: + +- Callbacks: All callbacks are now callables (not strings) +- Separator: Changed "add_seperator" to "add_separator" #188 + +Changes: +- Widgets: Changed "add_item_color style" to "set_item_color" + +New Commands: +- Widgets: Added "clear_item_color" +- App: Added "set_start_callback" #187 + +----------------------------------------------------------------------- + VERSION 0.2.0 (9/5/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.2.0 + +New Features: + +- Context Managers: You can now import dearpygui.wrappers to use context + manager versions of all containers + +Changes: + +- Widgets: All "add_widget" commands now return true on successful + adding or false. + +Breaking Changes: + +- Container Widgets: Replaced all "end_*" commands with a single "end" command + +----------------------------------------------------------------------- + VERSION 0.1.4 (9/4/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.4 + +-data source: quick fix to ref count issue that causes crash + +----------------------------------------------------------------------- + VERSION 0.1.3 (9/4/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.3 + +- Label Text: Quick fix to label_text setting #165 + +----------------------------------------------------------------------- + VERSION 0.1.2 (9/4/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.2 + +New Features: + +- Plots: Adding series will update an existing series if the names match. + No need to clear plot #163 + +New Commands: + +- Plot: Can now delete series in a plot "delete_series" #163 +- Main Window: Added "set_main_window_resizable" command #134 + +Fixes: + +- Themes: Fixed theme/custom settings inconsistency #165 +- Plot: Fixed automatic boundaries #170 +- Tips: Fixed weird tooltip behavior #171 +- Callback: Fixed mouse move callback for main window. + +----------------------------------------------------------------------- + VERSION 0.1.1 (9/3/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.1 + +Fixes: + +- Source Window: Fixed show_source error #166 + +----------------------------------------------------------------------- + VERSION 0.1.0 (9/2/2020) +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0 + +New Commands: + +- Events: Added "set_mouse_move_callback" #117 +- Callbacks: Added "set_exit_callback" #142 +- Callbacks: Added "set_mouse_release_callback" #161 + +Fixes: + +- Tabs: Fixed tabs being run-time addable +- Mouse/key Callbacks: Now work for builtin windows +- Active Window: Fixed names in debug + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 17 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta17 + +Fixes: + +- Plot: Adding new data to a plot bring all data into view +- MacOs: Fixed unthrottled event loop when minimized +- Linux: Fixed unthrottled event loop when minimized + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 16 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta16 + +Fixes: + +- MacOs: Fixed vsync issue mentioned on reddit. + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 15 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta15 + +New Commands: + +- Application: "set_vsync" now availble +- Standard Windows: "set_window_pos" now works for standard windows #146 +- Standard Windows: "get_window_pos" now works for standard windows #146 +- Standard Windows: "set_item_height" now works for standard windows #146 +- Standard Windows: "set_item_width" now works for standard windows #146 +- Standard Windows: "get_item_height" now works for standard windows #146 +- Standard Windows: "get_item_width" now works for standard windows #146 + +Fixes: + +- Main Window: Fixed set_window_size bug for MacOs/Linus #143 + + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 14 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta14 + +Fixes: + +- Data Source: Fixed seg faults related to data source #127 +- Debug Window: Fixed item deletion crash #128 +- Debug Window: Fixed debug item names #107 + +Breaking Changes: + +- Table Widget: Removed data source from table widget + + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 13 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta13 + +Fixes: + +- Images: Fixed memory leaks for image textures #122 +- Other: Fixed stop_dearpygui command #102 +- Labels: Fixed issue with set_label the same #120 + +New Commands: + +- Widgets: add "does_item_exist" command #119 +- Widgets: add "get_item_children" command #123 +- Widgets: add "get_all_items" command #123 +- Widgets: add "get_windows" command #123 + + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 12 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta12 + +Fixes: + +- Key/Mouse Callbacks: fixed issue where key/mouse callbacks were + sending there ID as the sender (and as a string). They know + send the active window as the sender and approriate information + through data. #108 + +New Commands: + +- Inputs: input/slider/drag now have an "on_enter" keyword to only + run their callbacks on enter key presses +- App: new command "stop_dearpygui" #102 +- Widgets: new command "set_item_label" #99 +- Widgets: new command "get_item_label" #99 + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 11 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta11 + +New Features: + +- Python 3.7 support + + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 10 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta10 + +Fixes: + +- Render Callback: fixed issue with debug window freezing main callback #95 +- Child Widget: child widget now shows a horizontal scrollbar if contents are too large #91 kinda +- Multiline: fixed issue where multiline did not work with other flags (i.e. readonly) #94 +- Logger: fixed issue with auto-scroll in logger (this is actually a Dear ImGui bug) #97 +- Data Storage: data storage is now updated at the end of each frame. No need to update by calling add_data again +- Other: fixed issue where imgui ini file was appearing + +New Commands: + +- Simple Plot: add simple plot now has a "data_source" keyword +- Table: add table now has a "data_source" keyword +- Drawing: delete_drawing_item + +New Features: + +- Data Storage: non primitive types can not by used within reaccessing data_storage + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 9 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta9 + +Fixes: + +- Tables: set_value as an empty list caused crash #93 +- Text: fixed truncation issue with large strings #92 +- Label Text: fixed truncation issue with large strings #92 + +New Commands: + +- Fonts: added custom_glyph_chars and custom_glyph_ranges to add_addition_font + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 8 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta8 + +Fixes: + +- File Dialog: Now returns file directory and file name (not path to file) + +New Commands: + +- Plots: new command add_area_series +- Other: new command set_main_window_title +- Other: new command is_dearpygui_running + +Breaking Changes: + +- File Dialog: File name extension is shown correctly now, fixing issue #88 + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 7 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta7 + +Fixes: + +- DataSources: Data sources now act consistent (added before or after a sourced widget) #56 + +New Commands: + +- Fonts: new command add_additional_font +- Styles: new command show_style_editor +- Styles: new command set_style_window_padding +- Styles: new command set_style_frame_padding +- Styles: new command set_style_item_spacing +- Styles: new command set_style_item_inner_spacing +- Styles: new command set_style_touch_extra_padding +- Styles: new command set_style_indent_spacing +- Styles: new command set_style_scrollbar_size +- Styles: new command set_style_grab_min_size +- Styles: new command set_style_window_border_size +- Styles: new command set_style_child_border_size +- Styles: new command set_style_popup_border_size +- Styles: new command set_style_frame_border_size +- Styles: new command set_style_tab_border_size +- Styles: new command set_style_window_rounding +- Styles: new command set_style_child_rounding +- Styles: new command set_style_frame_rounding +- Styles: new command set_style_popup_rounding +- Styles: new command set_style_scrollbar_rounding +- Styles: new command set_style_grab_rounding +- Styles: new command set_style_tab_rounding +- Styles: new command set_style_window_title_align +- Styles: new command set_style_window_menu_button_position +- Styles: new command set_style_color_button_position +- Styles: new command set_style_button_text_align +- Styles: new command set_style_selectable_text_align +- Styles: new command set_style_display_safe_area_padding +- Styles: new command set_style_global_alpha +- Styles: new command set_style_antialiased_lines +- Styles: new command set_style_antialiased_fill +- Styles: new command set_style_curve_tessellation_tolerance +- Styles: new command set_style_circle_segment_max_error + +- Styles: new command get_style_window_padding +- Styles: new command get_style_frame_padding +- Styles: new command get_style_item_spacing +- Styles: new command get_style_item_inner_spacing +- Styles: new command get_style_touch_extra_padding +- Styles: new command get_style_indent_spacing +- Styles: new command get_style_scrollbar_size +- Styles: new command get_style_grab_min_size +- Styles: new command get_style_window_border_size +- Styles: new command get_style_child_border_size +- Styles: new command get_style_popup_border_size +- Styles: new command get_style_frame_border_size +- Styles: new command get_style_tab_border_size +- Styles: new command get_style_window_rounding +- Styles: new command get_style_child_rounding +- Styles: new command get_style_frame_rounding +- Styles: new command get_style_popup_rounding +- Styles: new command get_style_scrollbar_rounding +- Styles: new command get_style_grab_rounding +- Styles: new command get_style_tab_rounding +- Styles: new command get_style_window_title_align +- Styles: new command get_style_window_menu_button_position +- Styles: new command get_style_color_button_position +- Styles: new command get_style_button_text_align +- Styles: new command get_style_selectable_text_align +- Styles: new command get_style_display_safe_area_padding +- Styles: new command get_style_global_alpha +- Styles: new command get_style_antialiased_lines +- Styles: new command get_style_antialiased_fill +- Styles: new command get_style_curve_tessellation_tolerance +- Styles: new command get_style_circle_segment_max_error + +Breaking Changes: + +- Themes: Changed change_style_item to set_theme_item +- Sliders: Removed power keyword from slider widgets +- Sliders: Changed default max value to 100 +- Drag: Removed power keyword from drag widgets +- Drag: Changed default max value to 100 +- Other: Changed get_marvel_version to get_dearpygui_version + + +----------------------------------------------------------------------- + VERSION 0.1.0 Beta 6 +----------------------------------------------------------------------- + +Decorated log: https://github.com/hoffstadt/DearPyGui/releases/tag/v0.1.0-beta6 + +Other Changes: + +- Drawing API: Fixed bug where draw_bezier_curve() with tags created weird results (Issue #73) (thanks mphirke) +- Window: Changed the return type of get_main_window_size() from [float, float] to [int, int] (Issue #75) diff --git a/.github/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md similarity index 100% rename from .github/CODE_OF_CONDUCT.md rename to docs/CODE_OF_CONDUCT.md diff --git a/.github/CONTRIBUTING.md b/docs/CONTRIBUTING.md similarity index 93% rename from .github/CONTRIBUTING.md rename to docs/CONTRIBUTING.md index 74d7729dc..e09e784ce 100644 --- a/.github/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -7,6 +7,7 @@ We would rather core library contributers hold off until we are finished making In the meantime the best ways to contribute: +- Add sample apps to _Examples_ directory - Improve the documentation - Improve the wiki - Offer feature suggestions diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index d0c3cbf10..000000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..948212413 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,191 @@ + + + +(This library is available under a free and permissive license however, if you Enjoy _Dear PyGui_ please consider becoming a [Sponsor](https://github.com/hoffstadt/DearPyGui/wiki/Sponsors)) + +![Python Version](https://img.shields.io/pypi/pyversions/dearpygui) +[![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) +[![Downloads](https://pepy.tech/badge/dearpygui)](https://pepy.tech/project/dearpygui) + +[![build status](https://github.com/hoffstadt/DearPyGui/workflows/Embedded%20Build/badge.svg?branch=master)](https://github.com/hoffstadt/DearPyGui/actions?workflow=Embedded%20Build) +[![static-analysis](https://github.com/hoffstadt/DearPyGui/workflows/static-analysis/badge.svg?branch=master)](https://github.com/hoffstadt/DearPyGui/actions?workflow=static-analysis) +[![Build status](https://ci.appveyor.com/api/projects/status/eypfn2lyuwfv8mel?svg=true)](https://ci.appveyor.com/project/hoffstadt/dearpygui) + +**Dear PyGui** is a **simple to use (but powerful) Python GUI framework**. _Dear PyGui_ is **NOT** a wrapping of **[Dear ImGui](https://github.com/ocornut/imgui)** in the normal sense. It is a library built with _Dear ImGui_ which simulates a traditional retained mode GUI (as opposed to _Dear ImGui_'s immediate mode paradigm). + +
![Themes](https://github.com/hoffstadt/DearPyGui/blob/assets/linuxthemes.PNG?raw=true) + +**Dear PyGui is fundamentally different than other Python GUI frameworks**. Under the hood, _Dear PyGui_ +uses the immediate mode paradigm and your computer's GPU to facilitate extremely dynamic interfaces. _Dear PyGui_ is currently supported on +the following platforms: + +| Platform | Rendering API | Newest Version | +|----------|---------------|----------------| +| **Windows 10** | _DirectX 11_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | +| **macOs** | _Metal_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | +| **Linux** | _OpenGL 3_ | [![PYPI](https://img.shields.io/pypi/v/dearpygui)](https://pypi.org/project/dearpygui/) | +| **Raspberry Pi 4** | _OpenGL ES_ | [![PYPI](https://img.shields.io/badge/pypi-v0.6.350-orange)](https://img.shields.io/badge/pypi-v0.6.350-orange) | + + +In the same manner Dear ImGui provides a simple way to create tools for game developers, _Dear PyGui_ provides a +simple way for python developers to **create quick and powerful GUIs for scripts**. + +| [Installing](#installation) - [Usage](#usage) - [Resources](#Resources) - [Support](#support) | +:----------------------------------------------------------: | +| [Features](#some-features) - [Sponsors](#sponsors) - [Credits](#credits) - [License](#license)| + +### Installation + +--- + +Ensure you have at least Python 3.6 64bit. + ``` + pip install dearpygui + or + pip3 install dearpygui + ``` + + +### Resources + + --- + + [![Chat on Discord](https://img.shields.io/discord/736279277242417272?logo=discord)](https://discord.gg/tyE7Gu4) +[![Reddit](https://img.shields.io/reddit/subreddit-subscribers/dearpygui?label=r%2Fdearpygui)](https://www.reddit.com/r/DearPyGui/) + +- [Documentation](https://github.com/hoffstadt/DearPyGui/wiki) comprehensive documentaion, tutorials, and examples. +- [Development Roadmap](https://github.com/hoffstadt/DearPyGui/projects/4) major future features and changes. +- [Feature Tracker](https://github.com/hoffstadt/DearPyGui/projects/5) all proposed new features. +- [Bug Tracker](https://github.com/hoffstadt/DearPyGui/projects/1) current bugs and issues. +- Internal Documentation: Run the `show_documentation` command from within the library to view a reference guide. +- Complete Demo: You can also view a mostly complete showcase of _Dear PyGui_ by running: +```python +from dearpygui.core import start_dearpygui +from dearpygui.demo import show_demo +show_demo() +start_dearpygui() +``` + + +### Usage + + --- + +Using _Dear PyGui_ is a simple as creating a python script like the one below: + +Code: +```Python +from dearpygui import core, simple + +def save_callback(sender, data): + print("Save Clicked") + +with simple.window("Example Window"): + core.add_text("Hello world") + core.add_button("Save", callback=save_callback) + core.add_input_text("string") + core.add_slider_float("float") + +core.start_dearpygui() +``` +Result: +
![BasicUsageExample](https://github.com/hoffstadt/DearPyGui/blob/assets/BasicUsageExample1.PNG?raw=true) + + +### Some Features + +--- + +#### Plotting/Graphing +_Dear PyGui_ includes a plotting API ([ImPlot](https://github.com/epezent/implot) Wrapping) + + + + + + + + + + + + +#### Node Editor +_Dear PyGui_ includes a node editor API ([imnodes](https://github.com/Nelarius/imnodes) Wrapping) +![](https://raw.githubusercontent.com/Nelarius/imnodes/master/img/imnodes.gif?token=ADH_jEpqbBrw0nH-BUmOip490dyO2CnRks5cVZllwA%3D%3D) + +#### Themes +_Dear PyGui_ currently includes 10 themes and you can create your own: +
![Themes](https://github.com/hoffstadt/DearPyGui/blob/assets/linuxthemes.PNG?raw=true) + +#### Canvas +_Dear PyGui_ includes a drawing API to create custom drawings, plot, and even 2D games. +
![BasicUsageExample](https://github.com/hoffstadt/DearPyGui/blob/assets/canvas.png?raw=true) + +#### Tools +_Dear PyGui_ includes several tools to help developers with _DearPyGui_ app development including built-in documentation, logging, source viewer, and other tools: +
![BasicUsageExample](https://github.com/hoffstadt/DearPyGui/blob/assets/tools.png?raw=true) + + +### Support + +If you are having issues or want to help, here are some places you can go: +- [Github Discussions](https://github.com/hoffstadt/DearPyGui/discussions/) +- [Discord Forum](https://discord.gg/tyE7Gu4) +- [Reddit](https://www.reddit.com/r/DearPyGui/) + +### Sponsors + +--- + +![GitHub Sponsors](https://img.shields.io/github/sponsors/hoffstadt?label=Github%20Sponsors) +![Open Collective](https://img.shields.io/opencollective/sponsors/dearpygui?label=Open%20Collective%20Sponsors) + + If you enjoy _Dear PyGui_ please consider becoming a [sponsor](https://github.com/hoffstadt/DearPyGui/wiki/Sponsors). + +Ongoing _Dear PyGui_ development is financially supported by users and private sponsors. + +These include: +* 🏢 [Anthony Tanbakuchi](https://github.com/kuchi) _Corporate Sponsor_ +* 🏆 [Dean Keinan](https://github.com/deankeinan) _Partner Sponsor_ +* 🏆 [何凌锋](https://github.com/Hedaozi) _Partner Sponsor_ +* 🏆 [Anthony Doupe](https://github.com/Atlamillias) _Partner Sponsor_ +* 🏆 [Ray Heasman](https://github.com/rheasman) _Partner Sponsor_ +* 🏆 [Marco Studer](https://github.com/Mstpyt) _Partner Sponsor_ +* 🥇 [Caden Bloxham](https://github.com/cubic-unit) _Gold Sponsor_ +* 🥇 [Michael Kadziela](https://github.com/Innominus) _Gold Sponsor_ +* 🥇 [Yan Zaretskiy](https://github.com/mindv0rtex) _Gold Sponsor_ +* 🥇 [Trinnik](https://github.com/Trinnik) _Gold Sponsor_ +* 🥇 [Derek Barker](https://github.com/LordOdin) _Gold Sponsor_ +* 🥇 [Barney Mannerings](https://github.com/barnabee) _Gold Sponsor_ +* 🥇 [Leron Gray](https://github.com/daddycocoaman) _Gold Sponsor_ +* 🥇 [RB Blackstone](https://github.com/RBBlackstone) _Gold Sponsor_ + + +Thank you to all other [sponsors](https://github.com/hoffstadt/DearPyGui/wiki/Sponsors) for keeping this project moving forward! + + + +### Credits + +--- + +Developed by [Jonathan Hoffstadt](https://github.com/hoffstadt), [Preston Cothren](https://github.com/Pcothren), and every direct or indirect contributor. + +[Omar Cornut](http://www.miracleworld.net/) for all his incredible work on [Dear ImGui](https://github.com/ocornut/imgui). + +[Evan Pezent](http://evanpezent.com/) for all his work on [ImPlot](https://github.com/epezent/implot) + +[Johann Muszynski](https://github.com/Nelarius) for all of his work on [imnodes](https://github.com/Nelarius/imnodes) + +### License + +--- + +_Dear PyGui_ is licensed under the [MIT License](https://github.com/hoffstadt/DearPyGui/blob/master/LICENSE). diff --git a/docs/TODO.txt b/docs/TODO.txt new file mode 100644 index 000000000..cca8052f5 --- /dev/null +++ b/docs/TODO.txt @@ -0,0 +1,16 @@ +Dear PyGui +ISSUES & TODO LIST + +Issue numbers (#) refer to github issues listed at https://github.com/RaylockLLC/DearPyGui/issues +The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point they usually exist on the github issue tracker). +It's mostly a bunch of personal notes, probably incomplete. Feel free to query if you have any questions. + +- window class: alot of work needs to happen here to clean this up. +- doc: work on the CONTRIBUTING.md file +- doc/wiki: work on the wiki https://github.com/RaylockLLC/DearPyGui/wiki +- custom widgets: add a fully supported custom widget API to allow users to make their own widgets more easily +- misc: deal with deprecation of codecvt +- mvPythonTranslator: make commands more consistent, more like ToPyPairII +- add_texture: fix alpha channel mess +- mac: handle retina display nonsense +- tables: add automatic placement of columns \ No newline at end of file diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 000000000..c74188174 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-slate \ No newline at end of file diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 9534b0181..000000000 --- a/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=source -set BUILDDIR=build - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index 3bde56929..000000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -alabaster==0.7.12 -Sphinx==4.1.2 -sphinx-rtd-theme==0.5.2 -sphinx-copybutton==0.4.0 -myst_parser -Pillow \ No newline at end of file diff --git a/docs/source/about/repo-info.rst b/docs/source/about/repo-info.rst deleted file mode 100644 index 1d5251b20..000000000 --- a/docs/source/about/repo-info.rst +++ /dev/null @@ -1,102 +0,0 @@ -Project Information -=================== - -.. meta:: - :description lang=en: Overview of the project and all the badges - ------------- - -**Socials:** - -|inline sub for discord| | |inline sub for reddit| | `Github Discussions`_ | `Youtube`_ | - -.. |inline sub for discord| - image:: https://img.shields.io/discord/736279277242417272?logo=discord - :target: https://discord.com/invite/tyE7Gu4 - -.. |inline sub for reddit| - image:: https://img.shields.io/reddit/subreddit-subscribers/dearpygui?label=r%2Fdearpygui - :target: https://www.reddit.com/r/DearPyGui/ - -.. _Github Discussions: https://github.com/hoffstadt/DearPyGui/discussions -.. _Youtube: https://www.youtube.com/channel/UCF4mg5-bD7VUFAhAiyf7v0g - - - ------------- - -**Funding:** - -.. image:: https://img.shields.io/github/sponsors/hoffstadt?label=Github%20Sponsors - :target: https://github.com/sponsors/hoffstadt -.. image:: https://img.shields.io/opencollective/sponsors/dearpygui?label=Open%20Collective%20Sponsors - :target: https://opencollective.com/DearPyGui -.. image:: https://img.buymeacoffee.com/button-api/?text=Buy us a coffee&emoji=&slug=DearPyGui&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff - :target: https://www.buymeacoffee.com/DearPyGui - ------------- - -**Repository:** - -.. image:: https://img.shields.io/github/languages/code-size/hoffstadt/dearpygui?label=Repo%20Size -.. image:: https://img.shields.io/github/languages/count/hoffstadt/dearpygui -.. image:: https://pepy.tech/badge/dearpygui - :target: https://pepy.tech/project/dearpygui -.. image:: https://img.shields.io/github/contributors/hoffstadt/DearPyGui - :target: https://discord.com/invite/tyE7Gu4 - ------------- - -**Issues:** - -.. image:: https://img.shields.io/github/issues-raw/hoffstadt/DearPyGui -.. image:: https://img.shields.io/github/issues-closed-raw/hoffstadt/DearPyGui -.. image:: https://img.shields.io/github/issues/hoffstadt/DearPyGui/bug?label=issues%3A%20bug - ------------- - -**CI Builds:** - -.. image:: https://github.com/hoffstadt/DearPyGui/workflows/Embedded%20Build/badge.svg?branch=master - :target: https://github.com/hoffstadt/DearPyGui/actions?workflow=Embedded%20Build - ------------- - -**CI Static Analysis:** - -.. image:: https://github.com/hoffstadt/DearPyGui/workflows/static-analysis/badge.svg?branch=master - :target: https://github.com/hoffstadt/DearPyGui/actions?workflow=static-analysis - ------------- - -**Platforms:** - -+--------------------+---------------+------------------+ -| Header row, column | Rendering API | Latest Version | -| (header rows ) | | | -+====================+===============+==================+ -| **Windows 10** | DirectX 11 | |windows| |wheel|| -+--------------------+---------------+------------------+ -| **macOs** | Metal | |mac| |wheel| | -+--------------------+---------------+------------------+ -| **Linux** | OpenGL 3 | |linux| |wheel| | -+--------------------+---------------+------------------+ -| **Raspberry Pi 4** | OpenGL ES | |rb pi| |wheel| | -+--------------------+---------------+------------------+ - -.. |wheel| - image:: https://img.shields.io/pypi/format/dearpygui - :target: https://pypi.org/project/dearpygui/ -.. |windows| - image:: https://img.shields.io/pypi/v/dearpygui - :target: https://pypi.org/project/dearpygui/ -.. |mac| - image:: https://img.shields.io/pypi/v/dearpygui - :target: https://discord.com/invite/tyE7Gu4 -.. |linux| - image:: https://img.shields.io/pypi/v/dearpygui - :target: https://pypi.org/project/dearpygui/ -.. |rb pi| - image:: https://img.shields.io/badge/pypi-v1.1-blue - :target: https://img.shields.io/badge/pypi-v1.1-blue)](https://img.shields.io/badge/pypi-v1.1-blue - diff --git a/docs/source/about/what-why.rst b/docs/source/about/what-why.rst deleted file mode 100644 index ca4bdd885..000000000 --- a/docs/source/about/what-why.rst +++ /dev/null @@ -1,34 +0,0 @@ -What & Why -========== - -.. meta:: - :description lang=en: Information about Dear PyGui and the developers. - -What is DPG ------------ - -DPG is a simple, bloat-free, and powerful Python GUI framework. - -DPG is built with *Dear ImGui* and other extensions in order to create a unique -retained mode API, as opposed to Dear ImGui's immediate mode paradigm. - -Under the hood, DPG uses the immediate mode paradigm allowing for extremely -dynamic interfaces. Similar to *PyQt*, DPG does not use native widgets -but instead draws the widgets using your computer's graphics -card (using Directx11, Metal, and Vulkan rendering APIs). - -In the same manner *Dear ImGui* provides a simple way to create tools -for game developers, DPG provides a simple way for python -developers to create quick and powerful GUIs for scripts. - -Why use DPG ------------ - -When compared with other Python GUI libraries DPG is unique with: - -* GPU rendering -* Multithreaded -* Highly customizable -* Built-in developer tools: theme inspection, resource inspection, runtime metrics -* 70+ widgets with hundreds of widget combinations -* Detailed documentation, examples and support diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 2c233334a..000000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,59 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# This file only contains a selection of the most common options. For a full -# list see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Path setup -------------------------------------------------------------- - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import sphinx_rtd_theme - - -# -- Project information ----------------------------------------------------- - -project = 'Dear PyGui' -copyright = '2026, Jonathan Hoffstadt and Preston Cothren' -author = 'Jonathan Hoffstadt and Preston Cothren' - - -# -- General configuration --------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "myst_parser", - "sphinx.ext.autodoc", - "sphinx.ext.viewcode", - "sphinx.ext.napoleon", - "sphinx.ext.autosectionlabel", - "sphinx_copybutton", -] - -suppress_warnings = ["myst.header"] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = [] - - -# -- Options for HTML output ------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = 'sphinx_rtd_theme' -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] - -# 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'] \ No newline at end of file diff --git a/docs/source/documentation/container-context-manager.rst b/docs/source/documentation/container-context-manager.rst deleted file mode 100644 index fe87f6a37..000000000 --- a/docs/source/documentation/container-context-manager.rst +++ /dev/null @@ -1,230 +0,0 @@ -Containers & Context Managers -============================= - -We have added context managers as helpers for most container items. - -.. seealso:: For more detail :doc:`../documentation/container-stack` - - -+---------------------------+----------------------------------+ -| Core Command | Context Manager | -+---------------------------+----------------------------------+ -| **add_table** | **with table(...):** | -+---------------------------+----------------------------------+ -| **add_table_row** | **with table_row(...):** | -+---------------------------+----------------------------------+ -| **add_window** | **with window(...):** | -+---------------------------+----------------------------------+ -| **add_menu_bar** | **with menu_bar(...):** | -+---------------------------+----------------------------------+ -| **add_child** | **with child(...):** | -+---------------------------+----------------------------------+ -| **add_clipper** | **with clipper(...):** | -+---------------------------+----------------------------------+ -| **add_collapsing_header** | **with collapsing_header(...):** | -+---------------------------+----------------------------------+ -| **add_colormap_registry** | **with colormap_registry(...):** | -+---------------------------+----------------------------------+ -| **add_group** | **with group(...):** | -+---------------------------+----------------------------------+ -| **add_node** | **with node(...):** | -+---------------------------+----------------------------------+ -| **add_node_attribute** | **with node_attribute(...):** | -+---------------------------+----------------------------------+ -| **add_node_editor** | **with node_editor(...):** | -+---------------------------+----------------------------------+ -| **add_staging_container** | **with staging_container(...):** | -+---------------------------+----------------------------------+ -| **add_tab_bar** | **with tab_bar(...):** | -+---------------------------+----------------------------------+ -| **add_tab** | **with tab(...):** | -+---------------------------+----------------------------------+ -| **add_tree_node** | **with tree_node(...):** | -+---------------------------+----------------------------------+ -| **add_tooltip** | **with tooltip(...):** | -+---------------------------+----------------------------------+ -| **add_popup** | **with popup(...):** | -+---------------------------+----------------------------------+ -| **add_drag_payload** | **with payload(...):** | -+---------------------------+----------------------------------+ -| **add_drawlist** | **with drawlist(...):** | -+---------------------------+----------------------------------+ -| **add_draw_layer** | **with draw_layer(...):** | -+---------------------------+----------------------------------+ -| **add_viewport_drawlist** | **with viewport_drawlist(...):** | -+---------------------------+----------------------------------+ -| **add_file_dialog** | **with file_dialog(...):** | -+---------------------------+----------------------------------+ -| **add_filter_set** | **with filter_set(...):** | -+---------------------------+----------------------------------+ -| **add_font** | **with font(...):** | -+---------------------------+----------------------------------+ -| **add_font_registry** | **with font_registry(...):** | -+---------------------------+----------------------------------+ -| **add_handler_registry** | **with handler_registry(...):** | -+---------------------------+----------------------------------+ -| **add_plot** | **with plot(...):** | -+---------------------------+----------------------------------+ -| **add_subplots** | **with subplots(...):** | -+---------------------------+----------------------------------+ -| **add_texture_registry** | **with texture_registry(...):** | -+---------------------------+----------------------------------+ -| **add_value_registry** | **with value_registry(...):** | -+---------------------------+----------------------------------+ -| **add_theme** | **with theme(...):** | -+---------------------------+----------------------------------+ -| **add_item_pool** | **with item_pool(...):** | -+---------------------------+----------------------------------+ -| **add_template_registry** | **with template_registry(...):** | -+---------------------------+----------------------------------+ - - -Benefits: ---------- - -1. Automatically push containers to container stack. -2. Automatically pop containers off container stack. -3. More structured, readable code. - -Context Managers: ------------------ - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Main"): - - with dpg.menu_bar(): - with dpg.menu(label="Themes"): - dpg.add_menu_item(label="Dark") - dpg.add_menu_item(label="Light") - dpg.add_menu_item(label="Classic") - - with dpg.menu(label="Other Themes"): - dpg.add_menu_item(label="Purple") - dpg.add_menu_item(label="Gold") - dpg.add_menu_item(label="Red") - - with dpg.menu(label="Tools"): - dpg.add_menu_item(label="Show Logger") - dpg.add_menu_item(label="Show About") - - with dpg.menu(label="Oddities"): - dpg.add_button(label="A Button") - dpg.add_simple_plot(label="Menu plot", default_value=(0.3, 0.9, 2.5, 8.9), height=80) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Explicit Parental Assignment (using UUIDs): -------------------------------------------- - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - w = dpg.add_window(label="Main") - - mb = dpg.add_menu_bar(parent=w) - - themes = dpg.add_menu(label="Themes", parent=mb) - dpg.add_menu_item(label="Dark", parent=themes) - dpg.add_menu_item(label="Light", parent=themes) - - other_themes = dpg.add_menu(label="Other Themes", parent=themes) - dpg.add_menu_item(label="Purple", parent=other_themes) - dpg.add_menu_item(label="Gold", parent=other_themes) - dpg.add_menu_item(label="Red", parent=other_themes) - - tools = dpg.add_menu(label="Tools", parent=mb) - dpg.add_menu_item(label="Show Logger", parent=tools) - dpg.add_menu_item(label="Show About", parent=tools) - - oddities = dpg.add_menu(label="Oddities", parent=mb) - dpg.add_button(label="A Button", parent=oddities) - dpg.add_simple_plot(label="A menu plot", default_value=(0.3, 0.9, 2.5, 8.9), height=80, parent=oddities) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Explicit Parental Assignment (using aliases): ---------------------------------------------- - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.add_window(label="Main", tag="w") - - dpg.add_menu_bar(parent="w", tag="mb") - - dpg.add_menu(label="Themes", parent="mb", tag="themes") - dpg.add_menu_item(label="Dark", parent="themes") - dpg.add_menu_item(label="Light", parent="themes") - - dpg.add_menu(label="Other Themes", parent="themes", tag="other_themes") - dpg.add_menu_item(label="Purple", parent="other_themes") - dpg.add_menu_item(label="Gold", parent="other_themes") - dpg.add_menu_item(label="Red", parent="other_themes") - - dpg.add_menu(label="Tools", parent="mb", tag="tools") - dpg.add_menu_item(label="Show Logger", parent="tools") - dpg.add_menu_item(label="Show About", parent="tools") - - dpg.add_menu(label="Oddities", parent="mb", tag="Oddities") - dpg.add_button(label="A Button", parent="Oddities") - dpg.add_simple_plot(label="A menu plot", default_value=(0.3, 0.9, 2.5, 8.9), height=80, parent="Oddities") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Container Stack Operations: ---------------------------- - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.push_container_stack(dpg.add_window(label="Main")) - - dpg.push_container_stack(dpg.add_menu_bar()) - - dpg.push_container_stack(dpg.add_menu(label="Themes")) - dpg.add_menu_item(label="Dark") - dpg.add_menu_item(label="Light") - dpg.pop_container_stack() - - dpg.push_container_stack(dpg.add_menu(label="Tools")) - dpg.add_menu_item(label="Show Logger") - dpg.add_menu_item(label="Show About") - dpg.pop_container_stack() - - # remove menu_bar from container stack - dpg.pop_container_stack() - - # remove window from container stack - dpg.pop_container_stack() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/container-slots.rst b/docs/source/documentation/container-slots.rst deleted file mode 100644 index 37d2507b9..000000000 --- a/docs/source/documentation/container-slots.rst +++ /dev/null @@ -1,84 +0,0 @@ -Container Slots & Children -========================== - -Most items can have child items. Items -can only be children to valid **container** items. -Some related commands can be found below: - -:py:func:`is_item_container ` - checks if an item is a container type -:py:func:`get_item_slot ` - returns the item's slot -:py:func:`get_item_parent ` - returns the item's parent UUID -:py:func:`get_item_children ` - returns an item’s children -:py:func:`reorder_items ` - reorders children in a single call -:py:func:`move_item_up ` - moves an item up within its slot -:py:func:`move_item_down ` - moves an item down within its slot -:py:func:`move_item ` - moves an item between containers -:py:func:`set_item_children ` - unstaging a stage into an item's children slot - -Slots ------ - -Items are stored in target slots within their parent container. -Below is the breakdown of slots: - -Slot 0: - **mvFileExtension**, **mvFontRangeHint**, **mvNodeLink**, **mvAnnotation**, **mvDragLine**, **mvDragRect**, **mvDragPoint**, **mvLegend**, **mvTableColumn** -Slot 1: - Most items -Slot 2: - Draw items -Slot 3: - **mvDragPayload** - -To query what slot an item belongs to, use -:py:func:`get_item_slot `. - -Basic Example -------------- - -Below is a simple example that demonstrates some of the above: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="about", width=400, height=400): - dpg.add_button(label="Press me") - dpg.draw_line((0, 10), (100, 100), color=(255, 0, 0, 255), thickness=1) - - # print children - print(dpg.get_item_children(dpg.last_root())) - - # print children in slot 1 - print(dpg.get_item_children(dpg.last_root(), 1)) - - # check draw_line's slot - print(dpg.get_item_slot(dpg.last_item())) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. note:: - Use the *slot* keyword with - :py:func:`get_item_children ` - to return just a specific slot. - -.. note:: - Use the *slot* and *children_only* keywords with - :py:func:`delete_item ` - to delete a specific slot of children from a parent. - diff --git a/docs/source/documentation/container-stack.rst b/docs/source/documentation/container-stack.rst deleted file mode 100644 index ea976a638..000000000 --- a/docs/source/documentation/container-stack.rst +++ /dev/null @@ -1,110 +0,0 @@ -Container Stack -=============== - -Unless an item is a root item, -all items need to belong to a valid container. -An item's parent is deduced through the following process: - -1. If item is a root, no parent needed; finished. -2. Check *before* keyword, if used skip to 5 using parent of "before" item. -3. Check *parent* keyword, if used skip to 5. -4. Check container stack, if used skip to 5. -5. Check if parent is compatible. -6. Check if parent accepts. -7. If runtime, add item using runtime methods; finished. -8. If startup, add item using startup methods; finished. - -Container items can be manually pushed onto the container stack using -:py:func:`push_container_stack ` -and popped off using -:py:func:`pop_container_stack `. - -This process is automated when using :doc:`../documentation/container-context-manager`. -Below is a simple example demonstrating manual stack operations: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.push_container_stack(dpg.add_window(label="Tutorial")) - - dpg.push_container_stack(dpg.add_menu_bar()) - - dpg.push_container_stack(dpg.add_menu(label="Themes")) - dpg.add_menu_item(label="Dark") - dpg.add_menu_item(label="Light") - dpg.pop_container_stack() - - # remove menu_bar from container stack - dpg.pop_container_stack() - - # remove window from container stack - dpg.pop_container_stack() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Explicit Parental Assignment ----------------------------- - -Parents can be explicitly assigned using the *parent* keyword. -This is most often used for adding new items at runtime. -The above example can be shown again below using explicit parent assignment: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.add_window(label="Tutorial", tag="window") - - dpg.add_menu_bar(parent="window", tag="menu_bar") - - dpg.add_menu(label="Themes", parent="menu_bar", tag="themes") - dpg.add_menu_item(label="Dark", parent="themes") - dpg.add_menu_item(label="Light", parent="themes") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - -Context Managers ----------------- - -Context managers can be used to simplify the above example. -All the context managers can be found in the -:doc:`../documentation/container-context-manager` -but a simple example can be found below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - with dpg.menu_bar(): - with dpg.menu(label="Themes"): - dpg.add_menu_item(label="Dark") - dpg.add_menu_item(label="Light") - dpg.add_menu_item(label="Classic") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Benefits** -1. Automatically push container to container stack. -2. Automatically pop container off container stack. -3. More structured, readable code. \ No newline at end of file diff --git a/docs/source/documentation/drawing-api.rst b/docs/source/documentation/drawing-api.rst deleted file mode 100644 index 70fb8e9e5..000000000 --- a/docs/source/documentation/drawing-api.rst +++ /dev/null @@ -1,398 +0,0 @@ -Drawing-API -=========== - -DPG has a low level drawing API that is well suited for primitive drawing, -custom widgets or even dynamic drawings. - -Drawing commands can be added to containers like drawlist, -viewport_drawlist, or a window. - -A drawlist item is created by calling -:py:func:`add_drawlist ` -then items can be added by calling their respective draw commands. -The origin for the drawing is in the top left and the y-axis points down. - -The coordinate system is right-handed with the x axis point left, y axis point down, -and z axis pointing into the screen. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.drawlist(width=300, height=300): # or you could use dpg.add_drawlist and set parents manually - - dpg.draw_line((10, 10), (100, 100), color=(255, 0, 0, 255), thickness=1) - dpg.draw_text((0, 0), "Origin", color=(250, 250, 250, 255), size=15) - dpg.draw_arrow((50, 70), (100, 65), color=(0, 200, 255), thickness=1, size=10) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/draw_items.PNG - -Layers ------- - -Drawlists can also contain layers. Layers are an effective way to group -drawing items for better control of hiding, Z ordering, etc. - -**New in 1.1**. Layers can be used to assist with some 3D operations. See "3D Operations" section below. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def toggle_layer2(sender): - show_value = dpg.get_value(sender) - dpg.configure_item("layer2", show=show_value) - - with dpg.window(label="Tutorial"): - dpg.add_checkbox(label="show layer", callback=toggle_layer2, default_value=True) - - with dpg.drawlist(width=300, height=300): - - with dpg.draw_layer(): - dpg.draw_line((10, 10), (100, 100), color=(255, 0, 0, 255), thickness=1) - dpg.draw_text((0, 0), "Origin", color=(250, 250, 250, 255), size=15) - dpg.draw_arrow((50, 70), (100, 65), color=(0, 200, 255), thickness=1, size=10) - - with dpg.draw_layer(tag="layer2"): - dpg.draw_line((10, 60), (100, 160), color=(255, 0, 0, 255), thickness=1) - dpg.draw_arrow((50, 120), (100, 115), color=(0, 200, 255), thickness=1, size=10) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - - -Images ------- - -Drawlists can display images -of types PNG, JPEG, or BMP (See -:doc:`../documentation/textures` for -more detail). Images are added using draw_image. - -Using the keywords **pmin** and **pmax** we can define the -upper left and lower right area of the rectangle that the image -will be drawn onto the canvas. The image will scale to fit the specified area. - -With keywords **uv_min** and **uv_max** we can specify normalized texture -coordinates to use just a portion of the area on the image. The -default of uv_min = [0,0] and uv_max = [1,1] will display the entire -image while uv_min = [0,0] uv_max = [0.5,0.5] will only show the first -quarter of the drawing. - -To be able to demonstrate these features you must update the directory -to that of an image on your computer, such as -`SpriteMapExample.png `_. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - width, height, channels, data = dpg.load_image('SpriteMapExample.png') # 0: width, 1: height, 2: channels, 3: data - - with dpg.texture_registry(): - dpg.add_static_texture(width, height, data, tag="image_id") - - with dpg.window(label="Tutorial"): - - with dpg.drawlist(width=700, height=700): - - dpg.draw_image("image_id", (0, 400), (200, 600), uv_min=(0, 0), uv_max=(1, 1)) - dpg.draw_image("image_id", (400, 300), (600, 500), uv_min=(0, 0), uv_max=(0.5, 0.5)) - dpg.draw_image("image_id", (0, 0), (300, 300), uv_min=(0, 0), uv_max=(2.5, 2.5)) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/draw_images.PNG - -Viewport and Window -------------------- - -You can also use all the same draw_* drawings commands with a -window as the parent. Similarly you can draw to the viewport foreground -or background by using a viewport_drawlist. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - # creating font and back viewport drawlists - with dpg.viewport_drawlist(): - dpg.draw_circle((100, 100), 25, color=(255, 255, 255, 255)) - - dpg.add_viewport_drawlist(front=False, tag="viewport_back") - - dpg.draw_circle((200, 200), 25, color=(255, 255, 255, 255), parent="viewport_back") - - with dpg.window(label="Tutorial", width=300, height=300): - dpg.add_text("Move the window over the drawings to see the effects.", wrap=300) - dpg.draw_circle((100, 100), 25, color=(255, 255, 255, 255)) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/draw_viewport.gif - -Scene Graph ------------ - -**New in 1.1**. For more complex drawing, you can utilize a **draw_node** item. A draw node is used -to associate a transformation matrix with a group of draw items. You can use **apply_transform** -to apply a transformation matrix to a node. This matrix will be used to multiply each child draw item's -points. If a child is another draw node, the matricies will concatenate. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - import math - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - with dpg.window(label="tutorial", width=550, height=550): - - with dpg.drawlist(width=500, height=500): - - with dpg.draw_node(tag="root node"): - dpg.draw_circle([0, 0], 150, color=[0, 255, 0]) # inner planet orbit - dpg.draw_circle([0, 0], 200, color=[0, 255, 255]) # outer planet orbit - dpg.draw_circle([0, 0], 15, color=[255, 255, 0], fill=[255, 255, 0]) # sun - - with dpg.draw_node(tag="planet node 1"): - dpg.draw_circle([0, 0], 10, color=[0, 255, 0], fill=[0, 255, 0]) # inner planet - dpg.draw_circle([0, 0], 25, color=[255, 0, 255]) # moon orbit path - - with dpg.draw_node(tag="planet 1, moon node"): - dpg.draw_circle([0, 0], 5, color=[255, 0, 255], fill=[255, 0, 255]) # moon - - with dpg.draw_node(tag="planet node 2"): - dpg.draw_circle([0, 0], 10, color=[0, 255, 255], fill=[0, 255, 255]) # outer planet - dpg.draw_circle([0, 0], 25, color=[255, 0, 255]) # moon 1 orbit path - dpg.draw_circle([0, 0], 45, color=[255, 255, 255]) # moon 2 orbit path - - with dpg.draw_node(tag="planet 2, moon 1 node"): - dpg.draw_circle([0, 0], 5, color=[255, 0, 255], fill=[255, 0, 255]) # moon 1 - - with dpg.draw_node(tag="planet 2, moon 2 node"): - dpg.draw_circle([0, 0], 5, color=[255, 255, 255], fill=[255, 255, 255]) # moon 2 - - planet1_distance = 150 - planet1_angle = 45.0 - planet1_moondistance = 25 - planet1_moonangle = 45 - - planet2_distance = 200 - planet2_angle = 0.0 - planet2_moon1distance = 25 - planet2_moon1angle = 45 - planet2_moon2distance = 45 - planet2_moon2angle = 120 - - dpg.apply_transform("root node", dpg.create_translation_matrix([250, 250])) - dpg.apply_transform("planet node 1", dpg.create_rotation_matrix(math.pi*planet1_angle/180.0 , [0, 0, -1])*dpg.create_translation_matrix([planet1_distance, 0])) - dpg.apply_transform("planet 1, moon node", dpg.create_rotation_matrix(math.pi*planet1_moonangle/180.0 , [0, 0, -1])*dpg.create_translation_matrix([planet1_moondistance, 0])) - dpg.apply_transform("planet node 2", dpg.create_rotation_matrix(math.pi*planet2_angle/180.0 , [0, 0, -1])*dpg.create_translation_matrix([planet2_distance, 0])) - dpg.apply_transform("planet 2, moon 1 node", dpg.create_rotation_matrix(math.pi*planet2_moon1distance/180.0 , [0, 0, -1])*dpg.create_translation_matrix([planet2_moon1distance, 0])) - dpg.apply_transform("planet 2, moon 2 node", dpg.create_rotation_matrix(math.pi*planet2_moon2angle/180.0 , [0, 0, -1])*dpg.create_translation_matrix([planet2_moon2distance, 0])) - - dpg.show_viewport() - while dpg.is_dearpygui_running(): - dpg.render_dearpygui_frame() - - dpg.destroy_context() - -3D Operations -------------- - -**New in 1.1**. Version *1.1* added 3 new options to layers, **perspective_divide**, -**depth_clipping**, and **cull_mode**. - -When perspective divide is set to **True**, the x, y, and z components of each point -are divided by the w component after transformation. - -When depth clipping is set to **True**, points will be clipped when they are outside the clip -space set using **set_clip_space**. Setting the clip space will scale and transform points. Scaling -is based on normalized coordinates (use perspective or othographic matrices). - -Cull mode is used to activate front/back face culling. - -Matrices are column major. Post-multiplication is used, for example to scale, then rotate, then transform -you use: Transform = Translate * Rotate * Scale. - -The following matrix helper functions are provided: -- **create_rotation_matrix** -- **create_translation_matrix** -- **create_scale_matrix** -- **create_lookat_matrix** -- **create_perspective_matrix** -- **create_orthographic_matrix** -- **create_fps_matrix** - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - import math - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - size = 5 - verticies = [ - [-size, -size, -size], # 0 near side - [ size, -size, -size], # 1 - [-size, size, -size], # 2 - [ size, size, -size], # 3 - [-size, -size, size], # 4 far side - [ size, -size, size], # 5 - [-size, size, size], # 6 - [ size, size, size], # 7 - [-size, -size, -size], # 8 left side - [-size, size, -size], # 9 - [-size, -size, size], # 10 - [-size, size, size], # 11 - [ size, -size, -size], # 12 right side - [ size, size, -size], # 13 - [ size, -size, size], # 14 - [ size, size, size], # 15 - [-size, -size, -size], # 16 bottom side - [ size, -size, -size], # 17 - [-size, -size, size], # 18 - [ size, -size, size], # 19 - [-size, size, -size], # 20 top side - [ size, size, -size], # 21 - [-size, size, size], # 22 - [ size, size, size], # 23 - ] - - colors = [ - [255, 0, 0, 150], - [255, 255, 0, 150], - [255, 255, 255, 150], - [255, 0, 255, 150], - [ 0, 255, 0, 150], - [ 0, 255, 255, 150], - [ 0, 0, 255, 150], - [ 0, 125, 0, 150], - [128, 0, 0, 150], - [128, 70, 0, 150], - [128, 255, 255, 150], - [128, 0, 128, 150] - ] - - with dpg.window(label="tutorial", width=550, height=550): - - with dpg.drawlist(width=500, height=500): - - with dpg.draw_layer(tag="main pass", depth_clipping=True, perspective_divide=True, cull_mode=dpg.mvCullMode_Back): - - with dpg.draw_node(tag="cube"): - - dpg.draw_triangle(verticies[1], verticies[2], verticies[0], color=[0,0,0.0], fill=colors[0]) - dpg.draw_triangle(verticies[1], verticies[3], verticies[2], color=[0,0,0.0], fill=colors[1]) - dpg.draw_triangle(verticies[7], verticies[5], verticies[4], color=[0,0,0.0], fill=colors[2]) - dpg.draw_triangle(verticies[6], verticies[7], verticies[4], color=[0,0,0.0], fill=colors[3]) - dpg.draw_triangle(verticies[9], verticies[10], verticies[8], color=[0,0,0.0], fill=colors[4]) - dpg.draw_triangle(verticies[9], verticies[11], verticies[10], color=[0,0,0.0], fill=colors[5]) - dpg.draw_triangle(verticies[15], verticies[13], verticies[12], color=[0,0,0.0], fill=colors[6]) - dpg.draw_triangle(verticies[14], verticies[15], verticies[12], color=[0,0,0.0], fill=colors[7]) - dpg.draw_triangle(verticies[18], verticies[17], verticies[16], color=[0,0,0.0], fill=colors[8]) - dpg.draw_triangle(verticies[19], verticies[17], verticies[18], color=[0,0,0.0], fill=colors[9]) - dpg.draw_triangle(verticies[21], verticies[23], verticies[20], color=[0,0,0.0], fill=colors[10]) - dpg.draw_triangle(verticies[23], verticies[22], verticies[20], color=[0,0,0.0], fill=colors[11]) - - x_rot = 10 - y_rot = 45 - z_rot = 0 - - view = dpg.create_fps_matrix([0, 0, 50], 0.0, 0.0) - proj = dpg.create_perspective_matrix(math.pi*45.0/180.0, 1.0, 0.1, 100) - model = dpg.create_rotation_matrix(math.pi*x_rot/180.0 , [1, 0, 0])*\ - dpg.create_rotation_matrix(math.pi*y_rot/180.0 , [0, 1, 0])*\ - dpg.create_rotation_matrix(math.pi*z_rot/180.0 , [0, 0, 1]) - - dpg.set_clip_space("main pass", 0, 0, 500, 500, -1.0, 1.0) - dpg.apply_transform("cube", proj*view*model) - - dpg.show_viewport() - while dpg.is_dearpygui_running(): - dpg.render_dearpygui_frame() - - dpg.destroy_context() - -3D Operations Limitations -------------------------- - -**New in 1.1**. The drawing API 3D operations are not hardware accelerated (this will be introduced with DearPy3D). -This API is for 'light' 3D operations. There are a few issues you may come across while performing 3D operation with -the drawing API. - -**Issue 1: Z ordering** - -With the current API, users are responsible for correct Z ordering. The recommended way to address -this is to use "painter's algorithm". Basically, just order the items in proper depth order. - -This is not the best solution overall. We would prefer to use proper depth buffering but this -requires pixel level control which is not practical with this API. - -**Issue 2: Perspective Texture Correction** - -When using draw_image_quad, viewing the image at sharp angles will deform the image. This is -due to texture coordinates being linearly interpolated in normalized device coordinate space. - -There is currently no practical solution but an attempt could be made to split the quad into -several smaller quads. The actual solution requires pixel level control which is not practical with this API. - -**Issue 3: Culling** - -Currently, culling is only setup for triangles. - -**Dear Py3D and Software Renderer** - -All of the above issues will resolved in **Dear Py3D**. Before **Dear Py3D**, we will also be -introducing a software renderer for **Dear PyGui** that will resolve the above issues. diff --git a/docs/source/documentation/file-directory-selector.rst b/docs/source/documentation/file-directory-selector.rst deleted file mode 100644 index 2bad26539..000000000 --- a/docs/source/documentation/file-directory-selector.rst +++ /dev/null @@ -1,168 +0,0 @@ -File & Directory Selector -========================= - -The file dialog item can be used to select a single file, -multiple files, or a directory. When the user clicks the **Ok** button, -the dialog's callback is run. An optional second callback, to be run -when the cancel button is clicked, can be provided as a keyword -argument. - -When OK is clicked, information is passed through the app_data argument -such as: -* file path -* file name -* current path -* current filter (the file type filter) - - -The simplest case is as a director picker. Below is the example - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(sender, app_data): - print('OK was clicked.') - print("Sender: ", sender) - print("App Data: ", app_data) - - def cancel_callback(sender, app_data): - print('Cancel was clicked.') - print("Sender: ", sender) - print("App Data: ", app_data) - - dpg.add_file_dialog( - directory_selector=True, show=False, callback=callback, tag="file_dialog_id", - cancel_callback=cancel_callback, width=700 ,height=400) - - with dpg.window(label="Tutorial", width=800, height=300): - dpg.add_button(label="Directory Selector", callback=lambda: dpg.show_item("file_dialog_id")) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. note:: If no file extensions have been added, the selector defaults to directories. - -File Extensions ---------------- - -File extensions are items that are added to the file dialog. -You can even set the color of the file extensions. Below is a simple example: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(sender, app_data, user_data): - print("Sender: ", sender) - print("App Data: ", app_data) - - with dpg.file_dialog(directory_selector=False, show=False, callback=callback, id="file_dialog_id", width=700 ,height=400): - dpg.add_file_extension(".*") - dpg.add_file_extension("", color=(150, 255, 150, 255)) - dpg.add_file_extension("Source files (*.cpp *.h *.hpp){.cpp,.h,.hpp}", color=(0, 255, 255, 255)) - dpg.add_file_extension(".h", color=(255, 0, 255, 255), custom_text="[header]") - dpg.add_file_extension(".py", color=(0, 255, 0, 255), custom_text="[Python]") - - with dpg.window(label="Tutorial", width=800, height=300): - dpg.add_button(label="File Selector", callback=lambda: dpg.show_item("file_dialog_id")) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Customizing ------------ - -File dialogs can be customized with a panel by just adding -items to the file dialog as if it were a regular container. - -This can allow the creation of a pinned menu, favorites, directory tree, and much more. - -Below is an example: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(sender, app_data): - print("Sender: ", sender) - print("App Data: ", app_data) - - with dpg.file_dialog(directory_selector=False, show=False, callback=callback, tag="file_dialog_tag", width=700 ,height=400): - dpg.add_file_extension(".*") - dpg.add_file_extension("", color=(150, 255, 150, 255)) - dpg.add_file_extension(".cpp", color=(255, 255, 0, 255)) - dpg.add_file_extension(".h", color=(255, 0, 255, 255)) - dpg.add_file_extension(".py", color=(0, 255, 0, 255)) - - with dpg.group(horizontal=True): - dpg.add_button(label="fancy file dialog") - dpg.add_button(label="file") - dpg.add_button(label="dialog") - dpg.add_date_picker() - with dpg.child_window(height=100): - dpg.add_selectable(label="bookmark 1") - dpg.add_selectable(label="bookmark 2") - dpg.add_selectable(label="bookmark 3") - - with dpg.window(label="Tutorial", width=800, height=300): - dpg.add_button(label="File Selector", callback=lambda: dpg.show_item("file_dialog_tag")) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Selecting Multiple Files ------------------------- - -You can select multiple files by setting the *file_count* keyword -**Must use Ctrl + click to select multiple files** -**Must use Shift + click to select multiple files** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(sender, app_data): - print("Sender: ", sender) - print("App Data: ", app_data) - - with dpg.file_dialog(directory_selector=False, show=False, callback=callback, file_count=3, tag="file_dialog_tag", width=700 ,height=400): - dpg.add_file_extension("", color=(255, 150, 150, 255)) - dpg.add_file_extension(".*") - dpg.add_file_extension(".cpp", color=(255, 255, 0, 255)) - dpg.add_file_extension(".h", color=(255, 0, 255, 255)) - dpg.add_file_extension(".py", color=(0, 255, 0, 255)) - - dpg.add_button(label="fancy file dialog") - with dpg.child_window(width=100): - dpg.add_selectable(label="bookmark 1") - dpg.add_selectable(label="bookmark 2") - dpg.add_selectable(label="bookmark 3") - - with dpg.window(label="Tutorial", width=800, height=300): - dpg.add_button(label="File Selector", callback=lambda: dpg.show_item("file_dialog_tag")) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/filter-set.rst b/docs/source/documentation/filter-set.rst deleted file mode 100644 index 57dec50c9..000000000 --- a/docs/source/documentation/filter-set.rst +++ /dev/null @@ -1,45 +0,0 @@ -Filter Set -========== - -The filter set item is a container that can -be used to filter its children based on their *filter_key*. - -Most items have a *filter_key* keyword that can be set when -creating the item. Filtering is based on the set value of the filter set. - -The easiest way to understand this is by considering the example below - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(sender, filter_string): - dpg.set_value("filter_id", filter_string) - - with dpg.window(label="about", width =500, height=300): - dpg.add_input_text(label="Filter (inc, -exc)", callback=callback) - with dpg.filter_set(id="filter_id"): - dpg.add_text("aaa1.c", filter_key="aaa1.c", bullet=True) - dpg.add_text("bbb1.c", filter_key="bbb1.c", bullet=True) - dpg.add_text("ccc1.c", filter_key="ccc1.c", bullet=True) - dpg.add_text("aaa2.cpp", filter_key="aaa2.cpp", bullet=True) - dpg.add_text("bbb2.cpp", filter_key="bbb2.cpp", bullet=True) - dpg.add_text("ccc2.cpp", filter_key="ccc2.cpp", bullet=True) - dpg.add_text("abc.h", filter_key="abc.h", bullet=True) - dpg.add_text("hello, world", filter_key="hello, world", bullet=True) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. note:: - * Display everything with *""* - * Display lines containing xxx with *"xxx"* - * Display lines containing xxx or yyy with *"xxx,yyy"* - * Hide lines containing xxx with *"-xxx"* diff --git a/docs/source/documentation/fonts.rst b/docs/source/documentation/fonts.rst deleted file mode 100644 index 2653ed90b..000000000 --- a/docs/source/documentation/fonts.rst +++ /dev/null @@ -1,109 +0,0 @@ -Fonts -===== - -DPG embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), -a 13 pixels high, pixel-perfect font used by default. ProggyClean does not scale smoothly, -therefore it is recommended that you load your own file when using DPG in an -application aiming to look nice and wanting to support multiple resolutions. - -You do this by loading external .TTF/.OTF files. -In the `Assets `_ -folder you can find an example of a otf font. - -Readme First ------------- - -All loaded fonts glyphs are rendered into a single texture atlas. Rendering occurs -on-the-fly as characters are encountered in UI strings (item labels, input contents, etc. - -anything that gets displayed in the viewport). - -You can use the Fonts Manager tool -:py:func:`show_font_manager ` -to browse your fonts and understand what's going on if you have an issue. - -Font Loading Instructions -------------------------- - -To add your own fonts, you must first create a font registry to -add fonts to. Next, add fonts to the registry. - -For a font to take effect, it must be either bound globally with :py:func:`bind_font ` -or bound to a particular item with :py:func:`bind_item_font `. -In the latter case, the font is "inherited" by all child item if it is bound to -a container. To remove font binding and revert to the default font (or inherit from -the parent item), call `bind_font`/`bind_item_font` again, passing 0 in the `font` -argument. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - # add a font registry - with dpg.font_registry(): - # first argument ids the path to the .ttf or .otf file - default_font = dpg.add_font("NotoSerifCJKjp-Medium.otf", 20) - second_font = dpg.add_font("NotoSerifCJKjp-Medium.otf", 10) - - dpg.bind_font(default_font) - - with dpg.window(label="Font Example", height=200, width=200): - dpg.add_button(label="Default font") - b2 = dpg.add_button(label="Secondary font") - dpg.add_button(label="default") - - # set font of specific widget - dpg.bind_item_font(b2, second_font) - - dpg.show_font_manager() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Loading Specific Unicode Characters ------------------------------------ - -.. note:: - This section previously described how to load specific characters from font file - so that they are displayed in the UI correctly. Since DPG version 2.3, character - glyphs are rendered automatically and there is no need to specify them in advance. - This section is no longer relevant, and the functions `add_font_chars`, `add_font_range`, - and `add_font_range_hint` are obsolete and do nothing if you call them. - -Remapping Characters ------------------------------------ - -For convenience, you can remap a character to a different character code and use -this replacement in your text strings. In particular, it might be useful with icon -fonts. Here is an example of how to do such remapping. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.font_registry(): - with dpg.font("NotoSerifCJKjp-Medium.otf", 20) as font1: - - # remap や to % - dpg.add_char_remap(0x3084, 0x0025) - - dpg.show_font_manager() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Where to find unicode character codes? --------------------------------------- - -`Unicode Characters `_ - - diff --git a/docs/source/documentation/init-files.rst b/docs/source/documentation/init-files.rst deleted file mode 100644 index 17e223c01..000000000 --- a/docs/source/documentation/init-files.rst +++ /dev/null @@ -1,59 +0,0 @@ -Init Files -========== - -**Init** files are used to preserve the following data between application sessions - -* window positions -* window sizes -* window collapse state -* window docking -* table column widths -* table column ordering -* table column visible state -* table column sorting state - -.. note:: Init files use the tag of the window. Make sure the tag does not - change between sessions by generating the tag beforehand or specifying it as a string. - -Creating init files -------------------- - -Use :py:func:`save_init_file ` while - your application is running. - -.. note:: windows and tables can individually opt out of having their settings saved with the - `no_saved_settings` keyword. - -Loading init files ------------------- - -Use :py:func:`configure_app ` before creating the viewport. - -Below is an example of using **init** files to preserve settings between sessions. - -* Position the windows -* Press the save button and the init file will be saved in the current working directory -* Restart the app and see your windows in the previous positions. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def save_init(): - dpg.save_init_file("dpg.ini") - - dpg.configure_app(init_file="dpg.ini") # default file is 'dpg.ini' - with dpg.window(label="about", tag="main window"): - dpg.add_button(label="Save Window pos", callback=lambda: save_init) - - with dpg.window(label="about", tag="side window"): - dpg.add_button(label="Press me") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - diff --git a/docs/source/documentation/io-handlers-state.rst b/docs/source/documentation/io-handlers-state.rst deleted file mode 100644 index 06680af35..000000000 --- a/docs/source/documentation/io-handlers-state.rst +++ /dev/null @@ -1,148 +0,0 @@ -IO, Handlers, State Polling -=========================== - -Handlers --------- - -Handlers are items that submit a callback when the specified state of an item changes. - -Handlers can be activated or deactivated by showing or hiding them. - -Handlers are required to be added to a handler registry. - -Item Handlers -------------- - -Item handlers listen for states related to a specific item. - -Events: - * Activated - * Active - * Clicked - * Deactivated - * Deactivated After Edited - * Focus - * Hover - * Resize - * Toggled - * Visible - - Item handlers are required to be added to a item handler registry. - - Item handler registries can be bound to an item. - They can be bound to multiple items to prevent having to duplicate handlers for every item. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def change_text(sender, app_data): - dpg.set_value("text item", f"Mouse Button ID: {app_data}") - - def visible_call(sender, app_data): - print("I'm visible") - - with dpg.item_handler_registry(tag="widget handler") as handler: - dpg.add_item_clicked_handler(callback=change_text) - dpg.add_item_visible_handler(callback=visible_call) - - with dpg.window(width=500, height=300): - dpg.add_text("Click me with any mouse button", tag="text item") - dpg.add_text("Close window with arrow to change visible state printing to console", tag="text item 2") - - # bind item handler registry to item - dpg.bind_item_handler_registry("text item", "widget handler") - dpg.bind_item_handler_registry("text item 2", "widget handler") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/widget_handlers.gif - -Global Handlers (IO Input) --------------------------- - -Global handlers listen for actions not tied to a specific item: - -**Keys:** - * Down - * Press - * Release - -**Mouse:** - * Click - * Double Click - * Down - * Drag - * Move - * Release - * Wheel - -Global handlers are required to be added to a handler registry. - -Registries provide a grouping aspect to handlers allowing separation -by input device. They also provide the ability to turn on and off the entire registry. - -For example this can allow a mouse input registry or a keyboard input -registry. Registries also give the ability to deactivate all their -children handlers by simply hiding the registry. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def change_text(sender, app_data): - dpg.set_value("text_item", f"Mouse Button: {app_data[0]}, Down Time: {app_data[1]} seconds") - - with dpg.handler_registry(): - dpg.add_mouse_down_handler(callback=change_text) - - with dpg.window(width=500, height=300): - dpg.add_text("Press any mouse button", tag="text_item") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/global_hanlders_global_registries.gif - -Polling Item State ------------------- - -Polling item state is accessible through -:py:func:`get_item_state `. These can be very powerful -when combined with handlers as shown below. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def change_text(sender, app_data): - if dpg.is_item_hovered("text item"): - dpg.set_value("text item", f"Stop Hovering Me, Go away!!") - else: - dpg.set_value("text item", f"Hover Me!") - - with dpg.handler_registry(): - dpg.add_mouse_move_handler(callback=change_text) - - with dpg.window(width=500, height=300): - dpg.add_text("Hover Me!", tag="text item") - - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/item-callbacks.rst b/docs/source/documentation/item-callbacks.rst deleted file mode 100644 index 052ccf109..000000000 --- a/docs/source/documentation/item-callbacks.rst +++ /dev/null @@ -1,183 +0,0 @@ -Item Callbacks -============== - -Most items have a callback which is submitted to a -**queue of callbacks** when the item is interacted with. - -Callbacks are used to give functionality to items. Callbacks -can either be assigned to the item upon creation or after creation -using :py:func:`set_item_callback ` -as shown in the code below. - -Callbacks in DPG can have up to 3 arguments. The first is usually -the sender or item triggering the callback. The second is data sent by -DPG for different reasons. The third is reserved for user specified data. -We refer to this in general terms as: **sender**, **app_data**, and **user_data**. - -.. note:: Because they are optional positional arguments you - must use the *sender* and *app_data* if you want to use *user_data* - keyword arguments: - -Sender, App_data ----------------- - -sender: - argument is used by DPG to inform the - callback which item triggered the callback by sending the tag - or 0 if trigger by the application. - -app_data: - argument is used by DPG to send information - to the callback i.e. the current value of most basic widgets. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def button_callback(sender, app_data): - print(f"sender is: {sender}") - print(f"app_data is: {app_data}") - - with dpg.window(label="Tutorial"): - dpg.add_button(label="Print to Terminal", callback=button_callback) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -User Data ---------- - -user_data: - argument is **Optionally** used to pass - your own python data into the function. - -The python data can be assigned or updated to the keyword *user_data* when the -item is created or after the item is created using -:py:func:`set_item_user_data ` - -User data can be any python object. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def button_callback(sender, app_data, user_data): - print(f"sender is: {sender}") - print(f"app_data is: {app_data}") - print(f"user_data is: {user_data}") - - with dpg.window(label="Tutorial"): - # user data set when button is created - dpg.add_button(label="Print to Terminal", callback=button_callback, user_data="Some Data") - - # user data and callback set any time after button has been created - dpg.add_button(label="Print to Terminal 2", tag="btn") - dpg.set_item_callback("btn", button_callback) - dpg.set_item_user_data("btn", "Some Extra User Data") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Drag and Drop callback (and drag payload) ------------------------------------------ - -Drag/Drop callback receive its **app_data** from drag_payload's **drag_data**. - -**user_data** (optional) can be specified in both **drag payload** and **target drop item** for further use in Drag/Drop callback. - -**payload_type** (optional) can be any string you like. If not specified, **payload_type**'s default value is '$$DPG_PAYLOAD'. - -For drop callback to work, **payload_type** must be specified the same in both **drag payload** and **target drop item**. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - dpg.create_context() - - def drag_cb(sender, app_data, user_data): - # sender is btn_drag - # app_data is btn_drag (value from drag_data) - # do some configure(drawing_item), animation - ... - - def drop_cb(sender, app_data, user_data): - # sender is group, app_data is btn_drag - dpg.move_item(app_data, parent=sender) - - with dpg.window(): - with dpg.group(horizontal=True): - - with dpg.group(width=300, drop_callback=drop_cb, payload_type="int"): # user_data=?? - dpg.add_text("Group left") - dpg.add_button(label="not drag this") - - with dpg.group(width=300, drop_callback=drop_cb, payload_type="int"): - dpg.add_text("Group right") - dpg.add_button(label="not drag this") - btn_drag = dpg.add_button(label="drag me to another group then drop", drag_callback=drag_cb) - - with dpg.drag_payload(parent=btn_drag, drag_data=btn_drag, payload_type="int"): - dpg.add_text("dragging a button") - - # parent=btn_drag --> this playload will appear if dragged from the btn_drag - # drag_data=btn_drag --> btn_drag will be app_data in the above drag_cb and drop_cb - # payload_type="int" --> btn_drag is an int, specified in this playload and drop target - two group above - - dpg.create_viewport() - dpg.setup_dearpygui() - dpg.show_viewport() - while dpg.is_dearpygui_running(): - dpg.render_dearpygui_frame() - dpg.destroy_context() - -Debugging Callbacks (new in 1.2) --------------------------------- - -Because callbacks are not run on the main thread, debugging can be a hassle. -In 1.2 we added a few utilities to help with this. - -By default, Dear PyGui handles the callbacks internally on a worker thread. This allows for -optimizations and steady framerates. However, to help with debugging, you can set the new -**manual_callback_management** key to **True** with :py:func:`configure_app `. -This will prevent Dear PyGui from handling the callbacks. Instead the callbacks and arguments will be stored. -You can then retrieve (and clear) them by calling :py:func:`get_callback_queue ` within -your main event loop. This will return a list of "Jobs". A "Job" is just list with the first item being the callable and -the remaining items (up to 3) being the typical arguments. We have also provided :py:func:`run_callbacks ` -to properly handle the jobs for simple usage. - -Below is a simple example - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.configure_app(manual_callback_management=True) - dpg.create_viewport() - dpg.setup_dearpygui() - - def callback(sender, app_data, user_data): - print("Called on the main thread!") - - with dpg.window(label="Tutorial"): - dpg.add_button(label="Press me", callback=callback) - - - # main loop - dpg.show_viewport() - while dpg.is_dearpygui_running(): - jobs = dpg.get_callback_queue() # retrieves and clears queue - dpg.run_callbacks(jobs) - dpg.render_dearpygui_frame() - - dpg.destroy_context() diff --git a/docs/source/documentation/item-configuration.rst b/docs/source/documentation/item-configuration.rst deleted file mode 100644 index bf328f7e6..000000000 --- a/docs/source/documentation/item-configuration.rst +++ /dev/null @@ -1,37 +0,0 @@ -Item Configuration -================== - -In DPG various configuration -options and flags can be set when items are created. -There are several options common -to all items (i.e. **show**) but most items have specific options. - -In order to modify an item's configuration after being created, you can -use the :py:func:`configure_item ` -command in conjunction with the keyword from -the item's *add_\*\*\** command. You can also retrieve an item's configuration -in the form of a dictionary by using the -:py:func:`get_item_configuration ` command. - -Example -------- - -Simple usage can be found below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(width=500, height=300): - dpg.add_button(enabled=True, label="Press me", tag="item") - - # at a later time, change the item's configuration - dpg.configure_item("item", enabled=False, label="New Label") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() \ No newline at end of file diff --git a/docs/source/documentation/item-creation.rst b/docs/source/documentation/item-creation.rst deleted file mode 100644 index 3fce32878..000000000 --- a/docs/source/documentation/item-creation.rst +++ /dev/null @@ -1,173 +0,0 @@ -Item Creation -============== - -DPG can be broken down into **Items**, **UI Items**, **Containers**. - -Items ------ - -Everything created in DPG is an **item**. New items can be created -by calling various *add_\*\*\** or *draw_\*\*\** functions. These commands -return a unique identifier that can be used to later refer to the item. -**UI items** and **containers** are also **items** - but not every **item** -is necessarily a **UI item** or **container**. - -All items have the following optional parameters: *label*, *tag*, *user_data*, -and *use_internal_label*. The *tag* is generated automatically or can be specified. -A *label* serves as the display name for an item. -*user_data* can be any value and is frequently used for **callbacks**. - -.. note:: Event **handlers**, **registries**, **group**, and **themes** are also items. - These are under-the-hood items for customizing the functionality, flow, - and overall look of your APP. - - -Containers ----------- - -**Container** items that can contain other (allowable) items. - -In addition to creating them by -calling their corresponding *add_\*\*\** function, they can also be -created by calling their corresponding context manager. - -.. note:: Containers are more useful (and recommended) when used as context managers. - -Below is an example of creating two new **window** items -using their context manager and starting the application: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Window1", pos=(0,0)): - pass - - with dpg.window(label="Window2", pos=(100,0)): - pass - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/Atlamillias/DearPyGui-Stuff/main/wiki%20images/dpg_creating_appitems_ex2.png - -UI Items --------- - -**UI items** are items that are considered to be a visual and -usually interactable element in your user interface. - -These include **buttons**, **sliders**, **inputs**, and even -other containers such as **windows** and **tree nodes**. - -Below is an example for creating a **window** container -that contains a few other items: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial") as window: - # When creating items within the scope of the context - # manager, they are automatically "parented" by the - # container created in the initial call. So, "window" - # will be the parent for all of these items. - - button1 = dpg.add_button(label="Press Me!") - - slider_int = dpg.add_slider_int(label="Slide to the left!", width=100) - slider_float = dpg.add_slider_float(label="Slide to the right!", width=100) - - # An item's unique identifier (tag) is returned when - # creating items. - print(f"Printing item tag's: {window}, {button1}, {slider_int}, {slider_float}") - - # If you want to add an item to an existing container, you - # can specify it by passing the container's tag as the - # "parent" parameter. - button2 = dpg.add_button(label="Don't forget me!", parent=window) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/Atlamillias/DearPyGui-Stuff/main/wiki%20images/dpg_creating_widgets_ex1.png - - -Runtime Adding and Deleting ---------------------------- - -With DPG you can dynamically add, delete, and move items at runtime. - -This can be done by using a callback to run the desired item's *add_\*\*\** -command and specifying the parent the item will belong to. - -By using the **before** keyword when adding a item you can control which -item in the parent the new item will come before. Default will place the -new widget at the end. - -Below is an example demonstrating adding and deleting items during runtime: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def add_buttons(): - global new_button1, new_button2 - new_button1 = dpg.add_button(label="New Button", before="delete_button", tag="new_button1") - new_button2 = dpg.add_button(label="New Button 2", parent="secondary_window", tag="new_button2") - - - def delete_buttons(): - dpg.delete_item("new_button1") - dpg.delete_item("new_button2") - - - with dpg.window(label="Tutorial", pos=(200, 200)): - dpg.add_button(label="Add Buttons", callback=add_buttons) - dpg.add_button(label="Delete Buttons", callback=delete_buttons, tag="delete_button") - - with dpg.window(label="Secondary Window", tag="secondary_window", pos=(100, 100)): - pass - - dpg.create_viewport(title='Custom Title', width=600, height=400) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. hint:: - When deleting a container the container and its' children are deleted by default, - unless the keyword **children_only** is set to True, i.e.: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def delete_children(): - dpg.delete_item("window", children_only=True) - - with dpg.window(label="Tutorial", pos=(200, 200), tag="window"): - dpg.add_button(label="Delete Children", callback=delete_children) - dpg.add_button(label="Button_1") - dpg.add_button(label="Button_2") - dpg.add_button(label="Button_3") - - dpg.create_viewport(title='Custom Title', width=600, height=400) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/item-id-system.rst b/docs/source/documentation/item-id-system.rst deleted file mode 100644 index cb6a9fd7d..000000000 --- a/docs/source/documentation/item-id-system.rst +++ /dev/null @@ -1,112 +0,0 @@ -Tag System -========== - -In DPG, all items must have an associated unique ID (UUID) -which can either be an integer or a string. - -When a item is created, a tag is generated for you automatically. -It is your responsibility to store this tag if you intend on interacting -with the widget at a later time. - -Tags allow for modification of the associated item at runtime. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - unique_id = 0 # to be filled out later - - def callback(): - print(dpg.get_value(unique_id)) - - with dpg.window(label="Example"): - dpg.add_button(label="Press me (print to output)", callback=callback) - unique_id = dpg.add_input_int(label="Input") - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - -Generated Tags --------------- -The previous example could also be handled by generating the tag beforehand like this: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - unique_tag = dpg.generate_uuid() - - def callback(): - print(dpg.get_value(unique_tag)) - - with dpg.window(label="Example"): - dpg.add_button(label="Press me (print to output)", callback=callback) - dpg.add_input_int(label="Input", tag=unique_tag) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Aliases -------- - -An alias is a string that takes the place of the regular **int** tag. -Aliases can be used anywhere UUID's can be used. -It is the user's responsibility to make sure aliases are unique. - -A simple example can be seen below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def callback(): - print(dpg.get_value("unique_tag")) - - with dpg.window(label="Example"): - dpg.add_button(label="Press me (print to output)", callback=callback) - dpg.add_input_int(default_value=5, label="Input", tag="unique_tag") - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Recent Tags ------------ -The most recent tag is stored for the last item, container, and root. - -This is useful when the last item created may -be done at run time, is anonymous or sometimes just for convenience. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Example"): - with dpg.group(): - dpg.add_button(label="View the Terminal for item tags") - print(dpg.last_item()) - print(dpg.last_container()) - print(dpg.last_root()) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/item-value.rst b/docs/source/documentation/item-value.rst deleted file mode 100644 index 285430238..000000000 --- a/docs/source/documentation/item-value.rst +++ /dev/null @@ -1,72 +0,0 @@ -Values -====== - -When an item is created, it creates an associated value by default. -Values can be shared between items with the same underlying value type. -This is accomplished by using the `source` keyword. One of the benefits of -this is to have multiple items control the same value. - -Values are retrieved from the value :py:func:`get_value `. - -Values can be changed manually using :py:func:`set_value `. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - dpg.add_checkbox(label="Radio Button1", tag="R1") - dpg.add_checkbox(label="Radio Button2", source="R1") - - dpg.add_input_text(label="Text Input 1") - dpg.add_input_text(label="Text Input 2", source=dpg.last_item(), password=True) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Value Items ------------ -There are several "Value" items that can be used. These are -items that have no visual component. These include: - -* **mvBoolValue** -* **mvColorValue** -* **mvDoubleValue** -* **mvDouble4Value** -* **mvFloatValue** -* **mvFloat4Value** -* **mvFloatVectValue** -* **mvIntValue** -* **mvInt4Value** -* **mvSeriesValue** -* **mvStringValue** - -Basic usage can be found below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.value_registry(): - dpg.add_bool_value(default_value=True, tag="bool_value") - dpg.add_string_value(default_value="Default string", tag="string_value") - - with dpg.window(label="Tutorial"): - dpg.add_checkbox(label="Radio Button1", source="bool_value") - dpg.add_checkbox(label="Radio Button2", source="bool_value") - - dpg.add_input_text(label="Text Input 1", source="string_value") - dpg.add_input_text(label="Text Input 2", source="string_value", password=True) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/menus.rst b/docs/source/documentation/menus.rst deleted file mode 100644 index 4275280db..000000000 --- a/docs/source/documentation/menus.rst +++ /dev/null @@ -1,103 +0,0 @@ -Menu Bar -======== - -DPG contains two types of Menu Bars - -Viewport Menu Bar - Attached to the viewport - -Menu Bar: - Attached to a specified window - -Other than being attached to different parents they both act the same. - -A typical menu bar consists of the following components: - -Menu Bar: - The main menu ribbon. Used to contain menus. -Menu: - Popup windows that are used to contain items in a collapsable fashion. -Menu Item: - Items that can run callbacks and display a checkmark. - -Usage ------ - -Items added to the Menu Bar are displayed from left to right. -Items added to the menus are displayed from top to bottom. - -Menus can be nested inside other menus. - -Any widget can be added to a menu. - -**Viewport Menu Bar Example** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - def print_me(sender): - print(f"Menu Item: {sender}") - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=600, height=200) - - with dpg.viewport_menu_bar(): - with dpg.menu(label="File"): - dpg.add_menu_item(label="Save", callback=print_me) - dpg.add_menu_item(label="Save As", callback=print_me) - - with dpg.menu(label="Settings"): - dpg.add_menu_item(label="Setting 1", callback=print_me, check=True) - dpg.add_menu_item(label="Setting 2", callback=print_me) - - dpg.add_menu_item(label="Help", callback=print_me) - - with dpg.menu(label="Widget Items"): - dpg.add_checkbox(label="Pick Me", callback=print_me) - dpg.add_button(label="Press Me", callback=print_me) - dpg.add_color_picker(label="Color Me", callback=print_me) - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Menu Bar Example** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.create_viewport(title='Custom Title', width=600, height=200) - - def print_me(sender): - print(f"Menu Item: {sender}") - - with dpg.window(label="Tutorial"): - with dpg.menu_bar(): - with dpg.menu(label="File"): - dpg.add_menu_item(label="Save", callback=print_me) - dpg.add_menu_item(label="Save As", callback=print_me) - - with dpg.menu(label="Settings"): - dpg.add_menu_item(label="Setting 1", callback=print_me, check=True) - dpg.add_menu_item(label="Setting 2", callback=print_me) - - dpg.add_menu_item(label="Help", callback=print_me) - - with dpg.menu(label="Widget Items"): - dpg.add_checkbox(label="Pick Me", callback=print_me) - dpg.add_button(label="Press Me", callback=print_me) - dpg.add_color_picker(label="Color Me", callback=print_me) - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/wiki_images/menus.PNG \ No newline at end of file diff --git a/docs/source/documentation/node-editor.rst b/docs/source/documentation/node-editor.rst deleted file mode 100644 index 32712e751..000000000 --- a/docs/source/documentation/node-editor.rst +++ /dev/null @@ -1,123 +0,0 @@ -Node Editor -=========== - -A Node Editor presents an editable schematic or graph, -displaying nodes and the connections between their attributes. -It allows you to view, modify, and create new node connections. - -You can see an example below - -.. image:: https://raw.githubusercontent.com/Nelarius/imnodes/master/img/imnodes.gif - -**There are 4 main components** - -1. **Node Editor** - the area in which the nodes are located -2. **Nodes** - the free floating "windows" which contains attributes -3. **Attributes** - the collections of widgets with pins to create links to/from. - Can be input, output, or static. -4. **Links** - the connections between attributes - -Attributes can contain any UI Items. When a user clicks and drags a node's attribute -the node editor's callback is ran. DPG sends the attributes' tags through the -_app_data_ argument of the callback. - -It's the developer's responsibility to create the link. - -Below is a basic example. You can grab an output pin and connect it to an input pin. -You can detach a link by **ctrl** clicking the link and dragging it. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - # callback runs when user attempts to connect attributes - def link_callback(sender, app_data): - # app_data -> (link_id1, link_id2) - dpg.add_node_link(app_data[0], app_data[1], parent=sender) - - # callback runs when user attempts to disconnect attributes - def delink_callback(sender, app_data): - # app_data -> link_id - dpg.delete_item(app_data) - - with dpg.window(label="Tutorial", width=400, height=400): - - with dpg.node_editor(callback=link_callback, delink_callback=delink_callback): - with dpg.node(label="Node 1"): - with dpg.node_attribute(label="Node A1"): - dpg.add_input_float(label="F1", width=150) - - with dpg.node_attribute(label="Node A2", attribute_type=dpg.mvNode_Attr_Output): - dpg.add_input_float(label="F2", width=150) - - with dpg.node(label="Node 2"): - with dpg.node_attribute(label="Node A3"): - dpg.add_input_float(label="F3", width=200) - - with dpg.node_attribute(label="Node A4", attribute_type=dpg.mvNode_Attr_Output): - dpg.add_input_float(label="F4", width=200) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Selection Querying ------------------- - -You can retrieve selected nodes and links (and clear this selections with the following commands) - -.. code-block:: python - - dpg.get_selected_nodes(editor_id) - dpg.get_selected_links(editor_id) - dpg.clear_selected_nodes(editor_id) - dpg.clear_selected_links(editor_id) - -Node Attribute Types --------------------- - -The following constants can be used in the `attribute_type` argument for node attributes - -+---------------------------------+ -| Attribute | -+---------------------------------+ -| **mvNode_Attr_Input** (default) | -+---------------------------------+ -| **mvNode_Attr_Output** | -+---------------------------------+ -| **mvNode_Attr_Static** | -+---------------------------------+ - -Node Attribute Pin Shapes -------------------------- - -The following constants can be used in the `shape` argument for node attributes - -+--------------------------------------------+ -| Shape | -+--------------------------------------------+ -| **mvNode_PinShape_Circle** | -+--------------------------------------------+ -| **mvNode_PinShape_CircleFilled** (default) | -+--------------------------------------------+ -| **mvNode_PinShape_Triangle** | -+--------------------------------------------+ -| **mvNode_PinShape_TriangleFilled** | -+--------------------------------------------+ -| **mvNode_PinShape_Quad** | -+--------------------------------------------+ -| **mvNode_PinShape_QuadFilled** | -+--------------------------------------------+ - -Associated Items --------------------- - -* **mvNode** -* **mvNodeAttribute** -* **mvNodeLink** diff --git a/docs/source/documentation/plots.rst b/docs/source/documentation/plots.rst deleted file mode 100644 index 07489fb2a..000000000 --- a/docs/source/documentation/plots.rst +++ /dev/null @@ -1,611 +0,0 @@ -Plots -===== - -Plots are composed of multiple components. - -Y-axis: - This is a container and is the parent of all the data series that are added to the plot. - The plot can have multiple Y-axis at one time (up to 3). - -X-axis: - This is the x data scale (only 1 x axis is allowed). - -Series: - These are the containers for the data you wish to display. - Data series need to be added as a child of a Y-axis to be displayed on the plot. - There are many different types of data series avaliable. - Series also can contain UI Items that will be displayed when right-clicking the series label in the legend as a context menu. - -Legend (optional): - This is a normal legend and alos allows the user to toggle which data series are visible. - -Plots have some functionality built in: - Toggle Data Series: - Click on the legend name of the desired data series to toggle - Settings: - Double Right Click - Pan Plot: - Click & Drag on plot - Pan Axis: - Click & Drag on Axis - Zoom: - Scroll Mouse Wheel - Zoom Axis: - Hover Axis & Scroll Mouse Wheel - Zoom Region: - Right Click & Drag - Zoom Extents: - Double Click - Zoom Axis Area: - Shift + Right Click & Drag - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - # creating data - sindatax = [] - sindatay = [] - for i in range(0, 500): - sindatax.append(i / 1000) - sindatay.append(0.5 + 0.5 * sin(50 * i / 1000)) - - with dpg.window(label="Tutorial"): - # create plot - with dpg.plot(label="Line Series", height=400, width=400): - # optionally create legend - dpg.add_plot_legend() - - # REQUIRED: create x and y axes - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y", tag="y_axis") - - # series belong to a y axis - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent="y_axis") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - -Updating Series Data --------------------- - -You can change a series on a plot by - * setting the series value - * deleting that specific series item from they y-axis and adding it again - * deleting all the series items from they y-axis and adding that specific series again - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin, cos - - dpg.create_context() - - sindatax = [] - sindatay = [] - for i in range(0, 500): - sindatax.append(i / 1000) - sindatay.append(0.5 + 0.5 * sin(50 * i / 1000)) - - def update_series(): - - cosdatax = [] - cosdatay = [] - for i in range(0, 500): - cosdatax.append(i / 1000) - cosdatay.append(0.5 + 0.5 * cos(50 * i / 1000)) - dpg.set_value('series_tag', [cosdatax, cosdatay]) - dpg.set_item_label('series_tag', "0.5 + 0.5 * cos(x)") - - with dpg.window(label="Tutorial", tag="win"): - dpg.add_button(label="Update Series", callback=update_series) - # create plot - with dpg.plot(label="Line Series", height=400, width=400): - # optionally create legend - dpg.add_plot_legend() - - # REQUIRED: create x and y axes - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y", tag="y_axis") - - # series belong to a y axis - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent="y_axis", tag="series_tag") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - -Axis Limits ------------ -The following commands can be used to control the plot axes limits - -* `set_axis_limits(...)` -* `get_axis_limits(...)` -* `set_axis_limits_auto(...)` -* `fit_axis_data(...)` -* `set_axis_limits_constraints(...)` -* `reset_axis_limits_constraints(...)` -* `set_axis_zoom_constraints(...)` -* `reset_axis_zoom_constraints(...)` - -An example demonstrating some of this can be found below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", width=400, height=400): - with dpg.group(horizontal=True): - dpg.add_button(label="fit y", callback=lambda: dpg.fit_axis_data("y_axis")) - dpg.add_button(label="unlock x limits", callback=lambda: dpg.set_axis_limits_auto("x_axis")) - dpg.add_button(label="unlock y limits", callback=lambda: dpg.set_axis_limits_auto("y_axis")) - dpg.add_button(label="print limits x", callback=lambda: print(dpg.get_axis_limits("x_axis"))) - dpg.add_button(label="print limits y", callback=lambda: print(dpg.get_axis_limits("y_axis"))) - - with dpg.plot(label="Bar Series", height=-1, width=-1): - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="Student", no_gridlines=True, tag="x_axis") - dpg.set_axis_limits(dpg.last_item(), 9, 33) - dpg.set_axis_ticks(dpg.last_item(), (("S1", 11), ("S2", 21), ("S3", 31))) - - # create y axis - dpg.add_plot_axis(dpg.mvYAxis, label="Score", tag="y_axis") - dpg.set_axis_limits("y_axis", 0, 110) - - # add series to y axis - dpg.add_bar_series([10, 20, 30], [100, 75, 90], label="Final Exam", weight=1, parent="y_axis") - dpg.add_bar_series([11, 21, 31], [83, 75, 72], label="Midterm Exam", weight=1, parent="y_axis") - dpg.add_bar_series([12, 22, 32], [42, 68, 23], label="Course Grade", weight=1, parent="y_axis") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Custom Axis Labels ------------------- - -Custom labels can be set per axis using -:py:func:`set_axis_ticks `. They can be reset with -:py:func:`reset_axis_ticks `. -An example can be found below - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", width=400, height=400): - with dpg.plot(label="Bar Series", height=-1, width=-1): - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="Student", no_gridlines=True) - dpg.set_axis_ticks(dpg.last_item(), (("S1", 11), ("S2", 21), ("S3", 31))) - - # create y axis - dpg.add_plot_axis(dpg.mvYAxis, label="Score", tag="yaxis_tag") - - # add series to y axis - dpg.add_bar_series([10, 20, 30], [100, 75, 90], label="Final Exam", weight=1, parent="yaxis_tag") - dpg.add_bar_series([11, 21, 31], [83, 75, 72], label="Midterm Exam", weight=1, parent="yaxis_tag") - dpg.add_bar_series([12, 22, 32], [42, 68, 23], label="Course Grade", weight=1, parent="yaxis_tag") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Multiple Y Axes ---------------- - -Plots can contain up to Three Y-axis for different data that needs a different scale. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - sindatax = [] - sindatay = [] - for i in range(0, 100): - sindatax.append(i / 100) - sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) - - with dpg.window(label="Tutorial", width=400, height=400): - with dpg.plot(label="Multi Axes Plot", height=400, width=-1): - dpg.add_plot_legend() - - # create x axis - dpg.add_plot_axis(dpg.mvXAxis, label="x") - - # create y axis 1 - dpg.add_plot_axis(dpg.mvYAxis, label="y1") - dpg.add_line_series(sindatax, sindatay, label="y1 lines", parent=dpg.last_item()) - - # create y axis 2 - dpg.add_plot_axis(dpg.mvYAxis2, label="y2") - dpg.add_stem_series(sindatax, sindatay, label="y2 stem", parent=dpg.last_item()) - - # create y axis 3 - dpg.add_plot_axis(dpg.mvYAxis3, label="y3 scatter") - dpg.add_scatter_series(sindatax, sindatay, label="y3", parent=dpg.last_item()) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Annotations ------------ - -Annotations can be used to mark locations on a plot. - -Annotations are owned by the plot and their coordinates correspond to the 1st y axis. - -They are clamped by default. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - - sindatax = [] - sindatay = [] - for i in range(0, 100): - sindatax.append(i / 100) - sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) - - with dpg.window(label="Tutorial", width=400, height=400): - with dpg.plot(label="Annotations", height=-1, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.add_line_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent=dpg.last_item()) - - # annotations belong to the plot NOT axis - dpg.add_plot_annotation(label="BL", default_value=(0.25, 0.25), offset=(-15, 15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="BR", default_value=(0.75, 0.25), offset=(15, 15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="TR not clampled", default_value=(0.75, 0.75), offset=(-15, -15), - color=[255, 255, 0, 255], clamped=False) - dpg.add_plot_annotation(label="TL", default_value=(0.25, 0.75), offset=(-15, -15), color=[255, 255, 0, 255]) - dpg.add_plot_annotation(label="Center", default_value=(0.5, 0.5), color=[255, 255, 0, 255]) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Drag Points and Lines ---------------------- - -Drag lines/points are owned by the plot and their coordinates correspond to the 1st y axis. -These items can be moved by clicking and dragging. - -You can also set a callback to be ran when they -are interacted with! - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def print_val(sender): - print(dpg.get_value(sender)) - - with dpg.window(label="Tutorial", width=400, height=400): - with dpg.plot(label="Drag Lines/Points", height=-1, width=-1): - dpg.add_plot_legend() - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.set_axis_limits(dpg.last_item(), -5, 5) - dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.set_axis_limits(dpg.last_item(), -5, 5) - - # drag lines/points belong to the plot NOT axis - dpg.add_drag_line(label="dline1", color=[255, 0, 0, 255], default_value=2.0, callback=print_val) - dpg.add_drag_line(label="dline2", color=[255, 255, 0, 255], vertical=False, default_value=-2, callback=print_val) - dpg.add_drag_point(label="dpoint1", color=[255, 0, 255, 255], default_value=(1.0, 1.0), callback=print_val) - dpg.add_drag_point(label="dpoint2", color=[255, 0, 255, 255], default_value=(-1.0, 1.0), callback=print_val) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Querying --------- - -Querying allows the user to select a region of the plot by -**Ctrl + dragging the right mouse button** and dragging five -circles of the query rectangle with left mouse button. - -Double left click inside a drag rect will remove it (if *min_query_rects* allows). -If number of rects exceed *max_query_rects* when create new drag rect, it will replace the last one. - -Since DearPyGui 2.0, *query_mod* changes to *query_toggle_mod* for swapping the Ctrl key above. -*query_button* is removed, so **dragging the right mouse button** is hardcoded. -*min_query_rects, max_query_rects* limit the number of drag rects. - -Querying requires setting *query* to **True** when creating the plot. - -The callback of the plot will run when the plot is being queried (dragging five circles). -Or not using plot's callback but drag rect's callback *dpg.add_drag_rect(callback=...)*. - -All the query areas are sent through the *app_data* argument as -*((x_min, y_min, x_max, y_max), (x_min, y_min, x_max, y_max), ...)*. - -It is also possible to poll the plot for the query areas by calling: -:py:func:`get_plot_query_rects ` and - -Below is an example using the callback - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - sindatax = [] - sindatay = [] - for i in range(0, 100): - sindatax.append(i / 100) - sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) - - with dpg.window(label="Tutorial", width=400, height=600): - dpg.add_text("Ctrl and drag the right mouse button over the top plot!") - - - def query(sender, app_data, user_data): - # TODO: handle for when app_data is empty - IndexError: tuple index out of range. - rect_0 = app_data[0] - # other_rects = app_data[1:] - dpg.set_axis_limits("xaxis_tag2", rect_0[0], rect_0[2]) - dpg.set_axis_limits("yaxis_tag2", rect_0[1], rect_0[3]) - - - # plot 1 - with dpg.plot( - no_title=True, height=200, callback=query, query=True, no_menus=True, width=-1, - min_query_rects=0, max_query_rects=3, - ): - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y") - dpg.add_line_series(sindatax, sindatay, parent=dpg.last_item()) - - # plot 2 - with dpg.plot(no_title=True, height=200, no_menus=True, width=-1): - dpg.add_plot_axis(dpg.mvXAxis, label="x1", tag="xaxis_tag2") - dpg.add_plot_axis(dpg.mvYAxis, label="y1", tag="yaxis_tag2") - dpg.add_line_series(sindatax, sindatay, parent="yaxis_tag2") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Custom Context Menus --------------------- - -Plot series are actually containers! - -Adding UI Items to a plot series, -they will show up when right-clicking the series in the legend. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - sindatax = [] - sindatay = [] - for i in range(0, 100): - sindatax.append(i / 100) - sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) - - with dpg.window(label="Tutorial", width=400, height=400): - # create plot - dpg.add_text("Right click a series in the legend!") - with dpg.plot(label="Line Series", height=-1, width=-1): - dpg.add_plot_legend() - - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y", tag="yaxis") - - # series 1 - dpg.add_line_series(sindatax, sindatay, label="series 1", parent="yaxis", tag="series_1") - dpg.add_button(label="Delete Series 1", parent=dpg.last_item(), callback=lambda: dpg.delete_item("series_1")) - - # series 2 - dpg.add_line_series(sindatax, sindatay, label="series 2", parent="yaxis", tag="series_2") - dpg.add_button(label="Delete Series 2", parent=dpg.last_item(), callback=lambda: dpg.delete_item("series_2")) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Custom Series -------------- - -**New in 1.6**. Custom series allow you to control the way a series is rendered. - -A custom series can currently have between 2 and 5 channels. A channel is an array/list of -data. Each channel must be the same length. The first 2 channels and channel count are -required arguments. Additional channels can be provided with the y1, y2, and y3 keywords. You must -also set the "callback" keyword. The second argument will be provided by DPG as a list. The first item being -useful information. The following items are the original data sent in but transformed into pixel space. The -combination of all this information can be used to create a custom series. See simple example below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - x_data = [0.0, 1.0, 2.0, 4.0, 5.0] - y_data = [0.0, 10.0, 20.0, 40.0, 50.0] - - def callback(sender, app_data): - - _helper_data = app_data[0] - transformed_x = app_data[1] - transformed_y = app_data[2] - #transformed_y1 = app_data[3] # for channel = 3 - #transformed_y2 = app_data[4] # for channel = 4 - #transformed_y3 = app_data[5] # for channel = 5 - mouse_x_plot_space = _helper_data["MouseX_PlotSpace"] # not used in this example - mouse_y_plot_space = _helper_data["MouseY_PlotSpace"] # not used in this example - mouse_x_pixel_space = _helper_data["MouseX_PixelSpace"] - mouse_y_pixel_space = _helper_data["MouseY_PixelSpace"] - dpg.delete_item(sender, children_only=True, slot=2) - dpg.push_container_stack(sender) - dpg.configure_item("demo_custom_series", tooltip=False) - for i in range(0, len(transformed_x)): - dpg.draw_text((transformed_x[i]+15, transformed_y[i]-15), str(i), size=20) - dpg.draw_circle((transformed_x[i], transformed_y[i]), 15, fill=(50+i*5, 50+i*50, 0, 255)) - if mouse_x_pixel_space < transformed_x[i]+15 and mouse_x_pixel_space > transformed_x[i]-15 and mouse_y_pixel_space > transformed_y[i]-15 and mouse_y_pixel_space < transformed_y[i]+15: - dpg.draw_circle((transformed_x[i], transformed_y[i]), 30) - dpg.configure_item("demo_custom_series", tooltip=True) - dpg.set_value("custom_series_text", "Current Point: " + str(i)) - dpg.pop_container_stack() - - with dpg.window(label="Tutorial") as win: - dpg.add_text("Hover an item for a custom tooltip!") - with dpg.plot(label="Custom Series", height=400, width=-1): - dpg.add_plot_legend() - xaxis = dpg.add_plot_axis(dpg.mvXAxis) - with dpg.plot_axis(dpg.mvYAxis): - with dpg.custom_series(x_data, y_data, 2, label="Custom Series", callback=callback, tag="demo_custom_series"): - dpg.add_text("Current Point: ", tag="custom_series_text") - dpg.fit_axis_data(dpg.top_container_stack()) - - dpg.set_primary_window(win, True) - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Colors and Styles ------------------ - -The color and styles of a plot and series can be changed using theme app item - -.. seealso:: - For more information on item values :doc:`../documentation/themes` - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - sindatax = [] - sindatay = [] - for i in range(0, 100): - sindatax.append(i / 100) - sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) - sindatay2 = [] - for i in range(0, 100): - sindatay2.append(2 + 0.5 * sin(50 * i / 100)) - - with dpg.window(label="Tutorial", width=500, height=400): - # create a theme for the plot - with dpg.theme(tag="plot_theme"): - with dpg.theme_component(dpg.mvStemSeries): - dpg.add_theme_color(dpg.mvPlotCol_Line, (150, 255, 0), category=dpg.mvThemeCat_Plots) - dpg.add_theme_style(dpg.mvPlotStyleVar_Marker, dpg.mvPlotMarker_Diamond, category=dpg.mvThemeCat_Plots) - dpg.add_theme_style(dpg.mvPlotStyleVar_MarkerSize, 7, category=dpg.mvThemeCat_Plots) - - with dpg.theme_component(dpg.mvScatterSeries): - dpg.add_theme_color(dpg.mvPlotCol_Line, (60, 150, 200), category=dpg.mvThemeCat_Plots) - dpg.add_theme_style(dpg.mvPlotStyleVar_Marker, dpg.mvPlotMarker_Square, category=dpg.mvThemeCat_Plots) - dpg.add_theme_style(dpg.mvPlotStyleVar_MarkerSize, 4, category=dpg.mvThemeCat_Plots) - - # create plot - with dpg.plot(tag="plot", label="Line Series", height=-1, width=-1): - - # optionally create legend - dpg.add_plot_legend() - - # REQUIRED: create x and y axes - dpg.add_plot_axis(dpg.mvXAxis, label="x") - dpg.add_plot_axis(dpg.mvYAxis, label="y", tag="yaxis") - - # series belong to a y axis - dpg.add_stem_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent="yaxis", tag="series_data") - dpg.add_scatter_series(sindatax, sindatay2, label="2 + 0.5 * sin(x)", parent="yaxis", tag="series_data2") - - # apply theme to series - dpg.bind_item_theme("series_data", "plot_theme") - dpg.bind_item_theme("series_data2", "plot_theme") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Colormaps ---------- - -Under construction - -Gallery -------- - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/controls.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/dnd.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/pie.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/query.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/bars.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/rt.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/stem.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/markers.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/shaded.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/candle.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/heat.gif - -.. image:: https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/tables.gif diff --git a/docs/source/documentation/popups.rst b/docs/source/documentation/popups.rst deleted file mode 100644 index 11dda6d06..000000000 --- a/docs/source/documentation/popups.rst +++ /dev/null @@ -1,104 +0,0 @@ -Popups -====== - -Popups are windows that disappear when clicked outside of the popup's border. - -They are typically used as context menus when right-clicking an item or as dialogs. - -In DPG, popups are just windows with *popup* set to **True**, *show* set to **False**, -and a *clicked_handler* attached to a widget that shows the window when clicked. - -Normally when used, a popup will be shown until you click away from it. -By default, a right click activates the popup. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - dpg.add_text("Right Click Me") - - with dpg.popup(dpg.last_item()): - dpg.add_text("A popup") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/wiki_images/popups1.PNG - -Modal Usage ------------ - -When the modal keyword is set to **True**, the popup will be modal. - -This prevents the user from interacting with other windows until the popup is closed. -You must hide or delete the popup to remove it. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - dpg.add_text("Left Click Me") - - # check out simple module for details - with dpg.popup(dpg.last_item(), mousebutton=dpg.mvMouseButton_Left, modal=True, tag="modal_id"): - dpg.add_button(label="Close", callback=lambda: dpg.configure_item("modal_id", show=False)) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/wiki_images/popup2.PNG - -Mouse Button options include: - * _mvMouseButton_Right_ - * _mvMouseButton_Left_ - * _mvMouseButton_Middle_ - * _mvMouseButton_X1_ - * _mvMouseButton_X2_ - -Window as Dialog Popup ----------------------- - -This is an example of a window made into a typical dialog. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Delete Files", modal=True, show=False, tag="modal_id", no_title_bar=True): - dpg.add_text("All those beautiful files will be deleted.\nThis operation cannot be undone!") - dpg.add_separator() - dpg.add_checkbox(label="Don't ask me next time") - with dpg.group(horizontal=True): - dpg.add_button(label="OK", width=75, callback=lambda: dpg.configure_item("modal_id", show=False)) - dpg.add_button(label="Cancel", width=75, callback=lambda: dpg.configure_item("modal_id", show=False)) - - with dpg.window(label="Tutorial"): - dpg.add_button(label="Open Dialog", callback=lambda: dpg.configure_item("modal_id", show=True)) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/primary-window.rst b/docs/source/documentation/primary-window.rst deleted file mode 100644 index 6c0591ea1..000000000 --- a/docs/source/documentation/primary-window.rst +++ /dev/null @@ -1,24 +0,0 @@ -Primary Window -============== - -The primary window fills the viewport, resizes with the viewport and remains behind other windows. - -A window can be set as the primary window by using the -:py:func:`set_primary_window ` -command using the required True/False allows the window to be set or unset. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(tag="Primary Window"): - dpg.add_text("Hello, world") - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.set_primary_window("Primary Window", True) - dpg.start_dearpygui() - dpg.destroy_context() \ No newline at end of file diff --git a/docs/source/documentation/render-loop.rst b/docs/source/documentation/render-loop.rst deleted file mode 100644 index 7d597b0cb..000000000 --- a/docs/source/documentation/render-loop.rst +++ /dev/null @@ -1,38 +0,0 @@ -Render Loop -=========== - -The render loop (or event loop) runs continously and is responsible for polling user input and drawing widgets. - -Drawing the items is how the DPG appears to update items. DPG does this at the rate of your monitor refresh when -:py:func:`set_viewport_vsync ` -is set **True**. If vsync is set **False** the render loop will run as fast possible. - -If you try to run too many computationally expensive operations inside the render loop, you may reduce -the frame rate of your application. - -For most use cases the render loop does not need to be considered -and is completely handled by :py:func:`start_dearpygui `. - -For more advanced use cases full access to the render loop can be acced like so: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - - with dpg.window(label="Example Window"): - dpg.add_text("Hello, world") - - dpg.show_viewport() - - # below replaces, start_dearpygui() - while dpg.is_dearpygui_running(): - # insert here any code you would like to run in the render loop - # you can manually stop by using stop_dearpygui() - print("this will run every frame") - dpg.render_dearpygui_frame() - - dpg.destroy_context() \ No newline at end of file diff --git a/docs/source/documentation/simple-plots.rst b/docs/source/documentation/simple-plots.rst deleted file mode 100644 index 142757b8a..000000000 --- a/docs/source/documentation/simple-plots.rst +++ /dev/null @@ -1,61 +0,0 @@ -Simple Plots -============ - -Simple plots take in a list and plot y-axis data against the -number of items in the list. These can be line graphs or histograms -and are demonstrated below - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", width=500, height=500): - dpg.add_simple_plot(label="Simpleplot1", default_value=(0.3, 0.9, 0.5, 0.3), height=300) - dpg.add_simple_plot(label="Simpleplot2", default_value=(0.3, 0.9, 2.5, 8.9), overlay="Overlaying", height=180, - histogram=True) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -You can change the simple plot's data using *set_value*. - -Here we are using a mouse move handler and each callback that runs will set the -plot data to make it animated! - -.. code-block:: python - - import dearpygui.dearpygui as dpg - from math import sin - - dpg.create_context() - - - def update_plot_data(sender, app_data, plot_data): - mouse_y = app_data[1] - if len(plot_data) > 100: - plot_data.pop(0) - plot_data.append(sin(mouse_y / 30)) - dpg.set_value("plot", plot_data) - - - data = [] - with dpg.window(label="Tutorial", width=500, height=500): - dpg.add_simple_plot(label="Simple Plot", min_scale=-1.0, max_scale=1.0, height=300, tag="plot") - - with dpg.handler_registry(): - dpg.add_mouse_move_handler(callback=update_plot_data, user_data=data) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/wiki_images/simple_plots.PNG \ No newline at end of file diff --git a/docs/source/documentation/staging.rst b/docs/source/documentation/staging.rst deleted file mode 100644 index a6bd35e37..000000000 --- a/docs/source/documentation/staging.rst +++ /dev/null @@ -1,186 +0,0 @@ -Staging -======= - -The staging system is used to create items or item hierarchies where -the parent/root is to be decided at a later time. - -Staged items are not submitted for rendering. - -Staged items will show up in the item registry. - -Items can be moved out of staging by using :py:func:`move_item `. - - - -The most basic example can be found below: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def stage_items(): - with dpg.stage(tag="stage1"): - dpg.add_text("hello, i was added from a stage", tag="text_tag") - - def present_stage_items(): - dpg.move_item("text_tag", parent="main_win") - - with dpg.window(label="Tutorial", tag="main_win"): - dpg.add_button(label="stage items", callback=stage_items) - dpg.add_button(label="present stages items", callback=present_stage_items) - - dpg.show_item_registry() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Prefered way to "unstage" items is -using :py:func:`unstage `. -This will place the items as if they were newly created items according to -the standard rules of :doc:`../documentation/container-stack`. - -Also using the unstage command will automatically clean up the stage container. - -Using :py:func:`push_container_stack ` and -:py:func:`pop_container_stack ` is recomended here as it -provides better performance when unstaging. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def stage_items(): - with dpg.stage(tag="stage1"): - dpg.add_text("hello, i was added from a stage") - dpg.add_text("hello, i was added from a stage") - dpg.add_text("hello, i was added from a stage") - dpg.add_text("hello, i was added from a stage") - dpg.add_text("hello, i was added from a stage") - - def present_stage_items(): - dpg.push_container_stack("main_win") - dpg.unstage("stage1") - dpg.pop_container_stack() - - with dpg.window(label="Tutorial", tag="main_win", height=400, width=400): - dpg.add_button(label="stage items", callback=stage_items) - dpg.add_button(label="present stages items", callback=present_stage_items) - - dpg.show_item_registry() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Wrapping Items with Classes ---------------------------- - -The most obvious benefit of this system is for advanced users -who are wrapping DPG items into classes. Rather than having -to duplicate the various configurable options as members of the class -(to avoid making calls to :py:func:`configure_item ` -or :py:func:`get_item_configuration ` -before the item is actually created), you can create and stage the item in the -constructor of the wrapping class! - -Below are 2 examples: - -**Example 1** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - - class Button: - - def __init__(self, label): - with dpg.stage() as self._staging_container_id: - self._id = dpg.add_button(label=label) - - def set_callback(self, callback): - dpg.set_item_callback(self._id, callback) - - def get_label(self): - return dpg.get_item_label(self._id) - - def submit(self, parent): - dpg.push_container_stack(parent) - dpg.unstage(self._staging_container_id) - dpg.pop_container_stack() - - my_button = Button("Press me") - my_button.set_callback(lambda: print("I've been pressed!")) - - print(my_button.get_label()) - - with dpg.window(label="Tutorial", tag="main_win"): - dpg.add_text("hello world") - - my_button.submit("main_win") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Example 2** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - - class Window: - - def __init__(self, label): - self._children = [] - with dpg.stage() as stage: - self.id = dpg.add_window(label=label) - self.stage = stage - - def add_child(self, child): - dpg.move_item(child.id, parent=self.id) - - def submit(self): - dpg.unstage(self.stage) - - - class Button: - - def __init__(self, label): - with dpg.stage(): - self.id = dpg.add_button(label=label) - - def set_callback(self, callback): - dpg.set_item_callback(self.id, callback) - - - my_button = Button("Press me") - my_button.set_callback(lambda: print("I've been pressed!")) - - my_window = Window("Tutorial") - - my_window.add_child(my_button) - - my_window.submit() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/documentation/tables.rst b/docs/source/documentation/tables.rst deleted file mode 100644 index 1d444a833..000000000 --- a/docs/source/documentation/tables.rst +++ /dev/null @@ -1,499 +0,0 @@ -Tables -====== - -The table API is a low level API that can be used to create tables. - -It can also be used as a layout mechanism. Tables are composed of -multiple components which include columns, rows, cells, and the -actual items to be displayed. The best place to learn about the various -configuration options for the table is by running the demo! - -Below is the minimum example for creating a table - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - with dpg.table(header_row=False): - - # use add_table_column to add columns to the table, - # table columns use child slot 0 - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - # add_table_next_column will jump to the next row - # once it reaches the end of the columns - # table next column use slot 1 - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - dpg.add_text(f"Row{i} Column{j}") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. note:: The maximum number of columns is 64. - -multiple items can go into a single cell by creating a cell as shown - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.table(header_row=False, resizable=True, policy=dpg.mvTable_SizingStretchProp, - borders_outerH=True, borders_innerV=True, borders_innerH=True, borders_outerV=True): - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - # once it reaches the end of the columns - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - with dpg.table_cell(): - dpg.add_button(label=f"Row{i} Column{j} a") - dpg.add_button(label=f"Row{i} Column{j} b") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Borders, Background -------------------- - -You can control the borders of the table using the -`borders_innerH`, `borders_innerV`, `borders_outerH`, -and `borders_outerV` keywords. You can also turn on alternate -row coloring using the `row_background` keyword. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.table(header_row=False, row_background=True, - borders_innerH=True, borders_outerH=True, borders_innerV=True, - borders_outerV=True): - - # use add_table_column to add columns to the table, - # table columns use child slot 0 - dpg.add_table_column() - dpg.add_table_column() - dpg.add_table_column() - - # add_table_next_column will jump to the next row - # once it reaches the end of the columns - # table next column use slot 1 - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - dpg.add_text(f"Row{i} Column{j}") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Column Headers --------------- - -Column headers are simply shown by setting `header_row` to **True** -and setting the label of the columns. - -**Code** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.table(header_row=True): - - # use add_table_column to add columns to the table, - # table columns use slot 0 - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - # add_table_next_column will jump to the next row - # once it reaches the end of the columns - # table next column use slot 1 - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - dpg.add_text(f"Row{i} Column{j}") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Resizing --------- - -In order for a table to have resizable columns, -the `resizable` and `borders_innerV` keywords must be set to **True**. - -You can also set the sizing policy -keyword, `policy`, using the following options - - - Policy: - | mvTable_SizingFixedFit - | mvTable_SizingFixedSame - | mvTable_SizingStretchProp - | mvTable_SizingStretchSame - -Stretch -------- - -Below is an example of setting the stretch policy for the entire table - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.table(header_row=False, resizable=True, policy=dpg.mvTable_SizingStretchProp, - borders_outerH=True, borders_innerV=True, borders_outerV=True): - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - - # add_table_next_column will jump to the next row - # once it reaches the end of the columns - # table next column use slot 1 - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - dpg.add_text(f"Row{i} Column{j}") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Fixed** - -Below is an example of setting the fixed fit policy for the entire table - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - # Only available if scrollX/scrollY are disabled and stretch columns are not used - with dpg.table(header_row=False, policy=dpg.mvTable_SizingFixedFit, resizable=True, no_host_extendX=True, - borders_innerV=True, borders_outerV=True, borders_outerH=True): - - dpg.add_table_column(label="Header 1") - dpg.add_table_column(label="Header 2") - dpg.add_table_column(label="Header 3") - for i in range(0, 4): - with dpg.table_row(): - for j in range(0, 3): - dpg.add_button(label=f"Row{i} Column{j} a") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Mixed** - -You can also set columns individually by using the -`width_fixed` or `width_stretch` keyword along with the -`init_width_or_weight` keyword. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True, - resizable=True, no_host_extendX=False, hideable=True, - borders_innerV=True, borders_outerV=True, borders_innerH=True, - borders_outerH=True): - - dpg.add_table_column(label="AAA", width_fixed=True) - dpg.add_table_column(label="BBB", width_fixed=True) - dpg.add_table_column(label="CCC", width_stretch=True, init_width_or_weight=0.0) - dpg.add_table_column(label="DDD", width_stretch=True, init_width_or_weight=0.0) - - for i in range(0, 5): - with dpg.table_row(): - for j in range(0, 4): - if j == 2 or j == 3: - dpg.add_text(f"Stretch {i},{j}") - else: - dpg.add_text(f"Fixed {i}, {j}") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Column Options --------------- - -There are a large number of options available for table columns -which are best learned through running the demo, these include - -====================== ============= =========== -keyword default value description -====================== ============= =========== -init_width_or_weight 0.0 sets the starting width (fixed policy) or proportion (stretch) of the column. -default_hide False Default as a hidden/disabled column. -default_sort False Default as a sorting column. -width_stretch False Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). -width_fixed False Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). -no_resize False Disable manual resizing. -no_reorder False Disable manual reordering this column, this will also prevent other columns from crossing over this column. -no_hide False Disable ability to hide/disable this column. -no_clip False Disable clipping for this column. -no_sort False Disable sorting for this column. -no_sort_ascending False Disable ability to sort in the ascending direction. -no_sort_descending False Disable ability to sort in the descending direction. -no_header_width False Disable header text width contribution to automatic column width. -prefer_sort_ascending True Make the initial sort direction Ascending when first sorting on this column (default). -prefer_sort_descending False Make the initial sort direction Descending when first sorting on this column. -indent_enabled False Use current Indent value when entering cell (default for column 0). -indent_disable False Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. -====================== ============= =========== - -Sorting -------- - -DPG does not actually do any sorting for you. The table API is a -more general purpose API and it is up to the library user to handle sorting. -To sort a table based on user interaction, you must assign a callback to the table. -This callback will be ran when a user tries to sort a table by clicking on the table's column headers. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - def sort_callback(sender, sort_specs): - - # sort_specs scenarios: - # 1. no sorting -> sort_specs == None - # 2. single sorting -> sort_specs == [[column_id, direction]] - # 3. multi sorting -> sort_specs == [[column_id, direction], [column_id, direction], ...] - # - # notes: - # 1. direction is ascending if == 1 - # 2. direction is ascending if == -1 - - # no sorting case - if sort_specs is None: return - - rows = dpg.get_item_children(sender, 1) - - # create a list that can be sorted based on first cell - # value, keeping track of row and value used to sort - sortable_list = [] - for row in rows: - first_cell = dpg.get_item_children(row, 1)[0] - sortable_list.append([row, dpg.get_value(first_cell)]) - - def _sorter(e): - return e[1] - - sortable_list.sort(key=_sorter, reverse=sort_specs[0][1] < 0) - - # create list of just sorted row ids - new_order = [] - for pair in sortable_list: - new_order.append(pair[0]) - - dpg.reorder_items(sender, 1, new_order) - - with dpg.window(label="Tutorial", width=500): - - with dpg.table(header_row=True, borders_innerH=True, borders_outerH=True, - borders_innerV=True, borders_outerV=True, row_background=True, - sortable=True, callback=sort_callback): - - dpg.add_table_column(label="One") - dpg.add_table_column(label="Two", no_sort=True) - - for i in range(25): - with dpg.table_row(): - dpg.add_input_int(label=" ", step=0, default_value=i) - dpg.add_text(f"Cell {i}, 1") - - # main loop - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Scrolling ---------- - -Under construction - -Selecting ---------- - -You can make rows and/or cells selectable by adding a `selectable` to the table -and assigning a callback to it. Use a theme to control the hover style. The -`span_columns` option of the `selectable` is used to control whether -the row or the cell is selectable. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.theme() as table_theme: - with dpg.theme_component(dpg.mvTable): - # dpg.add_theme_color(dpg.mvThemeCol_HeaderHovered, (255, 0, 0, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - dpg.add_theme_color(dpg.mvThemeCol_Header, (0, 0, 0, 0), category=dpg.mvThemeCat_Core) - - def clb_selectable(sender, app_data, user_data): - print(f"Row {user_data}") - - with dpg.window(tag="Selectable Tables"): - with dpg.table(tag="SelectRows", header_row=True) as selectablerows: - dpg.add_table_column(label="First") - dpg.add_table_column(label="Second") - dpg.add_table_column(label="Third") - - for i in range(15): - with dpg.table_row(): - for j in range(3): - dpg.add_selectable(label=f"Row{i} Column{j}", span_columns=True, callback=clb_selectable, user_data=i) - dpg.bind_item_theme(selectablerows, table_theme) - - with dpg.table(tag="SelectCells", header_row=True) as selectablecells: - dpg.add_table_column(label="First") - dpg.add_table_column(label="Second") - dpg.add_table_column(label="Third") - - for i in range(15): - with dpg.table_row(): - for j in range(3): - dpg.add_selectable(label=f"Row{i} Column{j}", callback=clb_selectable, user_data=(i,j)) - dpg.bind_item_theme(selectablecells, table_theme) - - dpg.create_viewport(width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Clipping --------- - -Using a clipper can help performance with large tables. - -Try using the example below with and with out clipping and see -the effect on the framerate listed in metrics. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - - def clipper_toggle(sender): - dpg.configure_item("table_clip", clipper=dpg.get_value(sender)) - - - with dpg.window(label="Tutorial"): - dpg.add_checkbox(label="clipper", callback=clipper_toggle, default_value=True) - - with dpg.table(header_row=False, tag="table_clip", clipper=True): - - for i in range(5): - dpg.add_table_column() - - for i in range(30000): - with dpg.table_row(): - for j in range(5): - dpg.add_text(f"Row{i} Column{j}") - - dpg.show_metrics() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Filtering ---------- - -Under construction - -Padding -------- -Under construction - -Outer Size ----------- - -Under construction - -Column Widths -------------- - -Under construction - -Row Height ----------- - -Under construction - -Search Delay ------------- - -Under construction diff --git a/docs/source/documentation/textures.rst b/docs/source/documentation/textures.rst deleted file mode 100644 index e74661c4e..000000000 --- a/docs/source/documentation/textures.rst +++ /dev/null @@ -1,296 +0,0 @@ -Textures & Images -================= - -DPG uses the Graphics Processing Unit (GPU) to create the graphical user interface(GUI) you see. -To display an image, you must first create a texture with the image data that can then be -uploaded to the GPU. These textures belong to a texture registry. - -We offer 3 types of textures - -* Static -* Dynamic -* Raw - -This textures are then used in the following App Items - -* **mvDrawImage** -* **mvImage** -* **mvImageButton** -* **mvImageSeries** - -They are always 1D lists or arrays. - -Using the keyword Show on the texture registry will open the texture registry. - -Static Textures ---------------- - -Static textures are used for images that do not change often. -They are typically loaded at startup. If they need to be updated, -you would delete and recreate them. These accept python lists, tuples, numpy arrays, -and any type that supports python's buffer protocol with contiguous data. Below is a simple example - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - texture_data = [] - for i in range(0, 100 * 100): - texture_data.append(255 / 255) - texture_data.append(0) - texture_data.append(255 / 255) - texture_data.append(255 / 255) - - with dpg.texture_registry(show=True): - dpg.add_static_texture(width=100, height=100, default_value=texture_data, tag="texture_tag") - - with dpg.window(label="Tutorial"): - dpg.add_image("texture_tag") - - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -The texture can be deleted with `dpg.delete_item("texture_tag")`. However, for the tag/alias to be released items that use `"texture_tag"` (such as a plot series) must also be deleted. - -Dynamic Textures ----------------- - -Dynamic textures are used for small to medium sized textures that can change per frame. -These can be updated with -:py:func:`set_value ` -but the width and height must be the same as -when the texture was first created. These are similar to raw textures except these perform -safety checks and conversion. Below is a simple example - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - texture_data = [] - for i in range(0, 100 * 100): - texture_data.append(255 / 255) - texture_data.append(0) - texture_data.append(255 / 255) - texture_data.append(255 / 255) - - with dpg.texture_registry(show=True): - dpg.add_dynamic_texture(width=100, height=100, default_value=texture_data, tag="texture_tag") - - - def _update_dynamic_textures(sender, app_data, user_data): - new_color = dpg.get_value(sender) - new_color[0] = new_color[0] / 255 - new_color[1] = new_color[1] / 255 - new_color[2] = new_color[2] / 255 - new_color[3] = new_color[3] / 255 - - new_texture_data = [] - for i in range(0, 100 * 100): - new_texture_data.append(new_color[0]) - new_texture_data.append(new_color[1]) - new_texture_data.append(new_color[2]) - new_texture_data.append(new_color[3]) - - dpg.set_value("texture_tag", new_texture_data) - - - with dpg.window(label="Tutorial"): - dpg.add_image("texture_tag") - dpg.add_color_picker((255, 0, 255, 255), label="Texture", - no_side_preview=True, alpha_bar=True, width=200, - callback=_update_dynamic_textures) - - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Raw Textures ------------- - -Raw textures are used in the same way as dynamic textures. The main differences - -* Only accepts arrays (numpy, python, etc.) -* No safety checks are performed. - -These textures are used for high performance applications that require updating large -textures every frame. Below is a simple example - -.. code-block:: python - - import dearpygui.dearpygui as dpg - import array - - dpg.create_context() - - - texture_data = [] - for i in range(0, 100 * 100): - texture_data.append(255 / 255) - texture_data.append(0) - texture_data.append(255 / 255) - texture_data.append(255 / 255) - - raw_data = array.array('f', texture_data) - - with dpg.texture_registry(show=True): - dpg.add_raw_texture(width=100, height=100, default_value=raw_data, format=dpg.mvFormat_Float_rgba, tag="texture_tag") - - - def update_dynamic_texture(sender, app_data, user_data): - new_color = dpg.get_value(sender) - new_color[0] = new_color[0] / 255 - new_color[1] = new_color[1] / 255 - new_color[2] = new_color[2] / 255 - new_color[3] = new_color[3] / 255 - - for i in range(0, 100 * 100 * 4): - raw_data[i] = new_color[i % 4] - - - with dpg.window(label="Tutorial"): - dpg.add_image("texture_tag") - dpg.add_color_picker((255, 0, 255, 255), label="Texture", - no_side_preview=True, alpha_bar=True, width=200, - callback=update_dynamic_texture) - - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Formats -------- - -The following formats are currently supported - -======================= ============== =============== =========== -Format Static Texture Dynamic Texture Raw Texture -======================= ============== =============== =========== -**mvFormat_Float_rgba** ✅ ✅ ✅ -**mvFormat_Float_rgb** - - ✅* -**mvFormat_Int_rgba** - - - -**mvFormat_Int_rgb** - - * -======================= ============== =============== =========== - -.. note:: - | **mvFormat_Float_rgb** not currently supported on MacOS - | More formats will be added in the future. - -Loading Images --------------- - -DPG provides the function -:py:func:`load_image ` -for loading image data from a file. - -This function returns a tuple where - -* 0 -> width -* 1 -> height -* 2 -> channels -* 3 -> data (1D array, mvBuffer) - -On failure, returns **None**. - -The accepted file types include: - - * JPEG (no 12-bit-per-channel JPEG OR JPEG with arithmetic coding) - * PNG - * BMP - * PSD - * GIF - * HDR - * PIC - * PPM - * PGM - -A simple example can be found below - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - width, height, channels, data = dpg.load_image("Somefile.png") - - with dpg.texture_registry(show=True): - dpg.add_static_texture(width=width, height=height, default_value=data, tag="texture_tag") - - with dpg.window(label="Tutorial"): - dpg.add_image("texture_tag") - - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - - -Saving Images --------------- - -**New in 1.4**. DPG provides the function -:py:func:`save_image ` -for saving image data to a file. - -The image is a rectangle of pixels stored from left-to-right, top-to-bottom. -Each pixel contains up to 4 components of data interleaved with 8-bits per -channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. ( Y is monochrome color.) - -PNG creates output files with the same number of components as the input. -The BMP format expands Y to RGB in the file format and does not -output alpha. - -Additional options will will be released with v1.4.1. - -The accepted file types include: - - * PNG - * JPG (new in v1.4.1) - * BMP (new in v1.4.1) - * TGA (new in v1.4.1) - * HDR (new in v1.4.1) - -File type is determined by extension. Must be lowercase (png, jpg, bmp, tga, hdr). - -A simple example can be found below - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - width, height = 255, 255 - - data = [] - for i in range(width*height): - data.append(255) - data.append(255) - data.append(0) - - with dpg.window(label="Tutorial"): - dpg.add_button(label="Save Image", callback=lambda:dpg.save_image(file="newImage.png", width=width, height=height, data=data, components=3)) - - dpg.show_viewport() - while dpg.is_dearpygui_running(): - dpg.render_dearpygui_frame() - - dpg.destroy_context() diff --git a/docs/source/documentation/themes.rst b/docs/source/documentation/themes.rst deleted file mode 100644 index 372960b31..000000000 --- a/docs/source/documentation/themes.rst +++ /dev/null @@ -1,422 +0,0 @@ -Themes -====== - -Themes are containers which are composed of: - Theme Components: - containers within a theme that can specify an item type the theme colors/styles target - Theme Colors: - items that are added to a theme component and set colors - Theme Styles: - items that are added to a theme component and set styles - -The theme can be: - -* bound as the default theme. This will have a global effect across all windows and propagate. -* bound to a container. This will propagate to its children if applicable theme components are in the theme. -* bound to an item type if applicable theme components are in the theme. - -Theme components must have a specified item type. This can either be *mvAll* for all items or a specific item type. - -Style and color items have a named constant and will apply that constant to their components named item type. -Style and color items must have a named category. Constants contain their category in the name. - -Theme colors and styles fall into the following categories: - -**mvThemeCat_Plots**: - Items that are associated with plots. Style/color constants identified by *mvPlotCol_\*\*\** or *mvPlotStyle_\*\*\** - -**mvThemeCat_Nodes**: - Items that are associated with Nodes. Style/color constants identified by *mvNodeCol_\*\*\** or *mvNodeStyle_\*\*\** - -**mvThemeCat_Core**: - All other items within dearpygui. Style/color constants identified by *mvThemeCol_\*\*\** or *mvThemeStyle_\*\*\** - -Default Theme (global) ----------------------- - -Default themes will apply the theme globally across all windows and propagate to children. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", pos=(20, 50), width=275, height=225) as win1: - t1 = dpg.add_input_text(default_value="some text") - t2 = dpg.add_input_text(default_value="some text") - with dpg.child_window(height=100): - t3 = dpg.add_input_text(default_value="some text") - dpg.add_input_int() - dpg.add_input_text(default_value="some text") - - with dpg.window(label="Tutorial", pos=(320, 50), width=275, height=225) as win2: - dpg.add_input_text(default_value="some text") - dpg.add_input_int() - - with dpg.theme() as global_theme: - - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (255, 140, 23), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme_component(dpg.mvInputInt): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (140, 255, 23), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - dpg.bind_theme(global_theme) - - dpg.show_style_editor() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Container Propagation ---------------------- - -Applying a theme to a container will propagate the theme to its children: - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", pos=(20, 50), width=275, height=225) as win1: - t1 = dpg.add_input_text(default_value="some text") - t2 = dpg.add_input_text(default_value="some text") - with dpg.child_window(height=100): - t3 = dpg.add_input_text(default_value="some text") - dpg.add_input_int() - dpg.add_input_text(default_value="some text") - - with dpg.window(label="Tutorial", pos=(320, 50), width=275, height=225) as win2: - dpg.add_input_text(default_value="some text") - dpg.add_input_int() - - with dpg.theme() as container_theme: - - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (150, 100, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme_component(dpg.mvInputInt): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (100, 150, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - dpg.bind_item_theme(win1, container_theme) - - dpg.show_style_editor() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Item Specific -------------- - -Applying a theme to an item will overide any previous themes on the specified item if the theme contains an applicable component. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", pos=(20, 50), width=275, height=225) as win1: - t1 = dpg.add_input_text(default_value="some text") - t2 = dpg.add_input_text(default_value="some text") - with dpg.child_window(height=100): - t3 = dpg.add_input_text(default_value="some text") - dpg.add_input_int() - dpg.add_input_text(default_value="some text") - - with dpg.window(label="Tutorial", pos=(320, 50), width=275, height=225) as win2: - dpg.add_input_text(default_value="some text") - dpg.add_input_int() - - with dpg.theme() as item_theme: - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (200, 200, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 0, category=dpg.mvThemeCat_Core) - - dpg.bind_item_theme(t2, item_theme) - - dpg.show_style_editor() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Priority of Themes ------------------- - -The theme prioritizes the latest applied theme in the order of - -1. specific item -2. container inherited -3. global - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial", pos=(20, 50), width=275, height=225) as win1: - t1 = dpg.add_input_text(default_value="some text") - t2 = dpg.add_input_text(default_value="some text") - with dpg.child_window(height=100): - t3 = dpg.add_input_text(default_value="some text") - dpg.add_input_int() - dpg.add_input_text(default_value="some text") - - with dpg.window(label="Tutorial", pos=(320, 50), width=275, height=225) as win2: - dpg.add_input_text(default_value="some text") - dpg.add_input_int() - - with dpg.theme() as global_theme: - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (255, 140, 23), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme_component(dpg.mvInputInt): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (140, 255, 23), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme() as container_theme: - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (150, 100, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme_component(dpg.mvInputInt): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (100, 150, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5, category=dpg.mvThemeCat_Core) - - with dpg.theme() as item_theme: - with dpg.theme_component(dpg.mvAll): - dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (200, 200, 100), category=dpg.mvThemeCat_Core) - dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 0, category=dpg.mvThemeCat_Core) - - dpg.bind_theme(global_theme) - dpg.bind_item_theme(win1, container_theme) - dpg.bind_item_theme(t2, item_theme) - - dpg.show_style_editor() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Theme for Disabled Items ------------------------- - -Each item has a separate disabled theme that is used when the item is disabled. -The disabled theme follows the same propagation rules as the enabled theme. -When an item's parameter *enabled* is set to *False* the item will use its disabled theme. -If no disabled theme has been set the default theme will be used. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - with dpg.theme() as disabled_theme: - with dpg.theme_component(dpg.mvInputFloat, enabled_state=False): - dpg.add_theme_color(dpg.mvThemeCol_Text, [255, 0, 0]) - dpg.add_theme_color(dpg.mvThemeCol_Button, [255, 0, 0]) - - with dpg.theme_component(dpg.mvInputInt, enabled_state=False): - dpg.add_theme_color(dpg.mvThemeCol_Text, [255, 0, 0]) - dpg.add_theme_color(dpg.mvThemeCol_Button, [255, 0, 0]) - - dpg.bind_theme(disabled_theme) - - with dpg.window(label="tutorial"): - dpg.add_input_float(label="Input float", enabled=False) - dpg.add_input_int(label="Input int", enabled=False) - - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -Plot Markers ------------- - -===================== ============== -Plot Markers -===================== ============== -mvPlotMarker_None mvPlotMarker_Circle -mvPlotMarker_Square mvPlotMarker_Diamond -mvPlotMarker_Up mvPlotMarker_Down -mvPlotMarker_Left mvPlotMarker_Right -mvPlotMarker_Cross mvPlotMarker_Plus -mvPlotMarker_Asterisk -===================== ============== - -Core Colors ------------ - -=============================== ================================ ============================ -Core Colors -=============================== ================================ ============================ -mvThemeCol_Text mvThemeCol_TabActive mvThemeCol_SliderGrabActive -mvThemeCol_TextDisabled mvThemeCol_TabUnfocused mvThemeCol_Button -mvThemeCol_WindowBg mvThemeCol_TabUnfocusedActive mvThemeCol_ButtonHovered -mvThemeCol_ChildBg mvThemeCol_DockingPreview mvThemeCol_ButtonActive -mvThemeCol_Border mvThemeCol_DockingEmptyBg mvThemeCol_Header -mvThemeCol_PopupBg mvThemeCol_PlotLines mvThemeCol_HeaderHovered -mvThemeCol_BorderShadow mvThemeCol_PlotLinesHovered mvThemeCol_HeaderActive -mvThemeCol_FrameBg mvThemeCol_PlotHistogram mvThemeCol_Separator -mvThemeCol_FrameBgHovered mvThemeCol_PlotHistogramHovered mvThemeCol_SeparatorHovered -mvThemeCol_FrameBgActive mvThemeCol_TableHeaderBg mvThemeCol_SeparatorActive -mvThemeCol_TitleBg mvThemeCol_TableBorderStrong mvThemeCol_ResizeGrip -mvThemeCol_TitleBgActive mvThemeCol_TableBorderLight mvThemeCol_ResizeGripHovered -mvThemeCol_TitleBgCollapsed mvThemeCol_TableRowBg mvThemeCol_ResizeGripActive -mvThemeCol_MenuBarBg mvThemeCol_TableRowBgAlt mvThemeCol_Tab -mvThemeCol_ScrollbarBg mvThemeCol_TextSelectedBg mvThemeCol_TabHovered -mvThemeCol_ScrollbarGrab mvThemeCol_DragDropTarget -mvThemeCol_ScrollbarGrabHovered mvThemeCol_NavHighlight -mvThemeCol_ScrollbarGrabActive mvThemeCol_NavWindowingHighlight -mvThemeCol_CheckMark mvThemeCol_NavWindowingDimBg -mvThemeCol_SliderGrab mvThemeCol_ModalWindowDimBg -=============================== ================================ ============================ - -Plot Colors ------------ - -======================= ====================== ======================= -Plot Colors -======================= ====================== ======================= -mvPlotCol_Line mvPlotCol_LegendBg mvPlotCol_AxisBgHovered -mvPlotCol_Fill mvPlotCol_LegendBorder mvPlotCol_AxisGrid -mvPlotCol_MarkerOutline mvPlotCol_LegendText mvPlotCol_AxisText -mvPlotCol_MarkerFill mvPlotCol_TitleText mvPlotCol_Selection -mvPlotCol_ErrorBar mvPlotCol_InlayText -mvPlotCol_FrameBg mvPlotCol_AxisBg -mvPlotCol_PlotBg mvPlotCol_AxisBgActive -mvPlotCol_PlotBorder mvPlotCol_Crosshairs -======================= ====================== ======================= - -Node Colors ------------ - -================================ ========================== ============================ -Node Colors -================================ ========================== ============================ -mvNodeCol_NodeBackground mvNodeCol_TitleBarSelected mvNodeCol_BoxSelector -mvNodeCol_NodeBackgroundHovered mvNodeCol_Link mvNodeCol_BoxSelectorOutline -mvNodeCol_NodeBackgroundSelected mvNodeCol_LinkHovered mvNodeCol_GridBackground -mvNodeCol_NodeOutline mvNodeCol_LinkSelected mvNodeCol_GridLine -mvNodeCol_TitleBar mvNodeCol_Pin mvNodeCol_PinHovered -mvNodeCol_TitleBarHovered -================================ ========================== ============================ - -Core Styles ------------ - -======================================= ========== -Constant Components -======================================= ========== -mvStyleVar_Alpha 1 -mvStyleVar_DisabledAlpha 1 -mvStyleVar_WindowPadding 2 -mvStyleVar_WindowRounding 1 -mvStyleVar_WindowBorderSize 1 -mvStyleVar_WindowMinSize 2 -mvStyleVar_WindowTitleAlign 2 -mvStyleVar_ChildRounding 1 -mvStyleVar_ChildBorderSize 1 -mvStyleVar_PopupRounding 1 -mvStyleVar_PopupBorderSize 1 -mvStyleVar_FramePadding 2 -mvStyleVar_FrameRounding 1 -mvStyleVar_FrameBorderSize 1 -mvStyleVar_ItemSpacing 2 -mvStyleVar_ItemInnerSpacing 2 -mvStyleVar_IndentSpacing 1 -mvStyleVar_CellPadding 2 -mvStyleVar_ScrollbarSize 1 -mvStyleVar_ScrollbarRounding 1 -mvStyleVar_GrabMinSize 1 -mvStyleVar_GrabRounding 1 -mvStyleVar_TabRounding 1 -mvStyleVar_TabBorderSize 1 -mvStyleVar_TabBarBorderSize 1 -mvStyleVar_TableAngledHeadersAngle 1 -mvStyleVar_TableAngledHeadersTextAlign 2 -mvStyleVar_ButtonTextAlign 2 -mvStyleVar_SelectableTextAlign 2 -mvStyleVar_SeparatorTextBorderSize 1 -mvStyleVar_SeparatorTextAlign 2 -mvStyleVar_SeparatorTextPadding 2 -======================================= ========== - -Plot Styles ------------ - -================================= ========== -Constant Components -================================= ========== -mvPlotStyleVar_LineWeight 1 -mvPlotStyleVar_Marker 1 -mvPlotStyleVar_MarkerSize 1 -mvPlotStyleVar_MarkerWeight 1 -mvPlotStyleVar_FillAlpha 1 -mvPlotStyleVar_ErrorBarSize 1 -mvPlotStyleVar_ErrorBarWeight 1 -mvPlotStyleVar_DigitalBitHeight 1 -mvPlotStyleVar_DigitalBitGap 1 -mvPlotStyleVar_PlotBorderSize 1 -mvPlotStyleVar_MinorAlpha 1 -mvPlotStyleVar_MajorTickLen 2 -mvPlotStyleVar_MinorTickLen 2 -mvPlotStyleVar_MajorTickSize 2 -mvPlotStyleVar_MinorTickSize 2 -mvPlotStyleVar_MajorGridSize 2 -mvPlotStyleVar_MinorGridSize 2 -mvPlotStyleVar_PlotPadding 2 -mvPlotStyleVar_LabelPadding 2 -mvPlotStyleVar_LegendPadding 2 -mvPlotStyleVar_LegendInnerPadding 2 -mvPlotStyleVar_LegendSpacing 2 -mvPlotStyleVar_MousePosPadding 2 -mvPlotStyleVar_AnnotationPadding 2 -mvPlotStyleVar_FitPadding 2 -mvPlotStyleVar_PlotDefaultSize 2 -mvPlotStyleVar_PlotMinSize 2 -================================= ========== - -Node Styles ------------ - -======================================== ========== -Constant Components -======================================== ========== -mvNodeStyleVar_GridSpacing 1 -mvNodeStyleVar_NodeCornerRounding 1 -mvNodeStyleVar_NodePaddingHorizontal 1 -mvNodeStyleVar_NodePaddingVertical 1 -mvNodeStyleVar_NodeBorderThickness 1 -mvNodeStyleVar_LinkThickness 1 -mvNodeStyleVar_LinkLineSegmentsPerLength 1 -mvNodeStyleVar_LinkHoverDistance 1 -mvNodeStyleVar_PinCircleRadius 1 -mvNodeStyleVar_PinQuadSideLength 1 -mvNodeStyleVar_PinTriangleSideLength 1 -mvNodeStyleVar_PinLineThickness 1 -mvNodeStyleVar_PinHoverRadius 1 -mvNodeStyleVar_PinOffset 1 -======================================== ========== \ No newline at end of file diff --git a/docs/source/documentation/tooltips.rst b/docs/source/documentation/tooltips.rst deleted file mode 100644 index 9d7561935..000000000 --- a/docs/source/documentation/tooltips.rst +++ /dev/null @@ -1,30 +0,0 @@ -Tooltips -======== - -Tooltips are windows that appear when an item is hovered. - -Tooltips are containers that can hold any other UI Item. - -Tooltips must have the parent argument. This is the *tag* of the parent what will show the tooltip. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - dpg.add_text("Hover me", tag="tooltip_parent") - - with dpg.tooltip("tooltip_parent"): - dpg.add_text("A tooltip") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/wiki_images/tooltips.PNG \ No newline at end of file diff --git a/docs/source/documentation/viewport.rst b/docs/source/documentation/viewport.rst deleted file mode 100644 index 0415a4f9a..000000000 --- a/docs/source/documentation/viewport.rst +++ /dev/null @@ -1,44 +0,0 @@ -Viewport -======== - -The viewport is what you traditionally call a **window** in other GUI libraries. - -In the case of DPG we call the operating system window the *viewport* -and the DPG windows as *windows*. - -Before calling :py:func:`start_dearpygui `, you must do the following: - 1. Create a viewport, using :py:func:`create_viewport `. - 2. Assign the viewport, using :py:func:`setup_dearpygui `. - 3. Show the viewport, using :py:func:`show_viewport `. - -Once the viewport has been created, you can begin -configuring the viewport using :py:func:`configure_viewport ` -or the helper commands *set_viewport_\*\*\**. - -.. note:: - Large/small icon must be set before showing the viewport (i.e. you will need to setup the viewport manually). - -.. code-block:: python - import sys - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Example Window", width=500, height=150): - dpg.add_text("Hello, world") - - dpg.create_viewport(title='Custom Title', width=600, height=200) # create viewport takes in config options too! - - # must be called before showing viewport - dpg.set_viewport_small_icon("path/to/icon.ico") - dpg.set_viewport_large_icon("path/to/icon.ico") - # On Windows it isn't possible to show the large Icon, because it gets overwritten by the OS. This line fixes this Issue. - if sys.platform.startswith('win'): - import ctypes - ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( - u'CompanyName.ProductName.SubProduct.VersionInformation') - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() diff --git a/docs/source/extra/glossary.rst b/docs/source/extra/glossary.rst deleted file mode 100644 index 8aaefc7c5..000000000 --- a/docs/source/extra/glossary.rst +++ /dev/null @@ -1,8 +0,0 @@ -Glossary -======== - -* alias - A string that takes the place of the regular **int** ID. Aliases can be used anywhere UUID's can be used. -* item - Everything in **Dear PyGui** created with a context manager or a `add_` command. -* root - An item which has no parent (i.e. window, registries, etc.) -* window - A **Dear ImGui** window created with `add_window(...)`. -* viewport - The operating system window. \ No newline at end of file diff --git a/docs/source/extra/showcase.rst b/docs/source/extra/showcase.rst deleted file mode 100644 index 9e9ed2555..000000000 --- a/docs/source/extra/showcase.rst +++ /dev/null @@ -1,51 +0,0 @@ -Showcase -======== - -The following apps have been developed with Dear PyGui by various developers. - -Tetris ------- - -Tetris is a remake of the original Tetris tile-matching game as adopted by IBM PC. -Even though Dear PyGui is not a game engine, it can easily handle graphical -animations such as these. - -The source code is available in the `Tetris Github repository`_. - -.. _Tetris Github repository: https://github.com/RahulShagri/OG-Tetris-Game - -.. image:: https://raw.githubusercontent.com/RahulShagri/OG-Tetris-Game/main/resources/demo.gif - :target: https://github.com/RahulShagri/OG-Tetris-Game - -Snake ------ - -Snake is a simple game with customisable settings for changing the -speed and colours and fixing the snake length. Entirely made with Dear PyGui. - -The source code is available in the `Snake Github repository`_. - -.. _Snake Github repository: https://github.com/RahulShagri/OG-Snake-Game - -.. image:: https://raw.githubusercontent.com/RahulShagri/OG-Snake-Game/main/resources/demo.gif - :target: https://github.com/RahulShagri/OG-Snake-Game - - -Digital Phosphor Display with RTLSDR ------------------------------------- - -`Digital Phosphor Display Video `_ - -This video demonstrates an Intensity graded FFT or Python Digital -Phosphor Display by Thomas Schucker. The accompanying `blog post`_ -shows how to create a this dynamic graph. - -The source code is available in the `Digital Phosphor Github repository`_. - -.. _blog post: https://teaandtechtime.com/python-digital-phosphor-display-with-dearpygui/ -.. _Digital Phosphor Github repository: https://github.com/Tschucker/Python-Digital-Phosphor-Display - - -.. image:: - https://raw.githubusercontent.com/Tschucker/Python-Digital-Phosphor-Display/main/images/py_digital_phosphor_gui.png - :target: https://www.youtube.com/watch?v=GPoQYTfQMxw diff --git a/docs/source/extra/video-tutorials.rst b/docs/source/extra/video-tutorials.rst deleted file mode 100644 index 9ba6582ba..000000000 --- a/docs/source/extra/video-tutorials.rst +++ /dev/null @@ -1,272 +0,0 @@ -Video Tutorials -=============== - -The following video tutorials explain various aspects of Dear PyGui, -which are outlined per video below. The first section contains all -videos by the core developers. The second section lists a great -video by the community. - -View all `video tutorials on Dear PyGui`_ by the core developers on YouTube. - -.. _video tutorials on Dear PyGui: - https://www.youtube.com/playlist?list=PLcqt7R3y3elGh7zoj1-oyygzTh9j81hKV - -`Introduction to Dear PyGui `_ ------------------------------------------------------------- - -Dear PyGui is an extended Python wrapper around Dear ImGUI. -Dear ImGUI is an Immediate Mode GUI (IMGUI) for real-time applications - -While Dear ImGui uses the fast Immediate Mode in the background, -it simulates a traditional retained mode GUI to the Python developer, -which makes it easy to work with. - -Requirements for installation: Python 3.6 and up (64-bit only) - -IDE: Setting up PyCharm, only pip install DPG is required - -How to run the built-in demo. - -Changing the default font type (OTF or TTF font) - -Creating a basic window - -Using a primary window so that the window matches the area of the viewport - - -`Basics of callbacks `_ -------------------------------------------------------- - -Callbacks are functions that are run when any action -is taken on a certain widget. - -If a widget supports it, there will be a keyword called -callback and that can be any callable. - -When using a callback, the keyword should not end with -round brackets, e.g. (). The correct way to use a callback -is: add_button("Press me", callback=func_name). The function -func_name is called without (). - -The callback always transmits two *variables* to the callback -function, e.g. sender and data. - -Sender is the name of the widget. Data is None by default, -but additional data can be sent using the following: callback_data='extra data'. - -The tutorial shows the use of a callback for a float slider. - -Throughout the tutorial, the use of the built-in logger -and documentation is demonstrated. - -The callback can be changed during runtime using set_item_callback. - -`ID system and debug tool `_ ----------------------------------------------------------- - -The first argument of a widget is the ID. - -The label defaults to the ID if no label is provided. - -Widgets need unique IDs, but can share the same label. -There are two ways to accomplish this. - -Method 1: add_input_float('Float1', label='float1') -and add_input_float('Float2', label='float1') - -Method 2: add_input_float('Float1##1') and add_input_float('Float1##2') - -ID's are used to retrieve data from widgets. - -Start the debug tool by typing show_debug() - -The debug tool lists all available commands under tab Commands - -You can execute code at runtime using the debug tool. - -Track the float values by log_debug(get_value('Float1##1')) - -`Parent stack system `_ ------------------------------------------------------- - -The parent stack is a collection of all containers in a GUI. - -A window is a root item, meaning that it can't have a parent -and doesn't need to look at the parent stack. A window is also a -container. Because it is a container, a window gets added to the parent stack. - -When an item is not a root item, it requires a parent. Every tab bar -is added to the parent stack and to a container. A tab bar is a -container itself as well. A tab is a child of tab bar, but it is also a container. - -When adding a second item of a parent, it is necessary to remove -the first item from the parent stack, e.g. pop it, so that the -second item becomes part of the containing parent and not its sibling. - -The end() command in the core module pops an item off of the parent stack. - -A checkbox or (radio) button is part of a container, -but not a container itself. - -The simple module adds the context managers (e.g. 'with window' ). -The *with* statements of the context managers automate the application -of the end() statement, making the code easier to read. - -`Value Storage System `_ -------------------------------------------------------- - -In many GUI's the widget's value is stored inside the widget. - -In Dear PyGui, a key-value pair for each widget is stored in -the value storage system. A key-value pair tracks the type of the -value and the value itself. A widget's value can be retrieved and -changed through the widget (by the user) and by the program. - -Every widget has a keyword source, which by default is equal to -the widget's name. If you specify the source, the widget will use that -key instead to look up and change values in the value storage system. -This allows several widgets to manipulate a single value. - -If multiple widgets refer to the same keyword, the type and -size have to be the same. - -Pre-add a value with add_value if you are using multiple -widgets of different types or sizes on a single key-value pair. - -A code example is given to demonstrate the value storage -system and its types and sizes. - -`Widget basics `_ ------------------------------------------------- - -This tutorial shows how to use a number of widget types. -Widget types include button, checkbox, label_text, input_int, -drag_int, radio_button, combo, listbox and progress_bar widgets. - -The use of the callback keyword of a widget is shown. For example, -add_button('Press me', callback=callback_function). - -The callback_function is called whenever that button -is pressed. The callback always sends two arguments to the -callback_function: sender and data. Sender is the name of the -widget. The 'data' argument is often empty unless the widget has -data to send or it is specified in the code. Nonetheless, the -argument 'data' is always included. - -The use of a number of widget specific keywords are discussed. - -It is demonstrated how a progress bar widget can be controlled -via a drag_int slider using set_value(...) and configure_item(...) - -Many widgets have multi-component versions as well. - -More complex use of widgets and multi-component -widgets will be shown in future videos. - -`Tab bar, tabs, and tab button basics `_ ------------------------------------------------------------------------ - -Create a tab bar with the context manager from the simple module, e.g. with tab_bar('tb1') --> with tab('t1') --> add_button('b1'). - -You can add a callback to a tab_bar using with tab_bar('tb1', callback=callback). - -You can add a button to a tab_bar using add_tab_button('+'). - -Tabs in a tab bar can be made reorderable by using the keyword reorderable=True on the tab_bar. - -`Simple Plot & Tooltip `_ ---------------------------------------------------------- - - -:doc:`../documentation/simple-plots` is for plotting simple data. -This is not to be confused with the more powerful and complex :doc:`../documentation/plots`. - -Create a basic histogram using add_simple_plot(“Plot 1”, value=[1, 4.3, 8, 9, 3], histogram=True). -There are several keywords to customise the plot. - -add_text(“Hover me”, tip=”A simple tooltip”). This simple tooltip -is only for text. The :doc:`../documentation/tooltips` is more powerful. - -The tooltip widget is a container, i.e. -context manager, just like ‘with window’ and ‘with group’. -The widget basically acts as another window, so that it can contain -any other widget, such as a graph. The example in the video shows how -to embed a simple plot in a tooltip in two lines of code. - -Note that the user cannot interact with the tooltip widget. - -`Popups `_ -------------------------------------------------------- - -:doc:`../documentation/popups` require a parent. -That may change in future versions of Dear PyGui. - -A popup is a container, so it has a context manager (with popup:). - -Popup is the only widget where the name is not the first argument. - -By default, popups are set on the right-click. To change to -left-click, add the keyword mousebutton=mvMouseButtonLeft. - -Popups are a container and can contain any other widget, i.e. plots. - -The modal keyword greys everything else out to draw attention to the popup. - -To close the modal popup, it is necessary to add a button -with a callback close_popup("popup1"). - -`Experimental Windows Docking `_ -------------------------------------------------------------------------------- - - -The docking feature enables the user to dock windows to each other and the viewport. - -The docking feature is not documented yet (as of September 2025). - -Setting the `docking` argument to `True` in `configure_app()` will enable experimental docking. - -By default, the user needs to hold the shift key to enable docking. - -Setting `docking_shift_only = False` enables docking without holding the shift key. - -Setting `docking_space = True` enables docking windows to the viewport. - -The docking feature is experimental because you cannot programmatically -set up the docking positions. - -When the feature comes out of experimental, it can also function as a -layout tool, but it still requires lots of work to be released as non-experimental. - - -`Smart tables `_ ------------------------------------------------ - -This is an elaborate tutorial on creating a smart, interactive table. - -The table is created using managed_columns. - -The widgets used in the table are add_text, -add_input_text and add_input_float - -After creating a working example, the code is -refactored into a SmartTable class with header, row and get_cell_data methods. - -A widget's label can be hidden by using ## at the beginning -of a label's name, e.g. add_input_text('##input_text_1') -where input_text_1 is not shown in the GUI. - -Using add_separator() to change the horizontal spacing of the widgets. - -Using the built-in Dear PyGui debugger and logger for solving an coding issue. - -Community Videos ----------------- - -`Creating a complete Python app with Dear PyGui `_ - -Learn how to create a fully-functional Python app step by step! -In this project, we will build a graphic user interface with the -brand new Dear PyGui library! We will connect this interface to a -Simple SMS Spam Filter, which we've built together in a previous project. -We will learn how to display images, text, user input, buttons, and separators, -as well as hiding widgets and "click" event callback functions. \ No newline at end of file diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index 71ec4ddf7..000000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,134 +0,0 @@ - -Dear PyGui's Documentation -========================== - -.. meta:: - :description lang=en: Automate building, versioning, and hosting of your - technical documentation continuously on Read the Docs. - -About DPG ---------- - -Dear PyGui is an easy-to-use, dynamic, GPU-Accelerated, cross-platform graphical -user interface toolkit(GUI) for Python. It is "built with" `Dear ImGui`_. - -Features include traditional GUI elements such as buttons, radio buttons, -menus and various methods to create a functional layout. - -Additionally, DPG has an incredible assortment of dynamic -plots, tables, drawings, debugger, and multiple resource viewers. - -DPG is well suited for creating simple user interfaces -as well as developing complex and -demanding graphical interfaces. - -DPG offers a solid framework for developing scientific, -engineering, gaming, data science and other applications that require fast and interactive interfaces. - -.. _Dear ImGui: https://github.com/ocornut/imgui - -.. toctree:: - :maxdepth: 2 - :hidden: - :caption: About DPG - - /about/what-why - /about/repo-info - -.. asdfasd - Indices and tables - ================== - * :ref:`genindex` - * :ref:`modindex` - * :ref:`search` - -Quick Start ------------ - -If you're ready to start using DPG visit -the :doc:`tutorials/first-steps` in tutorials. - -The :doc:`Tutorials ` will provide a great overview -and links to each topic in the API Reference for more detailed reading. - -However, use the API reference -for the most detailed documentation on any specific topic. - -.. toctree:: - :maxdepth: 2 - :numbered: - :hidden: - :caption: Tutorials - - /tutorials/first-steps - /tutorials/dpg-structure - /tutorials/item-usage - /tutorials/tips-resources - -Documentation -------------- - -Live Demo: - A mostly complete showcase of DPG can be found by running the - :py:func:`show_demo ` command in the :py:mod:`dearpygui.demo` module. - -Internal Documentation: - Run :py:func:`show_documentation ` - -API Reference Guide: - :doc:`Online API Reference ` - -.. toctree:: - :maxdepth: 2 - :hidden: - :caption: Documentation - - /documentation/render-loop - /documentation/viewport - /documentation/primary-window - /documentation/io-handlers-state - /documentation/item-creation - /documentation/item-id-system - /documentation/item-configuration - /documentation/item-callbacks - /documentation/item-value - /documentation/container-context-manager - /documentation/container-slots - /documentation/container-stack - /documentation/drawing-api - /documentation/file-directory-selector - /documentation/filter-set - /documentation/fonts - /documentation/init-files - /documentation/menus - /documentation/node-editor - /documentation/plots - /documentation/popups - /documentation/simple-plots - /documentation/staging - /documentation/tables - /documentation/textures - /documentation/themes - /documentation/tooltips - -.. toctree:: - :maxdepth: 2 - :hidden: - :caption: API Reference - - reference/dearpygui.rst - -More ----- - - * :doc:`../extra/showcase` - * :doc:`../extra/video-tutorials` - -.. toctree:: - :maxdepth: 2 - :hidden: - :caption: More - - /extra/showcase - /extra/video-tutorials - /extra/glossary diff --git a/docs/source/reference.rst b/docs/source/reference.rst deleted file mode 100644 index 917b3a14e..000000000 --- a/docs/source/reference.rst +++ /dev/null @@ -1,7 +0,0 @@ -Reference -========= - -.. toctree:: - :maxdepth: 3 - - reference/dearpygui.rst \ No newline at end of file diff --git a/docs/source/reference/dearpygui.rst b/docs/source/reference/dearpygui.rst deleted file mode 100644 index 1f529fdc7..000000000 --- a/docs/source/reference/dearpygui.rst +++ /dev/null @@ -1,6 +0,0 @@ -dearpygui.dearpygui -=================== - -.. automodule:: dearpygui.dearpygui - :members: - :undoc-members: \ No newline at end of file diff --git a/docs/source/tutorials/dpg-structure.rst b/docs/source/tutorials/dpg-structure.rst deleted file mode 100644 index 1d1555343..000000000 --- a/docs/source/tutorials/dpg-structure.rst +++ /dev/null @@ -1,154 +0,0 @@ -DPG Structure Overview -====================== - -.. meta:: - :description lang=en: General overview of the structure of dpg items. - -A DPG app will have an overall structure as follows: - * Setup - * Context - * Viewport - * Render Loop - * Items - * Primary Window - -Setup ------ - -All DPG apps must do 3 things: - * Create & Destroy context - * Create & Show Viewport - * Setup & Start DearPyGui - -The Context ------------ - -To access any DPG commands the context must be created with :py:func:`create_context ` -This should be the first DPG command and it's typical to perform this with an import. - -Proper clean up of DPG can be done using :py:func:`destroy_context `. - -Creating and destroying the context and also setup and start dearpygui -are useful when the DPG needs to be started and stopped multiple times in one python session. - -.. warning:: If :py:func:`create_context ` - is not first DPG will not start (and will probably crash). - -The Viewport ------------- - -The viewport is the *window* created by the operating system. - -The viewport needs to be explicitly created -using :py:func:`create_viewport ` -and shown using :py:func:`show_viewport ` - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Example Window"): - dpg.add_text("Hello, world") - dpg.add_button(label="Save") - dpg.add_input_text(label="string", default_value="Quick brown fox") - dpg.add_slider_float(label="float", default_value=0.273, max_value=1) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: For more information on the viewport :doc:`../documentation/viewport` - -The Render Loop ---------------- - -The render loop is responsible for displaying items, -partially maintaining state and callbacks. - -The render loop is completely handled -by the :py:func:`start_dearpygui ` command. - -In some cases it's necessary to explicitly create -the render loop so you can call python commands that may need to run every frame. -Such as per-frame ticker or counter update functions. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Example Window"): - dpg.add_text("Hello, world") - dpg.add_button(label="Save") - dpg.add_input_text(label="string", default_value="Quick brown fox") - dpg.add_slider_float(label="float", default_value=0.273, max_value=1) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - - # below replaces, start_dearpygui() - while dpg.is_dearpygui_running(): - # insert here any code you would like to run in the render loop - # you can manually stop by using stop_dearpygui() - print("this will run every frame") - dpg.render_dearpygui_frame() - - dpg.destroy_context() - -.. warning:: The manual render loop must be created after :py:func:`setup_dearpygui ` - -.. seealso:: For more information on the render loop :doc:`../documentation/render-loop` - -Item Overview -------------- - -DPG can be broken down into **Items**, **UI Items**, **Containers** - -Items: - Items are anything in the library (i.e. button, registries, windows, etc). - -UI Items: - Any item in DPG that has a visual component (i.e. button, listbox, window, etc). - -Containers: - Items that can hold other items. (i.e. window, groups, registries, etc). - -The Primary Window ------------------- - -DPG can assign one window to be the *primary window*. -The primary window will fill the -viewport and always be drawn behind other windows. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(tag="Primary Window"): - dpg.add_text("Hello, world") - dpg.add_button(label="Save") - dpg.add_input_text(label="string", default_value="Quick brown fox") - dpg.add_slider_float(label="float", default_value=0.273, max_value=1) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.set_primary_window("Primary Window", True) - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: for more information on the primary window :doc:`../documentation/primary-window` diff --git a/docs/source/tutorials/first-steps.rst b/docs/source/tutorials/first-steps.rst deleted file mode 100644 index ac27fc4c8..000000000 --- a/docs/source/tutorials/first-steps.rst +++ /dev/null @@ -1,82 +0,0 @@ -First Steps -=========== - -.. meta:: - :description lang=en: The starting point for the tutorial set. - -Tutorials will give a broad overview and working knowledge of DPG. Tutorials do not cover every detail -so refer to the documentation on each topic to learn more. - -Installing ----------- - -Python 3.6 (64 bit) or above is required. - -.. code-block:: - - pip install dearpygui - -First Run ---------- - -Confirm the pip install by running the code block below. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=600, height=300) - - with dpg.window(label="Example Window"): - dpg.add_text("Hello, world") - dpg.add_button(label="Save") - dpg.add_input_text(label="string", default_value="Quick brown fox") - dpg.add_slider_float(label="float", default_value=0.273, max_value=1) - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readme/first_app.gif - -Demo ----- -DPG has a complete built-in demo/showcase. It is a good idea to look into this demo. -The code for this can be found in the repo in the `demo.py`_ file - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - import dearpygui.demo as demo - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=600, height=600) - - demo.show_demo() - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readme/demo.gif - -.. note:: - The main script must always: - - - Create the context :py:func:`create_context ` - - Create the viewport :py:func:`create_viewport ` - - Setup dearpygui :py:func:`setup_dearpygui ` - - Show the viewport :py:func:`show_viewport ` - - Start dearpygui :py:func:`start_dearpygui ` - - Clean up the context :py:func:`destroy_context ` diff --git a/docs/source/tutorials/item-usage.rst b/docs/source/tutorials/item-usage.rst deleted file mode 100644 index 3ca849c36..000000000 --- a/docs/source/tutorials/item-usage.rst +++ /dev/null @@ -1,324 +0,0 @@ -Item Usage -========== - -.. meta:: - :description lang=en: General overview of DPG items. - -Creating Items --------------- - -Items are created using their *add_\*\*\** commands. - -All items must have a tag which can either be specified or are automatically generated by DPG. - -*Tags* can be either integers or strings and are -used to refer to the item after it has been created. - -Items return their tag when they are created. - -.. warning:: - Item tags must be unique if specified using the *tag* keyword. - Integers 0-10 are reserved for DPG internal items. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - b0 = dpg.add_button(label="button 0") - b1 = dpg.add_button(tag=100, label="Button 1") - dpg.add_button(tag="Btn2", label="Button 2") - - print(b0) - print(b1) - print(dpg.get_item_label("Btn2")) - - dpg.create_viewport(title='Custom Title', width=600, height=200) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. note:: Items can be created and delete at runtime see :doc:`../documentation/item-creation` - -.. seealso:: - | For more information on the creating items: - | :doc:`../documentation/item-creation` - | :doc:`../documentation/item-id-system` - -Creating Containers -------------------- - -Below we will add a window, a group and a child window to the code. -Items can either be added directly to the context manager or later -by specifying the parent. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - dpg.add_button(label="Button 1") - dpg.add_button(label="Button 2") - with dpg.group(): - dpg.add_button(label="Button 3") - dpg.add_button(label="Button 4") - with dpg.group() as group1: - pass - dpg.add_button(label="Button 6", parent=group1) - dpg.add_button(label="Button 5", parent=group1) - - dpg.create_viewport(title='Custom Title', width=600, height=400) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: - | For more information on containers: - | :doc:`../documentation/item-creation` - | :doc:`../documentation/container-context-manager` - | :doc:`../documentation/container-slots` - | :doc:`../documentation/container-stack` - -Configuration, State, Info --------------------------- - -DPG items consist of configuration, state and info. (AND value but we will cover that separately) - -Each of these can be accessed by their corresponding function - -:py:func:`get_item_configuration ` - keywords that control its appearance and behavior (label, callback, width, height) - -:py:func:`get_item_state ` - keywords that reflect its interaction (visible, hovered, clicked, etc) - -:py:func:`get_item_info ` - keywords that reflect its information (item type, children, theme, etc) - -.. note:: configuration, state and info are broken into - separate commands that access each individual keyword, - instead of returning the entire dictionary. - - | Examples: - | :py:func:`get_item_label ` - | :py:func:`is_item_hovered ` - | :py:func:`get_item_children ` - -Below we will demonstrate the ways to configure items and how to check their state -by viewing them through the item registry tool. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(label="Tutorial"): - - # configuration set when button is created - dpg.add_button(label="Apply", width=300) - - # user data and callback set any time after button has been created - btn = dpg.add_button(label="Apply 2") - dpg.set_item_label(btn, "Button 57") - dpg.set_item_width(btn, 200) - - dpg.show_item_registry() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: - | For more information on the these topics: - | :doc:`../documentation/item-configuration` - | :doc:`../documentation/io-handlers-state` - -Callbacks ---------- - -Callbacks give items functionality by assigning a function to run when they are activated -and almost all UI Items in DPG can run callbacks. - -Functions or methods are assigned as UI item callbacks when -an item is created or at a later runtime using -:py:func:`set_item_callback ` - -Callbacks may have up to 3 arguments in the following order. - -sender: - the *id* of the UI item that submitted the callback - -app_data: - occasionally UI items will send their own data (ex. file dialog) - -user_data: - any python object you want to send to the function - -.. note:: Because they are optional positional arguments you - must use the *sender* and *app_data* if you want to use *user_data* - standard keyword arguments - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def button_callback(sender, app_data, user_data): - print(f"sender is: {sender}") - print(f"app_data is: {app_data}") - print(f"user_data is: {user_data}") - - with dpg.window(label="Tutorial"): - # user data and callback set when button is created - dpg.add_button(label="Apply", callback=button_callback, user_data="Some Data") - - # user data and callback set any time after button has been created - btn = dpg.add_button(label="Apply 2", ) - dpg.set_item_callback(btn, button_callback) - dpg.set_item_user_data(btn, "Some Extra User Data") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: - For more information on the item callbacks :doc:`../documentation/item-callbacks` - -Item Values ------------ - -Almost all UI items have a *value* which can be accessed or set. - -All UI items that have a *value* also have the *default_value* parameter -which will set the items' initial starting value. - -Values can be accessed using :py:func:`get_value `. - -Below is an example of setting the *default_value* for two different items, -setting a callback to the items and printing their values. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def print_value(sender): - print(dpg.get_value(sender)) - - with dpg.window(width=300): - input_txt1 = dpg.add_input_text() - # The value for input_text2 will have a starting value - # of "This is a default value!" - input_txt2 = dpg.add_input_text( - label="InputTxt2", - default_value="This is a default value!", - callback=print_value - ) - - slider_float1 = dpg.add_slider_float() - # The slider for slider_float2 will have a starting value - # of 50.0. - slider_float2 = dpg.add_slider_float( - label="SliderFloat2", - default_value=50.0, - callback=print_value - ) - - dpg.set_item_callback(input_txt1, print_value) - dpg.set_item_callback(slider_float1, print_value) - - print(dpg.get_value(input_txt1)) - print(dpg.get_value(input_txt2)) - print(dpg.get_value(slider_float1)) - print(dpg.get_value(slider_float2)) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/Atlamillias/DearPyGui-Stuff/main/wiki%20images/dpg_using_widgets_ex1.png - - -An input item's value is changed by interacting with it. -In the above example, moving slider_float1 slider to 30.55 sets its' value to 30.55. - -We can set the position of the slider by changing items' value at runtime using -:py:func:`set_value `. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - with dpg.window(width=300): - # Creating a slider_int widget and setting the - # default value to 15. - dpg.add_slider_int(default_value=15, tag="slider_int") - - # On second thought, we're gonna set the value to 40 - # instead - for no reason in particular... - dpg.set_value("slider_int", 40) - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. image:: https://raw.githubusercontent.com/Atlamillias/DearPyGui-Stuff/main/wiki%20images/dpg_using_widgets_ex2.png - - -.. note:: - The values' type depends on the widget. (ex.) input_int default value needs to be an integer. - -.. seealso:: - For more information on item values :doc:`../documentation/item-value` - -Using Item Handlers -------------------- - -UI item handlers listen for events (changes in state) related to a UI item then submit a callback. - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - def change_text(sender, app_data): - dpg.set_value("text item", f"Mouse Button ID: {app_data}") - - with dpg.window(width=500, height=300): - dpg.add_text("Click me with any mouse button", tag="text item") - with dpg.item_handler_registry(tag="widget handler") as handler: - dpg.add_item_clicked_handler(callback=change_text) - dpg.bind_item_handler_registry("text item", "widget handler") - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -.. seealso:: - For more information on item handlers :doc:`../documentation/io-handlers-state` diff --git a/docs/source/tutorials/tips-resources.rst b/docs/source/tutorials/tips-resources.rst deleted file mode 100644 index 517e9d13f..000000000 --- a/docs/source/tutorials/tips-resources.rst +++ /dev/null @@ -1,149 +0,0 @@ -Tips & More Resources -===================== - -.. meta:: - :description lang=en: Extra features not required but very useful when developing with dpg. - -Developer Tools ---------------- - -DPG includes several tools which can help develop and debug applications. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - - dpg.show_documentation() - dpg.show_style_editor() - dpg.show_debug() - dpg.show_about() - dpg.show_metrics() - dpg.show_font_manager() - dpg.show_item_registry() - - dpg.create_viewport(title='Custom Title', width=800, height=600) - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Results** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/examples_wiki_0.8.x/builtin_Dev_tools.PNG - - - -Style editor ------------- -The built-in style editor allows you to experiment with all style options at runtime to find the exact colors, padding, rounding and other style settings for your application. You can use the sliders to change the settings, which are applied to all items in your app, so you can immediately see what effect the changes have on your GUI. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - dpg.show_style_editor() - - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readthedocs/style_editor.png - - - -Item registry -------------- -The item registry shows all items of a running application in a hierarchical structure. For each item, a number of details, such as its tag ID, are shown. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - dpg.show_item_registry() - - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readthedocs/item_registry.gif - - -Font manager ------------- -The font manager shows all loaded fonts and their appropriate sizes. It allows you to inspect all characters, or glyphs, that are loaded with each font file. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport() - dpg.setup_dearpygui() - - dpg.show_font_manager() - - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readthedocs/font_manager.png - :width: 600 - :alt: Font manager - - -Runtime metrics --------------------------------- -Runtime metrics show the performance of your app in real-time. Here is it shown in conjunction with the built-in style editor. - -**Code:** - -.. code-block:: python - - import dearpygui.dearpygui as dpg - - dpg.create_context() - dpg.create_viewport(title='Custom Title', width=800, height=600) - - dpg.show_style_editor() - dpg.show_metrics() - - dpg.setup_dearpygui() - dpg.show_viewport() - dpg.start_dearpygui() - dpg.destroy_context() - -**Result:** - -.. image:: https://raw.githubusercontent.com/hoffstadt/DearPyGui/assets/readthedocs/style_editor_metrics.gif - :alt: Style editor and runtime metrics tools - -More Resources --------------- - - * :doc:`../extra/showcase` - * :doc:`../extra/video-tutorials` - diff --git a/sandbox/CMakeLists.txt b/sandbox/CMakeLists.txt deleted file mode 100644 index f3a24d9d3..000000000 --- a/sandbox/CMakeLists.txt +++ /dev/null @@ -1,86 +0,0 @@ -cmake_minimum_required (VERSION 3.16) - -add_executable (DearSandbox) - -set_target_properties(DearSandbox - PROPERTIES - CXX_STANDARD 17 - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearSandbox/" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearSandbox/" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}$<$:/cmake-build-release/>$<$:/cmake-build-debug/>DearSandbox/" - ) - -if(APPLE) - find_package(Python3 COMPONENTS Interpreter Development) -endif() - -target_sources(DearSandbox - - PRIVATE - - "$<$:main.cpp>" - "$<$:main_linux.cpp>" - "$<$:main_linux.cpp>" -) - -target_include_directories(DearSandbox - - PRIVATE - - "$<$:${CMAKE_SOURCE_DIR}/thirdparty/cpython/build/debug/include/python3.9d/>" - "$<$:${CMAKE_SOURCE_DIR}/thirdparty/cpython/PC/>" - "../thirdparty/imgui/" - "../thirdparty/imgui/backends/" - "../thirdparty/cpython/" - "../thirdparty/cpython/build/debug/" - "../thirdparty/cpython/Include/" - "../thirdparty/implot/" - "../src/" -) - -target_compile_definitions(DearSandbox - - PUBLIC - - $<$:MV_DEBUG> - $<$:MV_RELEASE> -) - -if (WIN32) - - target_link_directories(DearSandbox PRIVATE "../thirdparty/cpython/PCbuild/amd64/") - target_link_libraries(DearSandbox PUBLIC coreemb $<$:python39_d> $<$:python39>) - - add_custom_command(TARGET DearSandbox PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${CMAKE_SOURCE_DIR}/thirdparty/cpython/PCbuild/amd64/python3$<$:_d>.dll $) - - - add_custom_command(TARGET DearSandbox PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${CMAKE_SOURCE_DIR}/thirdparty/cpython/PCbuild/amd64/python39$<$:_d>.dll $) - -elseif(APPLE) - - set_property(TARGET DearSandbox APPEND_STRING PROPERTY COMPILE_FLAGS "-fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -arch x86_64 -g") - - target_link_directories(DearSandbox PRIVATE ../thirdparty/cpython/build/debug/lib) - - target_link_libraries(DearSandbox PUBLIC coreemb -ldl "-framework CoreFoundation" "python3.9d") - - file(GLOB PYTHON_LIBS_PATH "../thirdparty/cpython/build/debug/lib/python*") - - add_compile_definitions(PYTHON_LIBS_PATH="${PYTHON_LIBS_PATH}") - -else() # Linux - - target_link_directories(DearSandbox PRIVATE ../thirdparty/cpython/build/debug) - - target_link_libraries(DearSandbox - - PUBLIC - "-lcrypt -lpthread -ldl -lutil -lm" - coreemb - python3.9d - ) -endif() diff --git a/sandbox/main.cpp b/sandbox/main.cpp deleted file mode 100644 index ab4882764..000000000 --- a/sandbox/main.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#define PY_SSIZE_T_CLEAN -#include -#include "dearpygui.h" -#include "mvContext.h" -#include -#include -#include -#include -#include -#include "mvViewport.h" - -namespace fs = std::filesystem; - -void runTest(std::string test) -{ - auto ss = std::ostringstream{}; - std::ifstream input_file("../../testing/" + test + ".py"); -#ifndef MV_TESTS_ONLY - ss << "should_exit = False\n"; -#else - ss << "should_exit = True\n"; -#endif - ss << input_file.rdbuf(); - PyRun_SimpleString(ss.str().c_str()); -} - -int main(int argc, char* argv[]) -{ - - GenerateStubFile("../../dearpygui"); - GenerateDearPyGuiFile("../../dearpygui"); - GenerateDearPyGuiFileRTD("../../dearpygui"); - -#ifdef MV_RELEASE - HWND hWnd = GetConsoleWindow(); - ShowWindow(hWnd, SW_SHOW); -#else - HWND hWnd = GetConsoleWindow(); - ShowWindow(hWnd, SW_SHOW); -#endif - - // add our custom module - PyImport_AppendInittab("_dearpygui", &PyInit__dearpygui); - - // set path and start the interpreter - wchar_t* path = Py_DecodeLocale("../../thirdparty/DearPyGui_Ext/;../../sandbox/;../../thirdparty/cpython/Lib;../../thirdparty/cpython/PCbuild/amd64;../..", nullptr); - - Py_SetPath(path); - Py_NoSiteFlag = 1; // this must be set to 1 - Py_DontWriteBytecodeFlag = 1; - - // initialize python - Py_Initialize(); - if (!Py_IsInitialized()) - { - printf("Error initializing Python interpreter\n"); - return 1; - } - - // This one requires Python interpreter because internally it uses temporary PyObjects - // (hackyish but that's the best we can do for now). That's why we call it here rather - // than together with all other GenerateXYZ functions. - GenerateTypeInfoModule("../../dearpygui"); - - PyObject* mmarvel = PyImport_ImportModule("_dearpygui"); - - // tests - runTest("simple_tests"); - -#ifndef MV_TESTS_ONLY - // sandbox - { - auto ss = std::ostringstream{}; - std::ifstream input_file("../../sandbox/sandbox.py"); - ss << input_file.rdbuf(); - int result = PyRun_SimpleString(ss.str().c_str()); - } -#endif - - // check if error occurred - if (!PyErr_Occurred()) - Py_XDECREF(mmarvel); - else - PyErr_Print(); -} \ No newline at end of file diff --git a/sandbox/main_linux.cpp b/sandbox/main_linux.cpp deleted file mode 100644 index fff9907f2..000000000 --- a/sandbox/main_linux.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#define PY_SSIZE_T_CLEAN -#include -#include "dearpygui.h" -#include "mvViewport.h" -#include -#include -#include - -void runTest(std::string test) -{ - auto ss = std::ostringstream{}; - std::ifstream input_file("../../testing/" + test + ".py"); -#ifndef MV_TESTS_ONLY - ss << "should_exit = False\n"; -#else - ss << "should_exit = True\n"; -#endif - ss << input_file.rdbuf(); - PyRun_SimpleString(ss.str().c_str()); -} - -int main(int argc, char* argv[]) -{ - - GenerateStubFile("../../dearpygui"); - GenerateDearPyGuiFile("../../dearpygui"); - GenerateDearPyGuiFileRTD("../../dearpygui"); - - // initialize python - // add our custom module - PyImport_AppendInittab("_dearpygui", &PyInit__dearpygui); - - // set path and start the interpreter -#if defined(__APPLE__) - wchar_t *deco = Py_DecodeLocale( - PYTHON_LIBS_PATH":" - PYTHON_LIBS_PATH"/lib-dynload:" - PYTHON_LIBS_PATH"/site-packages:" - "../..:" - "../../thirdparty/DearPyGui_Ext:" - "../../sandbox", - nullptr); -#else - wchar_t *deco = Py_DecodeLocale( - "../../thirdparty/DearPyGui_Ext/:../../thirdparty/cpython/build/debug/build/lib.linux-x86_64-3.9-pydebug/:../" - "../thirdparty/cpython/Lib/:../..:../../sandbox", - nullptr); -#endif - - Py_SetPath(deco); - Py_NoSiteFlag = 1; // this must be set to 1 - Py_DontWriteBytecodeFlag = 1; - //_PyEval_SetSwitchInterval() - - Py_Initialize(); - if (!Py_IsInitialized()) - { - printf("Error initializing Python interpreter\n"); - return 1; - } - - // This one requires Python interpreter because internally it uses temporary PyObjects - // (hackyish but that's the best we can do for now). That's why we call it here rather - // than together with all other GenerateXYZ functions. - GenerateTypeInfoModule("../../dearpygui"); - - PyObject* mmarvel = PyImport_ImportModule("_dearpygui"); - - // tests - runTest("simple_tests"); - -#ifndef MV_TESTS_ONLY - // sandbox - { - auto ss = std::ostringstream{}; - std::ifstream input_file("../../sandbox/sandbox.py"); - ss << input_file.rdbuf(); - PyRun_SimpleString(ss.str().c_str()); - } -#endif - - // check if error occurred - if (!PyErr_Occurred()) - Py_XDECREF(mmarvel); - else - PyErr_Print(); - - return 0; -} \ No newline at end of file diff --git a/sandbox/sandbox.py b/sandbox/sandbox.py deleted file mode 100644 index d490a59e3..000000000 --- a/sandbox/sandbox.py +++ /dev/null @@ -1,30 +0,0 @@ -import dearpygui.dearpygui as dpg -import dearpygui.demo as demo -from dearpygui_ext.logger import mvLogger - -dpg.create_context() -#dpg.configure_app(manual_callback_management=True) -dpg.create_viewport() -dpg.setup_dearpygui() - -log = mvLogger() -log.log("log") -log.log_debug("log debug") -log.log_info("log info") -log.log_warning("log warning") -log.log_error("log error") -log.log_critical("log critical") - -with dpg.font_registry(): - dpg.add_font("../../assets/NotoSerifCJKjp-Medium.otf", 20, tag="custom font") - dpg.bind_font(dpg.last_container()) - -demo.show_demo() - -# main loop -dpg.show_viewport() -while dpg.is_dearpygui_running(): - #dpg.run_callbacks(dpg.get_callback_queue()) - dpg.render_dearpygui_frame() - -dpg.destroy_context() \ No newline at end of file diff --git a/scripts/BuildPythonForLinux.sh b/scripts/BuildPythonForLinux.sh deleted file mode 100755 index b3467f453..000000000 --- a/scripts/BuildPythonForLinux.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/sh -set -e - -# Allow user to set number of jobs when compiling -while getopts 'j:' OPTION; do - case "$OPTION" in - j) - jobs="-j $OPTARG" - ;; - ?) - exit 1 - ;; - esac - shift $(($OPTIND - 1)) -done - -cd $(dirname $0) # Make sure we start in the Scripts directory -cd ../thirdparty/cpython - -# Run `./BuildPythonForLinux.sh clean` to clean up the build directory -if [ "$1" = "clean" ]; then - rm -r build - exit 0 -fi - -# Default is to do a debug build -target="debug" -configure_args="--with-pydebug --enable-shared" -if [ "$1" = "release" ]; then - target="release" - configure_args="" -fi - -# Build in build/ so cpython's .gitignore hides the build output -mkdir -p "build/$target" -cd "build/$target" - -# Reconfiguring is time-consuming. Skip if it's already been done -if [ ! -f Makefile ]; then - /bin/bash ../../configure $configure_args -fi - -make $jobs diff --git a/scripts/BuildPythonForMac.sh b/scripts/BuildPythonForMac.sh deleted file mode 100755 index 6412cca27..000000000 --- a/scripts/BuildPythonForMac.sh +++ /dev/null @@ -1,6 +0,0 @@ -cd ../thirdparty/cpython -mkdir -p build/debug -cd build/debug -../../configure --with-pydebug --enable-shared --prefix=$(pwd) LDFLAGS=-Wl,-rpath,$(pwd) -make -make install diff --git a/scripts/BuildSandboxLinux.sh b/scripts/BuildSandboxLinux.sh deleted file mode 100644 index 5c9eec106..000000000 --- a/scripts/BuildSandboxLinux.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/sh -set -e - -# Allow user to set number of jobs when compiling -while getopts 'j:' OPTION; do - case "$OPTION" in - j) - jobs="-j $OPTARG" - ;; - ?) - exit 1 - ;; - esac -done - -cd $(dirname $0) # Make sure we start in the Scripts directory - -if [ "$1" = "clean" ]; then - rm -r ../cmake-build-debug - exit 0 -fi - -# Build python first if it hasn't been already -if [ ! -f ../thirdparty/cpython/build/debug/python ]; then - ./BuildPythonForLinux.sh $jobs debug -fi - -cd .. -mkdir -p cmake-build-debug -cd cmake-build-debug -cmake .. -cd .. -cmake --build cmake-build-debug --config Debug $jobs \ No newline at end of file diff --git a/scripts/GenItemFlagOps.py b/scripts/GenItemFlagOps.py deleted file mode 100644 index 314717ca2..000000000 --- a/scripts/GenItemFlagOps.py +++ /dev/null @@ -1,212 +0,0 @@ -# Takes a specific item's flags (a ImGuiSomethingFlags_ enum) from imgui.h and outputs -# boilerplate to copy-paste into handleSpecificKeywordArgs / getSpecificConfiguration. -# Run with --all to get updates for all known flags. -# Redirect output to a file for better reading / copy-pasting. - -import argparse -import itertools -from pathlib import Path -import re -from string import Template -from typing import List, Set, Tuple - - -imgui_h = Path(__file__).parent.parent / "thirdparty" / "imgui" / "imgui.h" -src_path = Path(__file__).parent.parent / "src" -# implot_h = Path(__file__).parent.parent / "thirdparty" / "implot" / "implot.h" -# imnodes_h = Path(__file__).parent.parent / "thirdparty" / "imnodes" / "imnodes.h" - - -# We extract both set_configuration and handleSpecificKeywordArgs -dpg_func_re = re.compile( - r"^(?:DearPyGui::set_configuration\(.*? (mv\w+?)Config&|" - r"(?:void\s+)?(mv\w+)::handleSpecificKeywordArgs).*?\n\{(.*?)^\}", - re.MULTILINE | re.DOTALL -) - - -def get_existing_flags(src_file: Path) -> List[Tuple[str, Set[str], str]]: - text = src_file.read_text("utf-8") - func_defs = dpg_func_re.findall(text) - - # We don't care what the destination flags variable is named - declarationRe = re.compile(r'\s*flagop\("\w+",\s*(ImGui\w+),') - - def extract_flags(text: str) -> Set[str]: - parsed = [declarationRe.match(l) for l in text.splitlines()] - return set([m[1] for m in parsed if m is not None]) - - def get_indentation(text: str) -> str: - # Note: we can't use \s in the pattern because it also matches newlines - m = re.search(r"^([ \t]*)flagop", text, re.MULTILINE) - return "\t" if m is None else m[1] - - # The widget name is either in the group 1 or group 2, which are 0th and 1st elements - # of the find_all result, respectively. - return [ (d[0] or d[1], extract_flags(d[2]), get_indentation(d[2])) for d in func_defs ] - - -def gen_py_name(imgui_name: str) -> str: - return re.sub("([^A-Z])([A-Z])", r"\1_\2", imgui_name).lower() - # return re.sub("([A-Z])", r"_\1", imgui_name).lstrip("_").lower() - - -# Returns a list of (imgui_name, py_name, comment) tuples -def read_enum(src_file: Path, enum_name: str, existing_flags: Set[str]) -> List[Tuple[str, str, str]]: - prefix = enum_name + "_" - - text = src_file.read_text("utf-8") - m = re.search(r"^enum\s+" + prefix + r"\b.*?\n\{(.*?)^\};", text, re.MULTILINE | re.DOTALL) - if m is None: - print(f"Can't find enum {enum_name}.") - return [] - - text = m[1] - text = re.sub(r"^#ifndef\s+IMGUI_DISABLE_OBSOLETE_FUNCTIONS.*?^#endif.*?\n", "", text, flags=re.MULTILINE | re.DOTALL) - lines = text.splitlines() - # drop all commented lines - # lines = list(filter(lambda l: not l.lstrip().startswith("//"), lines)) - declarationRe = re.compile(r"\s*" + prefix + r"(\w+)\s*=\s*1\s*<<\s*\d+,\s*(?://\s*(.*))") - parsed = [declarationRe.match(l) for l in lines] - - return [ - (prefix + m[1], gen_py_name(m[1]), m[2]) - for m in parsed - if m is not None and (prefix + m[1]) not in existing_flags - ] - - -def conv_set_config(flags: List[Tuple[str, str]], indent: str) -> List[str]: - template = Template('flagop("$py_name", $imgui_name, outConfig.flags);') - return [ - indent + template.substitute(py_name=py_name, imgui_name=imgui_name) - for imgui_name, py_name, comment in flags - ] - - -def conv_get_config(flags: List[Tuple[str, str]], indent: str) -> List[str]: - template = Template('checkbitset("$py_name", $imgui_name, inConfig.flags);') - return [ - indent + template.substitute(py_name=py_name, imgui_name=imgui_name) - for imgui_name, py_name, comment in flags - ] - - -def conv_parser(flags: List[Tuple[str, str]]) -> List[str]: - template = Template(' args.push_back({ mvPyDataType::Bool, "$py_name", mvArgType::KEYWORD_ARG, "False", "$desc" });') - return [ - template.substitute(py_name=py_name, desc=comment) - for imgui_name, py_name, comment in flags - ] - - -def process_enum(enum_name: str, existing_flags: Set[str], widget_name: str, indent: str) -> List[str]: - enum_name = enum_name.rstrip("_") - flags = read_enum(imgui_h, enum_name, existing_flags) - if not flags: - return [] - - if widget_name: - widget_name += ": " - - return ( - [ - f"=== {widget_name}{enum_name} ===", - "", - "Copy this to parser definitions in mvAppItem.cpp:", - "", - ] + - conv_parser(flags) + - [ - "", - "Copy this to handleSpecificKeywordArgs() / DearPyGui::set_configuration():", - "", - ] + - conv_set_config(flags, indent) + - [ - "", - "Copy this to getSpecificConfiguration() / DearPyGui::fill_configuration_dict():", - "", - ] + - conv_get_config(flags, indent) + - ["", ""] - ) - - -parser = argparse.ArgumentParser(description="Convert item flags into DPG boilerplate.") -parser.add_argument("enums", metavar="enum-name", nargs="*", - help="enum name, with or without the trailing underscore") -parser.add_argument("--all", action="store_true", help="refresh all known enums found in DPG source") - -args = parser.parse_args() - -# A list of (widget_name, imgui_flags, indentation) tuples -widget_defs = ( - get_existing_flags(src_path / "mvBasicWidgets.cpp") + - get_existing_flags(src_path / "mvColors.cpp") + - get_existing_flags(src_path / "mvContainers.cpp") + - # get_existing_flags(src_path / "mvNodes.cpp") + - # get_existing_flags(src_path / "mvPlotting.cpp") + - get_existing_flags(src_path / "mvTables.cpp") -) - -# This dict maps widget name to a list of ImGui flags -existing = {name: flags for name, flags, indentation in widget_defs} - -# Just squashing all prefixes in each sub-list into a set. -# The resulting dict maps widget name to a set of ImGui enum prefixes, ideally just -# one enum per widget (but who knows). -existing_prefixes = { - widget: set([ e.partition("_")[0] for e in flags ]) for widget, flags in existing.items() -} - -# This will keep a (widget, enum) list, where widget may be empty e.g. if we only -# have an enum name but it's not used in any known widget -enums: List[Tuple[str, str]] - -if args.all or not args.enums: - # Here we get all combinations of (widget, prefix) pairs - enums = sorted([ - (widget, prefix) - for widget, prefixes in existing_prefixes.items() - for prefix in prefixes - ], key=lambda item: (item[1], item[0])) - -else: - # Here we're only given enum prefixes, let's find the corresponding widgets - prefixes = [e.rstrip("_") for e in args.enums] - # We only need this mapping to make sure we don't lose prefixes that are not - # found anywhere in existing_prefixes (i.e. something new). For these, we add - # an empty widget name in their list so they are not lost. - widgets_per_pref = { - prefix: (sorted([w for w, p in existing_prefixes.items() if prefix in p]) or [""]) - for prefix in prefixes - } - # Now reverse the mapping - enums = [ - (w, p) - for p, widgets in widgets_per_pref.items() - for w in widgets - ] - -# Double check if we might be missing some widgets - -no_eyecatcher = [name for name, flags in existing.items() if not flags] -if no_eyecatcher: - print( - "=== No flags detected ===\n\n" - "The following items seem to not have any flags (or, rather, flagop() calls)\n" - "and are not included into the report below:\n") - print("\n".join(no_eyecatcher) + "\n") - -# Go compare the flags -widget_indents = {name: indentation for name, flags, indentation in widget_defs} - -lines = itertools.chain.from_iterable( - [ - process_enum(enum_name, existing[widget], widget, widget_indents[widget]) - for widget, enum_name in enums - ] -) - -print("\n".join(lines)) diff --git a/scripts/GenStyleConstants.py b/scripts/GenStyleConstants.py deleted file mode 100644 index 1ac7e0312..000000000 --- a/scripts/GenStyleConstants.py +++ /dev/null @@ -1,83 +0,0 @@ -# Takes ImGuiStyleVar declarations from imgui.h and outputs a set of corresponding DPG styles - -from itertools import dropwhile, takewhile -from pathlib import Path -import re -from string import Template -from typing import Callable, List, Set, Tuple, Union - - -imgui_h = Path(__file__).parent.parent / "thirdparty" / "imgui" / "imgui.h" -implot_h = Path(__file__).parent.parent / "thirdparty" / "implot" / "implot.h" -imnodes_h = Path(__file__).parent.parent / "thirdparty" / "imnodes" / "imnodes.h" - -# Returns a list of (name, comment) tuples -def read_constants(src_file: Path, enum_name: str) -> List[Tuple[str, str]]: - prefix = enum_name + "_" - end_marker = prefix + "COUNT" - lines = src_file.read_text("utf-8").splitlines() - lines = list( - filter(lambda line: line.strip().startswith(prefix), - takewhile(lambda line: not line.strip().startswith(end_marker), - dropwhile(lambda line: not line.strip().startswith(prefix), lines) - ) - ) - ) - - declarationRe = re.compile(r"\s*" + prefix + r"(\w+)\s*(?:=\s*\w+)?,\s*(.*)") - - parsed = [declarationRe.match(l) for l in lines] - return [(m[1], m[2]) for m in parsed if m is not None] - - -OLD_NODE_COLORS: Set[str] = { - "NodeBackground", - "NodeBackgroundHovered", - "NodeBackgroundSelected", - "NodeOutline", - "TitleBar", - "TitleBarHovered", - "TitleBarSelected", - "Link", - "LinkHovered", - "LinkSelected", - "Pin", - "PinHovered", - "BoxSelector", - "BoxSelectorOutline", - "GridBackground", - "GridLine", -} - - -def convert_constants(src_file: Path, dpg_prefix: Union[str, Callable], enum_name: str, comment_pos: int) -> List[str]: - template = Template('\t\tModuleConstants.push_back({ "${dpg_prefix}_$name", ${imgui_prefix}_$name });') - dpg_prefix_gen = (lambda name: dpg_prefix) if isinstance(dpg_prefix, str) else dpg_prefix - defs = read_constants(src_file, enum_name) - return [ - # Regarding comment_pos: we need to subtract 1 to account for 1-based column number, - # subtract 1 more to account for the space that we add before the comment, - # and subtract 3 twice to account for two tab characters at the start of the template - # (with tab width = 4, these take 4 characters on the screen but 1 character in actual text). - (template.substitute(name=name, dpg_prefix = dpg_prefix_gen(name), imgui_prefix = enum_name).ljust(comment_pos - 8) + " " + comment).rstrip() - for name, comment in defs - ] - - -convert_constants(implot_h, "mvPlotCol", "ImPlotCol", 90) - -lines = ( - convert_constants(imgui_h, "mvThemeCol", "ImGuiCol", 93) + - [""] + - convert_constants(implot_h, "mvPlotCol", "ImPlotCol", 90) + - [""] + - convert_constants(imnodes_h, (lambda name: "mvNodeCol" if name in OLD_NODE_COLORS else "mvNodesCol"), "ImNodesCol", 90) + - [""] + - convert_constants(imgui_h, "mvStyleVar", "ImGuiStyleVar", 109) + - [""] + - convert_constants(implot_h, "mvPlotStyleVar", "ImPlotStyleVar", 112) + - [""] + - convert_constants(imnodes_h, "mvNodesStyleVar", "ImNodesStyleVar", 109) -) - -print("\n".join(lines)) diff --git a/setup.py b/setup.py deleted file mode 100644 index be68c1ca5..000000000 --- a/setup.py +++ /dev/null @@ -1,224 +0,0 @@ -from setuptools import setup, find_packages, Distribution -from setuptools.command import build_py -import distutils.cmd -from codecs import open -import os -from os import path -import textwrap -import sys -import shutil -import subprocess - -wip_version = "2.3" - -def version_number(): - """This function reads the version number which is populated by github actions""" - - if os.environ.get('READTHEDOCS') == 'True': - return wip_version - try: - with open('version_number.txt', encoding='utf-8') as f: - version = f.readline().rstrip() - - # temporary fix fox CI issues with windows - if(version.startswith("ECHO")): - return "0.0.1" - - return version - - except IOError: - return wip_version - -def get_platform(): - - platforms = { - 'linux' : 'Linux', - 'linux1' : 'Linux', - 'linux2' : 'Linux', - 'darwin' : 'OS X', - 'win32' : 'Windows' - } - if sys.platform not in platforms: - return sys.platform - - return platforms[sys.platform] - -class BinaryDistribution(Distribution): - def has_ext_modules(var): - return True - -class DPGBuildCommand(distutils.cmd.Command): - - description = 'DPG Build Command' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - - if os.environ.get('READTHEDOCS') == 'True': - self.announce('Using readthedocs hack',level=distutils.log.INFO) - return - - if get_platform() == "Windows": - command = [r'set PATH="C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin";"C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin";"C:\Program Files (x86)\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin";%PATH% && '] - command.append("mkdir cmake-build-local && ") - command.append("cd cmake-build-local && ") - command.append('cmake .. -G "Visual Studio 17 2022" -A "x64" -DMVDIST_ONLY=True -DMVDPG_VERSION=') - command.append(version_number() + " -DMV_PY_VERSION=") - command.append(str(sys.version_info[0]) + "." + str(sys.version_info[1]) + " && ") - command.append("cd .. && cmake --build cmake-build-local --config Release") - self.announce('Running command: %s' % "Dear PyGui Build for Windows", level=distutils.log.INFO) - subprocess.check_call(''.join(command), env=os.environ, shell=True) - src_path = os.path.dirname(os.path.abspath(__file__)) - shutil.copy("cmake-build-local/DearPyGui/Release/_dearpygui.pyd", src_path +"/output/dearpygui") - - elif get_platform() == "Linux": - command = ["mkdir cmake-build-local; "] - command.append("cd cmake-build-local; ") - command.append('cmake .. -DMVDIST_ONLY=True -DMVDPG_VERSION='+version_number()+ " -DMV_PY_VERSION="+ str(sys.version_info[0]) + "." + str(sys.version_info[1])+"; ") - command.append("cd ..; cmake --build cmake-build-local --config Release") - self.announce('Running command: %s' % "Dear PyGui Build for Linux",level=distutils.log.INFO) - subprocess.check_call(''.join(command), shell=True) - src_path = os.path.dirname(os.path.abspath(__file__)) - shutil.copy("cmake-build-local/DearPyGui/_dearpygui.so", src_path +"/output/dearpygui") - - elif get_platform() == "OS X": - command = ["mkdir cmake-build-local; "] - command.append("cd cmake-build-local; ") - command.append('cmake .. -DMVDIST_ONLY=True -DMVDPG_VERSION='+version_number()+ " -DMV_PY_VERSION="+ str(sys.version_info[0]) + "." + str(sys.version_info[1])+"; ") - command.append("cd ..; cmake --build cmake-build-local --config Release") - self.announce('Running command: %s' % "Dear PyGui Build for OS X",level=distutils.log.INFO) - subprocess.check_call(''.join(command), shell=True) - src_path = os.path.dirname(os.path.abspath(__file__)) - shutil.copy("cmake-build-local/DearPyGui/_dearpygui.so", src_path +"/output/dearpygui") - - else: - self.announce('Command not ready.',level=distutils.log.INFO) - -class BuildPyCommand(build_py.build_py): - def run(self): - self.run_command('dpg_build') - build_py.build_py.run(self) - -def setup_package(): - - src_path = os.path.dirname(os.path.abspath(__file__)) - old_path = os.getcwd() - os.chdir(src_path) - sys.path.insert(0, src_path) - - # import readme content - with open("./README.md", encoding='utf-8') as f: - long_description = f.read() - - # create the necessary directories if they do not exist - if os.path.isdir(src_path + "/output"): - shutil.rmtree(src_path + "/output") - os.mkdir(src_path + "/output") - os.mkdir(src_path + "/output/dearpygui") - - if os.path.isdir(src_path + "/cmake-build-local"): - shutil.rmtree(src_path + "/cmake-build-local") - - # copy add items to temporary location - if os.environ.get('READTHEDOCS') == 'True': - shutil.copy(src_path + "/dearpygui/_dearpygui_RTD.py", src_path + "/output/dearpygui") - else: - shutil.copy(src_path + "/dearpygui/dearpygui.py", src_path + "/output/dearpygui") - - shutil.copy(src_path + "/dearpygui/demo.py", src_path + "/output/dearpygui") - shutil.copy(src_path + "/dearpygui/experimental.py", src_path + "/output/dearpygui") - shutil.copy(src_path + "/dearpygui/type_info.py", src_path + "/output/dearpygui") - - with open(src_path + "/output/dearpygui/__init__.py", 'w') as file: - file.write("__version__='" + version_number() + "'\n") - - if os.environ.get('READTHEDOCS') == 'True': - - os.rename(src_path + "/output/dearpygui/_dearpygui_RTD.py", src_path + "/output/dearpygui/dearpygui.py") - with open(src_path + "/output/dearpygui/_dearpygui.py", 'w') as newfile: - with open(src_path + "/dearpygui/_dearpygui.pyi", 'r') as file: - lines = file.readlines() - for line in lines: - if line.__contains__("...") and not line.__contains__("["): - newfile.write("\tpass\n") - elif line.__contains__("dearpygui._dearpygui"): - newfile.write("mvBuffer = 7\n") # hacky - newfile.write("mvVec4 = 7\n") # hacky - newfile.write("mvMat4 = 7\n") # hacky - else: - newfile.write(line) - else: - - # copy add items to temporary location - shutil.copy(src_path + "/dearpygui/_dearpygui.pyi", src_path + "/output/dearpygui") - if get_platform() == "Windows": - shutil.copy(src_path + "/thirdparty/Microsoft/vcruntime140_1.dll", src_path + "/output/dearpygui") - - metadata = dict( - name='dearpygui', # Required - version=version_number(), # Required - author="Jonathan Hoffstadt and Preston Cothren", # Optional - author_email="jonathanhoffstadt@yahoo.com", # Optional - description='DearPyGui: A simple Python GUI Toolkit', # Required - long_description=long_description, # Optional - long_description_content_type='text/markdown', # Optional - url='https://github.com/hoffstadt/DearPyGui', # Optional - license = 'MIT', - python_requires='>=3.8', - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Education', - 'Intended Audience :: Developers', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: MIT License', - 'Operating System :: MacOS', - 'Operating System :: Microsoft :: Windows :: Windows 10', - 'Operating System :: POSIX', - 'Operating System :: Unix', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'Programming Language :: Python :: 3.13', - 'Programming Language :: Python :: 3.14', - 'Programming Language :: Python :: Implementation :: CPython', - 'Programming Language :: Python :: 3 :: Only', - 'Topic :: Software Development :: User Interfaces', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - packages=['dearpygui'], - package_dir = {'': 'output'}, - package_data={}, - distclass=BinaryDistribution, - cmdclass={ - 'dpg_build': DPGBuildCommand, - 'build_py': BuildPyCommand, - }, - ) - - if os.environ.get('READTHEDOCS') == 'True': - metadata['package_data']['dearpygui'] = ["__init__.py", "_dearpygui.py", "dearpygui.py", "demo.py", "experimental.py"] - elif get_platform() == "Windows": - metadata['package_data']['dearpygui'] = ["__init__.py", "_dearpygui.so", "_dearpygui.pyd", "_dearpygui.pyi", "dearpygui.py", "demo.py", "experimental.py", "type_info.py", "vcruntime140_1.dll"] - else: - metadata['package_data']['dearpygui'] = ["__init__.py", "_dearpygui.so", "_dearpygui.pyd", "_dearpygui.pyi", "dearpygui.py", "demo.py", "experimental.py", "type_info.py"] - - if "--force" in sys.argv: - sys.argv.remove('--force') - - try: - setup(**metadata) - finally: - del sys.path[0] - os.chdir(old_path) - return - -if __name__ == '__main__': - setup_package() diff --git a/src/.gitignore b/src/.gitignore deleted file mode 100644 index f9d5183a5..000000000 --- a/src/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -__pycache__/ -__init__.py -_dearpygui.pyd -_dearpygui.pyi -demo.py -experimental.py -vcruntime140_1.dll -dearpygui.py \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index cd814106a..000000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,121 +0,0 @@ -cmake_minimum_required (VERSION 3.16) - - -set(MARVEL_SOURCES - - # core - "mvContext.cpp" - "mvMath.cpp" - "mvProfiler.cpp" - "dearpygui.cpp" - - # platform - "$<$:mvViewport_win32.cpp>" - "$<$:mvUtilities_win32.cpp>" - "$<$:mvGraphics_win32.cpp>" - - "$<$:mvViewport_apple.mm>" - "$<$:mvUtilities_apple.mm>" - "$<$:mvGraphics_apple.mm>" - - "$<$:mvUtilities_linux.cpp>" - "$<$:mvViewport_linux.cpp>" - "$<$:mvGraphics_linux.cpp>" - - # python - "mvPyUtils.cpp" - "mvCustomTypes.cpp" - - # ui - "mvBasicWidgets.cpp" - "mvTables.cpp" - "mvThemes.cpp" - "mvNodes.cpp" - "mvDrawings.cpp" - "mvGlobalHandlers.cpp" - "mvItemHandlers.cpp" - "mvValues.cpp" - "mvTextureItems.cpp" - "mvFontItems.cpp" - "mvColors.cpp" - "mvPlotting.cpp" - "mvContainers.cpp" - - "mvCallbackRegistry.cpp" - "mvLoadingIndicatorCustom.cpp" - "mvFontManager.cpp" - "mvToolManager.cpp" - "mvToolWindow.cpp" - "mvAboutWindow.cpp" - "mvDocWindow.cpp" - "mvMetricsWindow.cpp" - "mvStackWindow.cpp" - "mvStyleWindow.cpp" - "mvDebugWindow.cpp" - "mvLayoutWindow.cpp" - "mvAppItemState.cpp" - "mvAppItem.cpp" - "mvItemRegistry.cpp" - - "mvDatePicker.cpp" - "mvTimePicker.cpp" - "mvSlider3D.cpp" - "mvLoadingIndicator.cpp" - "mvFileDialog.cpp" - "mvFileExtension.cpp" - - # imnodes - "../thirdparty/imnodes/imnodes.cpp" - - # implot - "../thirdparty/implot/implot.cpp" - "../thirdparty/implot/implot_items.cpp" - "../thirdparty/implot/implot_demo.cpp" - - # ImGuiFileDialog - "../thirdparty/ImGuiFileDialog/ImGuiFileDialog.cpp" - - # imgui - "../thirdparty/imgui/misc/cpp/imgui_stdlib.cpp" - "../thirdparty/imgui/imgui.cpp" - "../thirdparty/imgui/imgui_demo.cpp" - "../thirdparty/imgui/imgui_draw.cpp" - "../thirdparty/imgui/imgui_widgets.cpp" - "../thirdparty/imgui/imgui_tables.cpp" - "$<$:../thirdparty/imgui/misc/freetype/imgui_freetype.cpp>" - "$<$:../thirdparty/imgui/backends/imgui_impl_win32.cpp>" - "$<$:../thirdparty/imgui/backends/imgui_impl_dx11.cpp>" - "$<$:../thirdparty/imgui/backends/imgui_impl_metal.mm>" - "$<$:../thirdparty/imgui/backends/imgui_impl_glfw.cpp>" - "$<$:../thirdparty/imgui/backends/imgui_impl_glfw.cpp>" - "$<$:../thirdparty/imgui/backends/imgui_impl_opengl3.cpp>" - - # gl3w - "$<$:../thirdparty/gl3w/GL/gl3w.c>" - ) - -set(MARVEL_INCLUDE_DIR - "." - "../thirdparty/implot" - "../thirdparty/stb" - "../thirdparty/imnodes" - "../thirdparty/ImGuiFileDialog" - "../thirdparty/glfw/include/" - "../thirdparty/glfw/deps/" - "../thirdparty/imgui/" - "../thirdparty/gl3w/" - "../thirdparty/imgui/misc/freetype/" - "../thirdparty/imgui/backends/" - "../thirdparty/cpython/" - "../thirdparty/cpython/Include/" - "../thirdparty/cpython/build/debug/" - "$<$:${CMAKE_SOURCE_DIR}/thirdparty/cpython/PC/>" - "$,${CMAKE_SOURCE_DIR}/thirdparty/cpython/build/release/,${CMAKE_SOURCE_DIR}/thirdparty/cpython/build/debug/>" - ) - - -if(MVDIST_ONLY) - include("distribution.cmake") -else() - include("embedded.cmake") -endif() \ No newline at end of file diff --git a/src/dearpygui.cpp b/src/dearpygui.cpp deleted file mode 100644 index 48e10493d..000000000 --- a/src/dearpygui.cpp +++ /dev/null @@ -1,802 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "dearpygui.h" - -#include "mvAppItemCommons.h" -#include "mvFontManager.h" -#include "mvItemRegistry.h" -#include "mvToolManager.h" -#include "mvCustomTypes.h" -#include "mvViewport.h" -#include "mvProfiler.h" -#include "dearpygui_commands.h" -#include "dearpygui_parsers.h" - -#include -#include -#include - -#define MV_ADD_COMMAND(x) methods.push_back({ #x, (PyCFunction)x, METH_VARARGS | METH_KEYWORDS, GetParsers()[#x].documentation.c_str() }); - -const std::map& -GetModuleParsers() -{ - - static auto parsers = std::map(); - - if (parsers.empty()) - { - #define X(el) parsers.insert({GetEntityCommand(mvAppItemType::el), DearPyGui::GetEntityParser(mvAppItemType::el)}); - MV_ITEM_TYPES - #undef X - - // to prevent exceeding function stack size - InsertParser_Block0(parsers); - InsertParser_Block1(parsers); - InsertParser_Block2(parsers); - InsertParser_Block3(parsers); - InsertParser_Block4(parsers); - } - return parsers; -} - -const std::vector>& -GetModuleConstants() -{ - static bool First_Run = true; - static std::vector> ModuleConstants; - - if (First_Run) - { - InsertConstants_mvContext(ModuleConstants); - - ModuleConstants.push_back({"mvAll", 0L }); - ModuleConstants.push_back({"mvTool_About", MV_TOOL_ABOUT_UUID }); - ModuleConstants.push_back({"mvTool_Debug", MV_TOOL_DEBUG_UUID }); - ModuleConstants.push_back({"mvTool_Doc", MV_TOOL_DOC_UUID }); - ModuleConstants.push_back({"mvTool_ItemRegistry", MV_TOOL_ITEM_REGISTRY_UUID }); - ModuleConstants.push_back({"mvTool_Metrics", MV_TOOL_METRICS_UUID }); - ModuleConstants.push_back({"mvTool_Stack", MV_TOOL_STACK_UUID }); - ModuleConstants.push_back({"mvTool_Style", MV_TOOL_STYLE_UUID }); - ModuleConstants.push_back({"mvTool_Font", MV_TOOL_FONT_UUID }); - ModuleConstants.push_back({"mvFontAtlas", MV_ATLAS_UUID }); - ModuleConstants.push_back({"mvAppUUID", MV_APP_UUID }); - ModuleConstants.push_back({"mvInvalidUUID", MV_INVALID_UUID }); - ModuleConstants.push_back({"mvDir_None", ImGuiDir_None }); - ModuleConstants.push_back({"mvDir_Left", ImGuiDir_Left }); - ModuleConstants.push_back({"mvDir_Right", ImGuiDir_Right }); - ModuleConstants.push_back({"mvDir_Up", ImGuiDir_Up }); - ModuleConstants.push_back({"mvDir_Down", ImGuiDir_Down }); - ModuleConstants.push_back({"mvComboHeight_Small", 0L }); - ModuleConstants.push_back({"mvComboHeight_Regular", 1L }); - ModuleConstants.push_back({"mvComboHeight_Large", 2L }); - ModuleConstants.push_back({"mvComboHeight_Largest", 3L }); - - ModuleConstants.push_back({"mvEventType_Off", mvEventType_Off }); - ModuleConstants.push_back({"mvEventType_Enter", mvEventType_Enter }); - ModuleConstants.push_back({"mvEventType_On", mvEventType_On }); - ModuleConstants.push_back({"mvEventType_Leave", mvEventType_Leave }); - - // We're not adding 'None' because it's useless in the API - ModuleConstants.push_back({"mvSetScrollFlags_Now", mvSetScrollFlags_Now }); - ModuleConstants.push_back({"mvSetScrollFlags_Delayed", mvSetScrollFlags_Delayed }); - ModuleConstants.push_back({"mvSetScrollFlags_Both", mvSetScrollFlags_Both }); - - ModuleConstants.push_back({"mvScrollDirection_XAxis", mvScrollDirection_XAxis }); - ModuleConstants.push_back({"mvScrollDirection_YAxis", mvScrollDirection_YAxis }); - ModuleConstants.push_back({"mvScrollDirection_Horizontal", mvScrollDirection_Horizontal }); - ModuleConstants.push_back({"mvScrollDirection_Vertical", mvScrollDirection_Vertical }); - - ModuleConstants.push_back({"mvLoadInd_DottedCircle", mvLoadingIndicator::Style_DottedCircle }); - ModuleConstants.push_back({"mvLoadInd_Ring", mvLoadingIndicator::Style_Ring }); - - ModuleConstants.push_back({"mvPlatform_Windows", 0L }); - ModuleConstants.push_back({"mvPlatform_Apple", 1L }); - ModuleConstants.push_back({"mvPlatform_Linux", 2L }); - - ModuleConstants.push_back({"mvColorEdit_AlphaPreviewNone", ImGuiColorEditFlags_AlphaOpaque }); - ModuleConstants.push_back({"mvColorEdit_AlphaPreview", ImGuiColorEditFlags_None }); - ModuleConstants.push_back({"mvColorEdit_AlphaPreviewHalf", ImGuiColorEditFlags_AlphaPreviewHalf }); - ModuleConstants.push_back({"mvColorEdit_uint8", ImGuiColorEditFlags_Uint8}); - ModuleConstants.push_back({"mvColorEdit_float", ImGuiColorEditFlags_Float}); - ModuleConstants.push_back({"mvColorEdit_rgb", ImGuiColorEditFlags_DisplayRGB}); - ModuleConstants.push_back({"mvColorEdit_hsv", ImGuiColorEditFlags_DisplayHSV}); - ModuleConstants.push_back({"mvColorEdit_hex", ImGuiColorEditFlags_DisplayHex}); - ModuleConstants.push_back({"mvColorEdit_input_rgb", ImGuiColorEditFlags_InputRGB}); - ModuleConstants.push_back({"mvColorEdit_input_hsv", ImGuiColorEditFlags_InputHSV}); - - ModuleConstants.push_back({ "mvPlotColormap_Default", ImPlotColormap_Deep }); // ImPlot default colormap (n=10) - ModuleConstants.push_back({ "mvPlotColormap_Deep", ImPlotColormap_Deep }); // a.k.a. seaborn deep (default) (n=10) - ModuleConstants.push_back({ "mvPlotColormap_Dark", ImPlotColormap_Dark }); // a.k.a. matplotlib "Set1" (n=9) - ModuleConstants.push_back({ "mvPlotColormap_Pastel", ImPlotColormap_Pastel }); // a.k.a. matplotlib "Pastel1" (n=9) - ModuleConstants.push_back({ "mvPlotColormap_Paired", ImPlotColormap_Paired }); // a.k.a. matplotlib "Paired" (n=12) - ModuleConstants.push_back({ "mvPlotColormap_Viridis", ImPlotColormap_Viridis }); // a.k.a. matplotlib "viridis" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Plasma", ImPlotColormap_Plasma }); // a.k.a. matplotlib "plasma" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Hot", ImPlotColormap_Hot }); // a.k.a. matplotlib/MATLAB "hot" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Cool", ImPlotColormap_Cool }); // a.k.a. matplotlib/MATLAB "cool" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Pink", ImPlotColormap_Pink }); // a.k.a. matplotlib/MATLAB "pink" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Jet", ImPlotColormap_Jet }); // a.k.a. MATLAB "jet" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Twilight", ImPlotColormap_Twilight }); // a.k.a. MATLAB "twilight" (n=11) - ModuleConstants.push_back({ "mvPlotColormap_RdBu", ImPlotColormap_RdBu }); // red/blue, Color Brewer (n=11) - ModuleConstants.push_back({ "mvPlotColormap_BrBG", ImPlotColormap_BrBG }); // brown/blue-green, Color Brewer (n=11) - ModuleConstants.push_back({ "mvPlotColormap_PiYG", ImPlotColormap_PiYG }); // pink/yellow-green, Color Brewer (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Spectral", ImPlotColormap_Spectral }); // color spectrum, Color Brewer (n=11) - ModuleConstants.push_back({ "mvPlotColormap_Greys", ImPlotColormap_Greys }); // white/black (n=11) - - ModuleConstants.push_back({ "mvColorPicker_bar", ImGuiColorEditFlags_PickerHueBar }); - ModuleConstants.push_back({ "mvColorPicker_wheel", ImGuiColorEditFlags_PickerHueWheel }); - - ModuleConstants.push_back({ "mvTabOrder_Reorderable", 0L }); - ModuleConstants.push_back({ "mvTabOrder_Fixed", 1L }); - ModuleConstants.push_back({ "mvTabOrder_Leading", 2L }); - ModuleConstants.push_back({ "mvTabOrder_Trailing", 3L }); - - ModuleConstants.push_back({ "mvTimeUnit_Us", 0L }); - ModuleConstants.push_back({ "mvTimeUnit_Ms", 1L }); - ModuleConstants.push_back({ "mvTimeUnit_S", 2L }); - ModuleConstants.push_back({ "mvTimeUnit_Min", 3L }); - ModuleConstants.push_back({ "mvTimeUnit_Hr", 4L }); - ModuleConstants.push_back({ "mvTimeUnit_Day", 5L }); - ModuleConstants.push_back({ "mvTimeUnit_Mo", 6L }); - ModuleConstants.push_back({ "mvTimeUnit_Yr", 7L }); - - ModuleConstants.push_back({ "mvDatePickerLevel_Day", 0L }); - ModuleConstants.push_back({ "mvDatePickerLevel_Month", 1L }); - ModuleConstants.push_back({ "mvDatePickerLevel_Year", 2L }); - - ModuleConstants.push_back({ "mvCullMode_None", 0L }); - ModuleConstants.push_back({ "mvCullMode_Back", 1L }); - ModuleConstants.push_back({ "mvCullMode_Front", 2L }); - - // We no longer need these mvFontRangeHint constants, but since there's no way - // to declare them deprecated, we'll leave them here for a while. - // TODO: decide if we should move definitions entirely to _deprecated.py and - // remove them from the "internal" API of DLL/.so file. - ModuleConstants.push_back({ "mvFontRangeHint_Default", 0L }); - ModuleConstants.push_back({ "mvFontRangeHint_Japanese", 1L }); - ModuleConstants.push_back({ "mvFontRangeHint_Korean", 2L }); - ModuleConstants.push_back({ "mvFontRangeHint_Chinese_Full", 3L }); - ModuleConstants.push_back({ "mvFontRangeHint_Chinese_Simplified_Common", 4L }); - ModuleConstants.push_back({ "mvFontRangeHint_Cyrillic", 5L }); - ModuleConstants.push_back({ "mvFontRangeHint_Thai", 6L }); - ModuleConstants.push_back({ "mvFontRangeHint_Vietnamese", 7L }); - - ModuleConstants.push_back({ "mvNode_PinShape_Circle", ImNodesPinShape_Circle }); - ModuleConstants.push_back({ "mvNode_PinShape_CircleFilled", ImNodesPinShape_CircleFilled }); - ModuleConstants.push_back({ "mvNode_PinShape_Triangle", ImNodesPinShape_Triangle }); - ModuleConstants.push_back({ "mvNode_PinShape_TriangleFilled", ImNodesPinShape_TriangleFilled }); - ModuleConstants.push_back({ "mvNode_PinShape_Quad", ImNodesPinShape_Quad }); - ModuleConstants.push_back({ "mvNode_PinShape_QuadFilled", ImNodesPinShape_QuadFilled }); - - ModuleConstants.push_back({ "mvNode_Attr_Input", 0L }); - ModuleConstants.push_back({ "mvNode_Attr_Output", 1L}); - ModuleConstants.push_back({ "mvNode_Attr_Static", 2L}); - - ModuleConstants.push_back({ "mvPlotBin_Sqrt", -1L }); - ModuleConstants.push_back({ "mvPlotBin_Sturges", -2L }); - ModuleConstants.push_back({ "mvPlotBin_Rice", -3L }); - ModuleConstants.push_back({ "mvPlotBin_Scott", -4L }); - - ModuleConstants.push_back({ "mvXAxis", ImAxis_X1}); - ModuleConstants.push_back({ "mvXAxis2", ImAxis_X2}); - ModuleConstants.push_back({ "mvXAxis3", ImAxis_X3}); - ModuleConstants.push_back({ "mvYAxis", ImAxis_Y1}); - ModuleConstants.push_back({ "mvYAxis2", ImAxis_Y2}); - ModuleConstants.push_back({ "mvYAxis3", ImAxis_Y3}); - - ModuleConstants.push_back({ "mvPlotScale_Linear", ImPlotScale_Linear}); // default linear scale - ModuleConstants.push_back({ "mvPlotScale_Time", ImPlotScale_Time}); // date/time scale - ModuleConstants.push_back({ "mvPlotScale_Log10", ImPlotScale_Log10}); // base 10 logartithmic scale - ModuleConstants.push_back({ "mvPlotScale_SymLog", ImPlotScale_SymLog}); // symmetric log scale - - ModuleConstants.push_back({ "mvPlotMarker_None", ImPlotMarker_None}); // no marker - ModuleConstants.push_back({ "mvPlotMarker_Circle", ImPlotMarker_Circle}); // a circle marker will be rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Square", ImPlotMarker_Square}); // a square maker will be rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Diamond", ImPlotMarker_Diamond}); // a diamond marker will be rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Up", ImPlotMarker_Up}); // an upward-pointing triangle marker will up rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Down", ImPlotMarker_Down}); // an downward-pointing triangle marker will up rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Left", ImPlotMarker_Left}); // an leftward-pointing triangle marker will up rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Right", ImPlotMarker_Right}); // an rightward-pointing triangle marker will up rendered at each point - ModuleConstants.push_back({ "mvPlotMarker_Cross", ImPlotMarker_Cross}); // a cross marker will be rendered at each point (not filled) - ModuleConstants.push_back({ "mvPlotMarker_Plus", ImPlotMarker_Plus}); // a plus marker will be rendered at each point (not filled) - ModuleConstants.push_back({ "mvPlotMarker_Asterisk", ImPlotMarker_Asterisk}); // a asterisk marker will be rendered at each point (not filled) - - ModuleConstants.push_back({ "mvPlot_Location_Center", ImPlotLocation_Center }); - ModuleConstants.push_back({ "mvPlot_Location_North", ImPlotLocation_North }); - ModuleConstants.push_back({ "mvPlot_Location_South", ImPlotLocation_South }); - ModuleConstants.push_back({ "mvPlot_Location_West", ImPlotLocation_West}); - ModuleConstants.push_back({ "mvPlot_Location_East", ImPlotLocation_East}); - ModuleConstants.push_back({ "mvPlot_Location_NorthWest", ImPlotLocation_NorthWest}); - ModuleConstants.push_back({ "mvPlot_Location_NorthEast", ImPlotLocation_NorthEast}); - ModuleConstants.push_back({ "mvPlot_Location_SouthWest", ImPlotLocation_SouthWest}); - ModuleConstants.push_back({ "mvPlot_Location_SouthEast", ImPlotLocation_SouthEast}); - - ModuleConstants.push_back({ "mvNodeMiniMap_Location_BottomLeft", ImNodesMiniMapLocation_BottomLeft }); - ModuleConstants.push_back({ "mvNodeMiniMap_Location_BottomRight", ImNodesMiniMapLocation_BottomRight }); - ModuleConstants.push_back({ "mvNodeMiniMap_Location_TopLeft", ImNodesMiniMapLocation_TopLeft }); - ModuleConstants.push_back({ "mvNodeMiniMap_Location_TopRight", ImNodesMiniMapLocation_TopRight }); - - ModuleConstants.push_back({ "mvTable_SizingFixedFit", ImGuiTableFlags_SizingFixedFit }); - ModuleConstants.push_back({ "mvTable_SizingFixedSame", ImGuiTableFlags_SizingFixedSame }); - ModuleConstants.push_back({ "mvTable_SizingStretchProp", ImGuiTableFlags_SizingStretchProp}); - ModuleConstants.push_back({ "mvTable_SizingStretchSame", ImGuiTableFlags_SizingStretchSame}); - - ModuleConstants.push_back({ "mvTreeLines_None", ImGuiTreeNodeFlags_DrawLinesNone }); - ModuleConstants.push_back({ "mvTreeLines_Full", ImGuiTreeNodeFlags_DrawLinesFull }); - ModuleConstants.push_back({ "mvTreeLines_ToNodes", ImGuiTreeNodeFlags_DrawLinesToNodes }); - - ModuleConstants.push_back({ "mvFormat_Float_rgba", 0L }); - ModuleConstants.push_back({ "mvFormat_Float_rgb", 1L }); - - ModuleConstants.push_back({ "mvThemeCat_Core", 0L }); - ModuleConstants.push_back({ "mvThemeCat_Plots", 1L}); - ModuleConstants.push_back({ "mvThemeCat_Nodes", 2L}); - - // Note: color and style constants are generated - see /scripts/GenStyleConstants.py. - // Avoid editing them manually. Update with caution, some entries have edits upon - // the script-generated version (commented-out lines or old constants kept for compatibility). - - ModuleConstants.push_back({ "mvThemeCol_Text", ImGuiCol_Text }); - ModuleConstants.push_back({ "mvThemeCol_TextDisabled", ImGuiCol_TextDisabled }); - ModuleConstants.push_back({ "mvThemeCol_WindowBg", ImGuiCol_WindowBg }); // Background of normal windows - ModuleConstants.push_back({ "mvThemeCol_ChildBg", ImGuiCol_ChildBg }); // Background of child windows - ModuleConstants.push_back({ "mvThemeCol_PopupBg", ImGuiCol_PopupBg }); // Background of popups, menus, tooltips windows - ModuleConstants.push_back({ "mvThemeCol_Border", ImGuiCol_Border }); - ModuleConstants.push_back({ "mvThemeCol_BorderShadow", ImGuiCol_BorderShadow }); - ModuleConstants.push_back({ "mvThemeCol_FrameBg", ImGuiCol_FrameBg }); // Background of checkbox, radio button, plot, slider, text input - ModuleConstants.push_back({ "mvThemeCol_FrameBgHovered", ImGuiCol_FrameBgHovered }); - ModuleConstants.push_back({ "mvThemeCol_FrameBgActive", ImGuiCol_FrameBgActive }); - ModuleConstants.push_back({ "mvThemeCol_TitleBg", ImGuiCol_TitleBg }); // Title bar - ModuleConstants.push_back({ "mvThemeCol_TitleBgActive", ImGuiCol_TitleBgActive }); // Title bar when focused - ModuleConstants.push_back({ "mvThemeCol_TitleBgCollapsed", ImGuiCol_TitleBgCollapsed }); // Title bar when collapsed - ModuleConstants.push_back({ "mvThemeCol_MenuBarBg", ImGuiCol_MenuBarBg }); - ModuleConstants.push_back({ "mvThemeCol_ScrollbarBg", ImGuiCol_ScrollbarBg }); - ModuleConstants.push_back({ "mvThemeCol_ScrollbarGrab", ImGuiCol_ScrollbarGrab }); - ModuleConstants.push_back({ "mvThemeCol_ScrollbarGrabHovered", ImGuiCol_ScrollbarGrabHovered }); - ModuleConstants.push_back({ "mvThemeCol_ScrollbarGrabActive", ImGuiCol_ScrollbarGrabActive }); - ModuleConstants.push_back({ "mvThemeCol_CheckMark", ImGuiCol_CheckMark }); // Checkbox tick and RadioButton circle - ModuleConstants.push_back({ "mvThemeCol_SliderGrab", ImGuiCol_SliderGrab }); - ModuleConstants.push_back({ "mvThemeCol_SliderGrabActive", ImGuiCol_SliderGrabActive }); - ModuleConstants.push_back({ "mvThemeCol_Button", ImGuiCol_Button }); - ModuleConstants.push_back({ "mvThemeCol_ButtonHovered", ImGuiCol_ButtonHovered }); - ModuleConstants.push_back({ "mvThemeCol_ButtonActive", ImGuiCol_ButtonActive }); - ModuleConstants.push_back({ "mvThemeCol_Header", ImGuiCol_Header }); // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem - ModuleConstants.push_back({ "mvThemeCol_HeaderHovered", ImGuiCol_HeaderHovered }); - ModuleConstants.push_back({ "mvThemeCol_HeaderActive", ImGuiCol_HeaderActive }); - ModuleConstants.push_back({ "mvThemeCol_Separator", ImGuiCol_Separator }); - ModuleConstants.push_back({ "mvThemeCol_SeparatorHovered", ImGuiCol_SeparatorHovered }); - ModuleConstants.push_back({ "mvThemeCol_SeparatorActive", ImGuiCol_SeparatorActive }); - ModuleConstants.push_back({ "mvThemeCol_ResizeGrip", ImGuiCol_ResizeGrip }); // Resize grip in lower-right and lower-left corners of windows. - ModuleConstants.push_back({ "mvThemeCol_ResizeGripHovered", ImGuiCol_ResizeGripHovered }); - ModuleConstants.push_back({ "mvThemeCol_ResizeGripActive", ImGuiCol_ResizeGripActive }); - ModuleConstants.push_back({ "mvThemeCol_InputTextCursor", ImGuiCol_InputTextCursor }); // InputText cursor/caret - ModuleConstants.push_back({ "mvThemeCol_TabHovered", ImGuiCol_TabHovered }); // Tab background, when hovered - ModuleConstants.push_back({ "mvThemeCol_Tab", ImGuiCol_Tab }); // Tab background, when tab-bar is focused & tab is unselected - ModuleConstants.push_back({ "mvThemeCol_TabSelected", ImGuiCol_TabSelected }); // Tab background, when tab-bar is focused & tab is selected - ModuleConstants.push_back({ "mvThemeCol_TabSelectedOverline", ImGuiCol_TabSelectedOverline }); // Tab horizontal overline, when tab-bar is focused & tab is selected - ModuleConstants.push_back({ "mvThemeCol_TabDimmed", ImGuiCol_TabDimmed }); // Tab background, when tab-bar is unfocused & tab is unselected - ModuleConstants.push_back({ "mvThemeCol_TabDimmedSelected", ImGuiCol_TabDimmedSelected }); // Tab background, when tab-bar is unfocused & tab is selected - ModuleConstants.push_back({ "mvThemeCol_TabDimmedSelectedOverline", ImGuiCol_TabDimmedSelectedOverline }); //..horizontal overline, when tab-bar is unfocused & tab is selected - ModuleConstants.push_back({ "mvThemeCol_DockingPreview", ImGuiCol_DockingPreview }); // Preview overlay color when about to docking something - ModuleConstants.push_back({ "mvThemeCol_DockingEmptyBg", ImGuiCol_DockingEmptyBg }); // Background color for empty node (e.g. CentralNode with no window docked into it) - ModuleConstants.push_back({ "mvThemeCol_PlotLines", ImGuiCol_PlotLines }); - ModuleConstants.push_back({ "mvThemeCol_PlotLinesHovered", ImGuiCol_PlotLinesHovered }); - ModuleConstants.push_back({ "mvThemeCol_PlotHistogram", ImGuiCol_PlotHistogram }); - ModuleConstants.push_back({ "mvThemeCol_PlotHistogramHovered", ImGuiCol_PlotHistogramHovered }); - ModuleConstants.push_back({ "mvThemeCol_TableHeaderBg", ImGuiCol_TableHeaderBg }); // Table header background - ModuleConstants.push_back({ "mvThemeCol_TableBorderStrong", ImGuiCol_TableBorderStrong }); // Table outer and header borders (prefer using Alpha=1.0 here) - ModuleConstants.push_back({ "mvThemeCol_TableBorderLight", ImGuiCol_TableBorderLight }); // Table inner borders (prefer using Alpha=1.0 here) - ModuleConstants.push_back({ "mvThemeCol_TableRowBg", ImGuiCol_TableRowBg }); // Table row background (even rows) - ModuleConstants.push_back({ "mvThemeCol_TableRowBgAlt", ImGuiCol_TableRowBgAlt }); // Table row background (odd rows) - // We don't have TextLink widget yet - // ModuleConstants.push_back({ "mvThemeCol_TextLink", ImGuiCol_TextLink }); // Hyperlink color - ModuleConstants.push_back({ "mvThemeCol_TextSelectedBg", ImGuiCol_TextSelectedBg }); // Selected text inside an InputText - ModuleConstants.push_back({ "mvThemeCol_TreeLines", ImGuiCol_TreeLines }); // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines - ModuleConstants.push_back({ "mvThemeCol_DragDropTarget", ImGuiCol_DragDropTarget }); // Rectangle border highlighting a drop target - ModuleConstants.push_back({ "mvThemeCol_DragDropTargetBg", ImGuiCol_DragDropTargetBg }); // Rectangle background highlighting a drop target - ModuleConstants.push_back({ "mvThemeCol_UnsavedMarker", ImGuiCol_UnsavedMarker }); // Unsaved Document marker (in window title and tabs) - ModuleConstants.push_back({ "mvThemeCol_NavCursor", ImGuiCol_NavCursor }); // Color of keyboard/gamepad navigation cursor/rectangle, when visible - ModuleConstants.push_back({ "mvThemeCol_NavWindowingHighlight", ImGuiCol_NavWindowingHighlight }); // Highlight window when using Ctrl+Tab - ModuleConstants.push_back({ "mvThemeCol_NavWindowingDimBg", ImGuiCol_NavWindowingDimBg }); // Darken/colorize entire screen behind the Ctrl+Tab window list, when active - ModuleConstants.push_back({ "mvThemeCol_ModalWindowDimBg", ImGuiCol_ModalWindowDimBg }); // Darken/colorize entire screen behind a modal window, when one is active - - // old names for colors that have been renamed in ImGui - keeping them for compatibility - ModuleConstants.push_back({ "mvThemeCol_TabActive", ImGuiCol_TabSelected }); - ModuleConstants.push_back({ "mvThemeCol_TabUnfocused", ImGuiCol_TabDimmed }); - ModuleConstants.push_back({ "mvThemeCol_TabUnfocusedActive", ImGuiCol_TabDimmedSelected }); - ModuleConstants.push_back({ "mvThemeCol_NavHighlight", ImGuiCol_NavCursor }); // Gamepad/keyboard: current highlighted item - - // plotting - - // item styling colors - ModuleConstants.push_back({ "mvPlotCol_Line", ImPlotCol_Line }); // plot line/outline color (defaults to next unused color in current colormap) - ModuleConstants.push_back({ "mvPlotCol_Fill", ImPlotCol_Fill }); // plot fill color for bars (defaults to the current line color) - ModuleConstants.push_back({ "mvPlotCol_MarkerOutline", ImPlotCol_MarkerOutline }); // marker outline color (defaults to the current line color) - ModuleConstants.push_back({ "mvPlotCol_MarkerFill", ImPlotCol_MarkerFill }); // marker fill color (defaults to the current line color) - ModuleConstants.push_back({ "mvPlotCol_ErrorBar", ImPlotCol_ErrorBar }); // error bar color (defaults to ImGuiCol_Text) - - // plot styling colors - ModuleConstants.push_back({ "mvPlotCol_FrameBg", ImPlotCol_FrameBg }); // plot frame background color (defaults to ImGuiCol_FrameBg) - ModuleConstants.push_back({ "mvPlotCol_PlotBg", ImPlotCol_PlotBg }); // plot area background color (defaults to ImGuiCol_WindowBg) - ModuleConstants.push_back({ "mvPlotCol_PlotBorder", ImPlotCol_PlotBorder }); // plot area border color (defaults to ImGuiCol_Border) - ModuleConstants.push_back({ "mvPlotCol_LegendBg", ImPlotCol_LegendBg }); // legend background color (defaults to ImGuiCol_PopupBg) - ModuleConstants.push_back({ "mvPlotCol_LegendBorder", ImPlotCol_LegendBorder }); // legend border color (defaults to ImPlotCol_PlotBorder) - ModuleConstants.push_back({ "mvPlotCol_LegendText", ImPlotCol_LegendText }); // legend text color (defaults to ImPlotCol_InlayText) - ModuleConstants.push_back({ "mvPlotCol_TitleText", ImPlotCol_TitleText }); // plot title text color (defaults to ImGuiCol_Text) - ModuleConstants.push_back({ "mvPlotCol_InlayText", ImPlotCol_InlayText }); // color of text appearing inside of plots (defaults to ImGuiCol_Text) - ModuleConstants.push_back({ "mvPlotCol_AxisText", ImPlotCol_AxisText }); // axis label and tick labels color (defaults to ImGuiCol_Text) - ModuleConstants.push_back({ "mvPlotCol_AxisGrid", ImPlotCol_AxisGrid }); // axis grid color (defaults to 25% ImPlotCol_AxisText) - ModuleConstants.push_back({ "mvPlotCol_AxisTick", ImPlotCol_AxisTick }); // axis tick color (defaults to AxisGrid) - ModuleConstants.push_back({ "mvPlotCol_AxisBg", ImPlotCol_AxisBg }); // background color of axis hover region (defaults to transparent) - ModuleConstants.push_back({ "mvPlotCol_AxisBgHovered", ImPlotCol_AxisBgHovered }); // axis hover color (defaults to ImGuiCol_ButtonHovered) - ModuleConstants.push_back({ "mvPlotCol_AxisBgActive", ImPlotCol_AxisBgActive }); // axis active color (defaults to ImGuiCol_ButtonActive) - ModuleConstants.push_back({ "mvPlotCol_Selection", ImPlotCol_Selection }); // box-selection color (defaults to yellow) - ModuleConstants.push_back({ "mvPlotCol_Crosshairs", ImPlotCol_Crosshairs }); // crosshairs color (defaults to ImPlotCol_PlotBorder) - - // nodes - ModuleConstants.push_back({ "mvNodeCol_NodeBackground", ImNodesCol_NodeBackground }); - ModuleConstants.push_back({ "mvNodeCol_NodeBackgroundHovered", ImNodesCol_NodeBackgroundHovered }); - ModuleConstants.push_back({ "mvNodeCol_NodeBackgroundSelected", ImNodesCol_NodeBackgroundSelected }); - ModuleConstants.push_back({ "mvNodeCol_NodeOutline", ImNodesCol_NodeOutline }); - ModuleConstants.push_back({ "mvNodeCol_TitleBar", ImNodesCol_TitleBar }); - ModuleConstants.push_back({ "mvNodeCol_TitleBarHovered", ImNodesCol_TitleBarHovered }); - ModuleConstants.push_back({ "mvNodeCol_TitleBarSelected", ImNodesCol_TitleBarSelected }); - ModuleConstants.push_back({ "mvNodeCol_Link", ImNodesCol_Link }); - ModuleConstants.push_back({ "mvNodeCol_LinkHovered", ImNodesCol_LinkHovered }); - ModuleConstants.push_back({ "mvNodeCol_LinkSelected", ImNodesCol_LinkSelected }); - ModuleConstants.push_back({ "mvNodeCol_Pin", ImNodesCol_Pin }); - ModuleConstants.push_back({ "mvNodeCol_PinHovered", ImNodesCol_PinHovered }); - ModuleConstants.push_back({ "mvNodeCol_BoxSelector", ImNodesCol_BoxSelector }); - ModuleConstants.push_back({ "mvNodeCol_BoxSelectorOutline", ImNodesCol_BoxSelectorOutline }); - ModuleConstants.push_back({ "mvNodeCol_GridBackground", ImNodesCol_GridBackground }); - ModuleConstants.push_back({ "mvNodeCol_GridLine", ImNodesCol_GridLine }); - ModuleConstants.push_back({ "mvNodesCol_GridLinePrimary", ImNodesCol_GridLinePrimary }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapBackground", ImNodesCol_MiniMapBackground }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapBackgroundHovered", ImNodesCol_MiniMapBackgroundHovered }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapOutline", ImNodesCol_MiniMapOutline }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapOutlineHovered", ImNodesCol_MiniMapOutlineHovered }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapNodeBackground", ImNodesCol_MiniMapNodeBackground }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapNodeBackgroundHovered", ImNodesCol_MiniMapNodeBackgroundHovered }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapNodeBackgroundSelected", ImNodesCol_MiniMapNodeBackgroundSelected }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapNodeOutline", ImNodesCol_MiniMapNodeOutline }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapLink", ImNodesCol_MiniMapLink }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapLinkSelected", ImNodesCol_MiniMapLinkSelected }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapCanvas", ImNodesCol_MiniMapCanvas }); - ModuleConstants.push_back({ "mvNodesCol_MiniMapCanvasOutline", ImNodesCol_MiniMapCanvasOutline }); - - - ModuleConstants.push_back({ "mvStyleVar_Alpha", ImGuiStyleVar_Alpha }); // float Alpha - ModuleConstants.push_back({ "mvStyleVar_DisabledAlpha", ImGuiStyleVar_DisabledAlpha }); // float DisabledAlpha - ModuleConstants.push_back({ "mvStyleVar_WindowPadding", ImGuiStyleVar_WindowPadding }); // ImVec2 WindowPadding - ModuleConstants.push_back({ "mvStyleVar_WindowRounding", ImGuiStyleVar_WindowRounding }); // float WindowRounding - ModuleConstants.push_back({ "mvStyleVar_WindowBorderSize", ImGuiStyleVar_WindowBorderSize }); // float WindowBorderSize - ModuleConstants.push_back({ "mvStyleVar_WindowMinSize", ImGuiStyleVar_WindowMinSize }); // ImVec2 WindowMinSize - ModuleConstants.push_back({ "mvStyleVar_WindowTitleAlign", ImGuiStyleVar_WindowTitleAlign }); // ImVec2 WindowTitleAlign - ModuleConstants.push_back({ "mvStyleVar_ChildRounding", ImGuiStyleVar_ChildRounding }); // float ChildRounding - ModuleConstants.push_back({ "mvStyleVar_ChildBorderSize", ImGuiStyleVar_ChildBorderSize }); // float ChildBorderSize - ModuleConstants.push_back({ "mvStyleVar_PopupRounding", ImGuiStyleVar_PopupRounding }); // float PopupRounding - ModuleConstants.push_back({ "mvStyleVar_PopupBorderSize", ImGuiStyleVar_PopupBorderSize }); // float PopupBorderSize - ModuleConstants.push_back({ "mvStyleVar_FramePadding", ImGuiStyleVar_FramePadding }); // ImVec2 FramePadding - ModuleConstants.push_back({ "mvStyleVar_FrameRounding", ImGuiStyleVar_FrameRounding }); // float FrameRounding - ModuleConstants.push_back({ "mvStyleVar_FrameBorderSize", ImGuiStyleVar_FrameBorderSize }); // float FrameBorderSize - ModuleConstants.push_back({ "mvStyleVar_ItemSpacing", ImGuiStyleVar_ItemSpacing }); // ImVec2 ItemSpacing - ModuleConstants.push_back({ "mvStyleVar_ItemInnerSpacing", ImGuiStyleVar_ItemInnerSpacing }); // ImVec2 ItemInnerSpacing - ModuleConstants.push_back({ "mvStyleVar_IndentSpacing", ImGuiStyleVar_IndentSpacing }); // float IndentSpacing - ModuleConstants.push_back({ "mvStyleVar_CellPadding", ImGuiStyleVar_CellPadding }); // ImVec2 CellPadding - ModuleConstants.push_back({ "mvStyleVar_ScrollbarSize", ImGuiStyleVar_ScrollbarSize }); // float ScrollbarSize - ModuleConstants.push_back({ "mvStyleVar_ScrollbarRounding", ImGuiStyleVar_ScrollbarRounding }); // float ScrollbarRounding - ModuleConstants.push_back({ "mvStyleVar_ScrollbarPadding", ImGuiStyleVar_ScrollbarPadding }); // float ScrollbarPadding - ModuleConstants.push_back({ "mvStyleVar_GrabMinSize", ImGuiStyleVar_GrabMinSize }); // float GrabMinSize - ModuleConstants.push_back({ "mvStyleVar_GrabRounding", ImGuiStyleVar_GrabRounding }); // float GrabRounding - ModuleConstants.push_back({ "mvStyleVar_ImageBorderSize", ImGuiStyleVar_ImageBorderSize }); // float ImageBorderSize - ModuleConstants.push_back({ "mvStyleVar_TabRounding", ImGuiStyleVar_TabRounding }); // float TabRounding - ModuleConstants.push_back({ "mvStyleVar_TabBorderSize", ImGuiStyleVar_TabBorderSize }); // float TabBorderSize - ModuleConstants.push_back({ "mvStyleVar_TabMinWidthBase", ImGuiStyleVar_TabMinWidthBase }); // float TabMinWidthBase - ModuleConstants.push_back({ "mvStyleVar_TabMinWidthShrink", ImGuiStyleVar_TabMinWidthShrink }); // float TabMinWidthShrink - ModuleConstants.push_back({ "mvStyleVar_TabBarBorderSize", ImGuiStyleVar_TabBarBorderSize }); // float TabBarBorderSize - ModuleConstants.push_back({ "mvStyleVar_TabBarOverlineSize", ImGuiStyleVar_TabBarOverlineSize }); // float TabBarOverlineSize - ModuleConstants.push_back({ "mvStyleVar_TableAngledHeadersAngle", ImGuiStyleVar_TableAngledHeadersAngle }); // float TableAngledHeadersAngle - ModuleConstants.push_back({ "mvStyleVar_TableAngledHeadersTextAlign", ImGuiStyleVar_TableAngledHeadersTextAlign }); // ImVec2 TableAngledHeadersTextAlign - ModuleConstants.push_back({ "mvStyleVar_TreeLinesSize", ImGuiStyleVar_TreeLinesSize }); // float TreeLinesSize - ModuleConstants.push_back({ "mvStyleVar_TreeLinesRounding", ImGuiStyleVar_TreeLinesRounding }); // float TreeLinesRounding - ModuleConstants.push_back({ "mvStyleVar_ButtonTextAlign", ImGuiStyleVar_ButtonTextAlign }); // ImVec2 ButtonTextAlign - ModuleConstants.push_back({ "mvStyleVar_SelectableTextAlign", ImGuiStyleVar_SelectableTextAlign }); // ImVec2 SelectableTextAlign - ModuleConstants.push_back({ "mvStyleVar_SeparatorTextBorderSize", ImGuiStyleVar_SeparatorTextBorderSize }); // float SeparatorTextBorderSize - ModuleConstants.push_back({ "mvStyleVar_SeparatorTextAlign", ImGuiStyleVar_SeparatorTextAlign }); // ImVec2 SeparatorTextAlign - ModuleConstants.push_back({ "mvStyleVar_SeparatorTextPadding", ImGuiStyleVar_SeparatorTextPadding }); // ImVec2 SeparatorTextPadding - ModuleConstants.push_back({ "mvStyleVar_DockingSeparatorSize", ImGuiStyleVar_DockingSeparatorSize }); // float DockingSeparatorSize - - // item styling variables - ModuleConstants.push_back({ "mvPlotStyleVar_LineWeight", ImPlotStyleVar_LineWeight }); // float, plot item line weight in pixels - ModuleConstants.push_back({ "mvPlotStyleVar_Marker", ImPlotStyleVar_Marker }); // int, marker specification - ModuleConstants.push_back({ "mvPlotStyleVar_MarkerSize", ImPlotStyleVar_MarkerSize }); // float, marker size in pixels (roughly the marker's "radius") - ModuleConstants.push_back({ "mvPlotStyleVar_MarkerWeight", ImPlotStyleVar_MarkerWeight }); // float, plot outline weight of markers in pixels - ModuleConstants.push_back({ "mvPlotStyleVar_FillAlpha", ImPlotStyleVar_FillAlpha }); // float, alpha modifier applied to all plot item fills - ModuleConstants.push_back({ "mvPlotStyleVar_ErrorBarSize", ImPlotStyleVar_ErrorBarSize }); // float, error bar whisker width in pixels - ModuleConstants.push_back({ "mvPlotStyleVar_ErrorBarWeight", ImPlotStyleVar_ErrorBarWeight }); // float, error bar whisker weight in pixels - ModuleConstants.push_back({ "mvPlotStyleVar_DigitalBitHeight", ImPlotStyleVar_DigitalBitHeight }); // float, digital channels bit height (at 1) in pixels - ModuleConstants.push_back({ "mvPlotStyleVar_DigitalBitGap", ImPlotStyleVar_DigitalBitGap }); // float, digital channels bit padding gap in pixels - - // plot styling variables - ModuleConstants.push_back({ "mvPlotStyleVar_PlotBorderSize", ImPlotStyleVar_PlotBorderSize }); // float, thickness of border around plot area - ModuleConstants.push_back({ "mvPlotStyleVar_MinorAlpha", ImPlotStyleVar_MinorAlpha }); // float, alpha multiplier applied to minor axis grid lines - ModuleConstants.push_back({ "mvPlotStyleVar_MajorTickLen", ImPlotStyleVar_MajorTickLen }); // ImVec2, major tick lengths for X and Y axes - ModuleConstants.push_back({ "mvPlotStyleVar_MinorTickLen", ImPlotStyleVar_MinorTickLen }); // ImVec2, minor tick lengths for X and Y axes - ModuleConstants.push_back({ "mvPlotStyleVar_MajorTickSize", ImPlotStyleVar_MajorTickSize }); // ImVec2, line thickness of major ticks - ModuleConstants.push_back({ "mvPlotStyleVar_MinorTickSize", ImPlotStyleVar_MinorTickSize }); // ImVec2, line thickness of minor ticks - ModuleConstants.push_back({ "mvPlotStyleVar_MajorGridSize", ImPlotStyleVar_MajorGridSize }); // ImVec2, line thickness of major grid lines - ModuleConstants.push_back({ "mvPlotStyleVar_MinorGridSize", ImPlotStyleVar_MinorGridSize }); // ImVec2, line thickness of minor grid lines - ModuleConstants.push_back({ "mvPlotStyleVar_PlotPadding", ImPlotStyleVar_PlotPadding }); // ImVec2, padding between widget frame and plot area, labels, or outside legends (i.e. main padding) - ModuleConstants.push_back({ "mvPlotStyleVar_LabelPadding", ImPlotStyleVar_LabelPadding }); // ImVec2, padding between axes labels, tick labels, and plot edge - ModuleConstants.push_back({ "mvPlotStyleVar_LegendPadding", ImPlotStyleVar_LegendPadding }); // ImVec2, legend padding from plot edges - ModuleConstants.push_back({ "mvPlotStyleVar_LegendInnerPadding", ImPlotStyleVar_LegendInnerPadding }); // ImVec2, legend inner padding from legend edges - ModuleConstants.push_back({ "mvPlotStyleVar_LegendSpacing", ImPlotStyleVar_LegendSpacing }); // ImVec2, spacing between legend entries - ModuleConstants.push_back({ "mvPlotStyleVar_MousePosPadding", ImPlotStyleVar_MousePosPadding }); // ImVec2, padding between plot edge and interior info text - ModuleConstants.push_back({ "mvPlotStyleVar_AnnotationPadding", ImPlotStyleVar_AnnotationPadding }); // ImVec2, text padding around annotation labels - ModuleConstants.push_back({ "mvPlotStyleVar_FitPadding", ImPlotStyleVar_FitPadding }); // ImVec2, additional fit padding as a percentage of the fit extents (e.g. ImVec2(0.1f,0.1f) adds 10% to the fit extents of X and Y) - ModuleConstants.push_back({ "mvPlotStyleVar_PlotDefaultSize", ImPlotStyleVar_PlotDefaultSize }); // ImVec2, default size used when ImVec2(0,0) is passed to BeginPlot - ModuleConstants.push_back({ "mvPlotStyleVar_PlotMinSize", ImPlotStyleVar_PlotMinSize }); // ImVec2, minimum size plot frame can be when shrunk - - // nodes - ModuleConstants.push_back({ "mvNodeStyleVar_GridSpacing", ImNodesStyleVar_GridSpacing }); - ModuleConstants.push_back({ "mvNodeStyleVar_NodeCornerRounding", ImNodesStyleVar_NodeCornerRounding }); - ModuleConstants.push_back({ "mvNodeStyleVar_NodePadding", ImNodesStyleVar_NodePadding }); - ModuleConstants.push_back({ "mvNodeStyleVar_NodeBorderThickness", ImNodesStyleVar_NodeBorderThickness }); - ModuleConstants.push_back({ "mvNodeStyleVar_LinkThickness", ImNodesStyleVar_LinkThickness }); - ModuleConstants.push_back({ "mvNodeStyleVar_LinkLineSegmentsPerLength", ImNodesStyleVar_LinkLineSegmentsPerLength }); - ModuleConstants.push_back({ "mvNodeStyleVar_LinkHoverDistance", ImNodesStyleVar_LinkHoverDistance }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinCircleRadius", ImNodesStyleVar_PinCircleRadius }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinQuadSideLength", ImNodesStyleVar_PinQuadSideLength }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinTriangleSideLength", ImNodesStyleVar_PinTriangleSideLength }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinLineThickness", ImNodesStyleVar_PinLineThickness }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinHoverRadius", ImNodesStyleVar_PinHoverRadius }); - ModuleConstants.push_back({ "mvNodeStyleVar_PinOffset", ImNodesStyleVar_PinOffset }); - ModuleConstants.push_back({ "mvNodesStyleVar_MiniMapPadding", ImNodesStyleVar_MiniMapPadding }); - ModuleConstants.push_back({ "mvNodesStyleVar_MiniMapOffset", ImNodesStyleVar_MiniMapOffset }); - - #define X(el) ModuleConstants.push_back({ std::string(#el), (long)mvAppItemType::el }); - MV_ITEM_TYPES - #undef X - - int j = 0; - for (int i = MV_RESERVED_UUID_start; i < MV_RESERVED_UUID_start+MV_RESERVED_UUIDs; i++) - { - ModuleConstants.push_back({"mvReservedUUID_" + std::to_string(j), (long)i}); - j++; - } - - } - - First_Run = false; - return ModuleConstants; -} - -static void -PreFetchItemInfo(mvUUID* out_name, mvUUID* out_parent, mvUUID* out_before, std::string* out_alias, PyObject* args, PyObject* kwargs) -{ - - if (kwargs) - { - if (PyObject* item = PyDict_GetItemString(kwargs, "parent")) - { - if (PyUnicode_Check(item)) - *out_parent = GetIdFromAlias(*GContext->itemRegistry, ToString(item)); - else - *out_parent = ToUUID(item); - } - - if (PyObject* item = PyDict_GetItemString(kwargs, "before")) - { - if (PyUnicode_Check(item)) - *out_before = GetIdFromAlias(*GContext->itemRegistry, ToString(item)); - else - *out_before = ToUUID(item); - } - - if (PyObject* item = PyDict_GetItemString(kwargs, "tag")) - { - if (PyUnicode_Check(item)) - *out_alias = ToString(item); - else - { - auto id = ToUUID(item); - if (id > 0) - *out_name = id; - } - }; - } -} - -static PyObject* -common_constructor(const char* command, mvAppItemType type, PyObject* self, PyObject* args, PyObject* kwargs) -{ - - std::shared_ptr item = nullptr; - mvUUID id = 0; - mvUUID parent = 0; - mvUUID before = 0; - std::string alias; - - PreFetchItemInfo(&id, &parent, &before, &alias, args, kwargs); - - // generate id if not specified - if (id == 0) - id = GenerateUUID(); - - item = DearPyGui::CreateEntity(type, id); - - i32 flags = DearPyGui::GetEntityDesciptionFlags(type); - if (flags & MV_ITEM_DESC_DRAW_CMP) - item->drawInfo = std::make_shared(); - - // register alias if present - if (!alias.empty()) - { - RemoveAlias(*GContext->itemRegistry, item->config.alias, true); - item->config.alias = alias; - AddAlias(*GContext->itemRegistry, item->config.alias, item->uuid); - } - - VerifyArgumentCount(GetParsers()[command], args); - - if(!GContext->IO.skipRequiredArgs) - item->handleSpecificRequiredArgs(args); - - if(!GContext->IO.skipPositionalArgs) - item->handleSpecificPositionalArgs(args); - - if(!GContext->IO.skipKeywordArgs) - item->handleKeywordArgs(kwargs, command); - - AddItemWithRuntimeChecks((*GContext->itemRegistry), item, parent, before); - - GContext->itemRegistry->allItems[id] = item.get(); - - // return raw UUID if alias not used - if (item->config.alias.empty()) - return Py_BuildValue("K", id); - - return ToPyString(item->config.alias); -} - -#define X(el) static PyObject* el##_command(PyObject* self, PyObject* args, PyObject* kwargs){return common_constructor(GetEntityCommand(mvAppItemType::el), mvAppItemType::el, self, args, kwargs);} -MV_ITEM_TYPES -#undef X - -PyMODINIT_FUNC -PyInit__dearpygui(void) -{ - - static std::vector methods; - methods.clear(); - - #define X(el) methods.push_back({GetEntityCommand(mvAppItemType::el), (PyCFunction)el##_command, METH_VARARGS | METH_KEYWORDS, GetParsers()[GetEntityCommand(mvAppItemType::el)].documentation.c_str()}); - MV_ITEM_TYPES - #undef X - - // color maps - MV_ADD_COMMAND(bind_colormap); - MV_ADD_COMMAND(sample_colormap); - MV_ADD_COMMAND(get_colormap_color); - - // file dialog - MV_ADD_COMMAND(get_file_dialog_info); - - // window commands - MV_ADD_COMMAND(set_x_scroll); - MV_ADD_COMMAND(set_y_scroll); - MV_ADD_COMMAND(get_x_scroll); - MV_ADD_COMMAND(get_y_scroll); - MV_ADD_COMMAND(get_x_scroll_max); - MV_ADD_COMMAND(get_y_scroll_max); - - // draw layer - MV_ADD_COMMAND(set_clip_space); - - // draw node - MV_ADD_COMMAND(apply_transform); - MV_ADD_COMMAND(create_rotation_matrix); - MV_ADD_COMMAND(create_translation_matrix); - MV_ADD_COMMAND(create_scale_matrix); - MV_ADD_COMMAND(create_lookat_matrix); - MV_ADD_COMMAND(create_perspective_matrix); - MV_ADD_COMMAND(create_orthographic_matrix); - MV_ADD_COMMAND(create_fps_matrix); - - // fonts - MV_ADD_COMMAND(bind_font); - MV_ADD_COMMAND(get_text_size); - MV_ADD_COMMAND(get_global_font_scale); - MV_ADD_COMMAND(set_global_font_scale); - - // node editor - MV_ADD_COMMAND(get_selected_nodes); - MV_ADD_COMMAND(get_selected_links); - MV_ADD_COMMAND(clear_selected_nodes); - MV_ADD_COMMAND(clear_selected_links); - - // plots - MV_ADD_COMMAND(get_plot_query_rects); - - // plot axes - MV_ADD_COMMAND(reset_axis_ticks); - MV_ADD_COMMAND(set_axis_ticks); - MV_ADD_COMMAND(set_axis_limits_constraints); - MV_ADD_COMMAND(reset_axis_limits_constraints); - MV_ADD_COMMAND(set_axis_zoom_constraints); - MV_ADD_COMMAND(reset_axis_zoom_constraints); - MV_ADD_COMMAND(set_axis_limits); - MV_ADD_COMMAND(set_axis_limits_auto); - MV_ADD_COMMAND(get_axis_limits); - MV_ADD_COMMAND(fit_axis_data); - - // tables - MV_ADD_COMMAND(highlight_table_column); - MV_ADD_COMMAND(unhighlight_table_column); - MV_ADD_COMMAND(set_table_row_color); - MV_ADD_COMMAND(unset_table_row_color); - MV_ADD_COMMAND(highlight_table_cell); - MV_ADD_COMMAND(unhighlight_table_cell); - MV_ADD_COMMAND(highlight_table_row); - MV_ADD_COMMAND(unhighlight_table_row); - MV_ADD_COMMAND(is_table_column_highlighted); - MV_ADD_COMMAND(is_table_row_highlighted); - MV_ADD_COMMAND(is_table_cell_highlighted); - - // themes - MV_ADD_COMMAND(bind_theme); - - // tools - MV_ADD_COMMAND(show_tool); - - // callback registry - MV_ADD_COMMAND(set_frame_callback); - MV_ADD_COMMAND(set_exit_callback); - MV_ADD_COMMAND(set_viewport_resize_callback); - - // viewport - MV_ADD_COMMAND(show_viewport); - MV_ADD_COMMAND(create_viewport); - MV_ADD_COMMAND(configure_viewport); - MV_ADD_COMMAND(maximize_viewport); - MV_ADD_COMMAND(minimize_viewport); - MV_ADD_COMMAND(get_viewport_configuration); - MV_ADD_COMMAND(is_viewport_ok); - MV_ADD_COMMAND(toggle_viewport_fullscreen); - - // context - MV_ADD_COMMAND(create_context); - MV_ADD_COMMAND(destroy_context); - MV_ADD_COMMAND(lock_mutex); - MV_ADD_COMMAND(unlock_mutex); - MV_ADD_COMMAND(setup_dearpygui); - MV_ADD_COMMAND(render_dearpygui_frame); - MV_ADD_COMMAND(get_delta_time); - MV_ADD_COMMAND(get_total_time); - MV_ADD_COMMAND(stop_dearpygui); - MV_ADD_COMMAND(is_dearpygui_running); - MV_ADD_COMMAND(generate_uuid); - MV_ADD_COMMAND(save_init_file); - MV_ADD_COMMAND(output_frame_buffer); - MV_ADD_COMMAND(load_image); - MV_ADD_COMMAND(save_image); - // MV_ADD_COMMAND(set_decimal_point); - MV_ADD_COMMAND(split_frame); - MV_ADD_COMMAND(get_frame_count); - MV_ADD_COMMAND(get_frame_rate); - MV_ADD_COMMAND(get_app_configuration); - MV_ADD_COMMAND(configure_app); - MV_ADD_COMMAND(get_drawing_mouse_pos); - MV_ADD_COMMAND(is_mouse_button_dragging); - MV_ADD_COMMAND(is_mouse_button_down); - MV_ADD_COMMAND(is_mouse_button_clicked); - MV_ADD_COMMAND(is_mouse_button_double_clicked); - MV_ADD_COMMAND(is_mouse_button_released); - MV_ADD_COMMAND(get_mouse_drag_delta); - MV_ADD_COMMAND(get_mouse_pos); - MV_ADD_COMMAND(get_plot_mouse_pos); - MV_ADD_COMMAND(is_key_pressed); - MV_ADD_COMMAND(is_key_released); - MV_ADD_COMMAND(is_key_down); - MV_ADD_COMMAND(get_callback_queue); - MV_ADD_COMMAND(set_clipboard_text); - MV_ADD_COMMAND(get_clipboard_text); - - // item registry - MV_ADD_COMMAND(focus_item); - MV_ADD_COMMAND(get_aliases); - MV_ADD_COMMAND(add_alias); - MV_ADD_COMMAND(remove_alias); - MV_ADD_COMMAND(does_alias_exist); - MV_ADD_COMMAND(get_alias_id); - MV_ADD_COMMAND(move_item); - MV_ADD_COMMAND(delete_item); - MV_ADD_COMMAND(does_item_exist); - MV_ADD_COMMAND(move_item_down); - MV_ADD_COMMAND(move_item_up); - MV_ADD_COMMAND(get_windows); - MV_ADD_COMMAND(get_all_items); - MV_ADD_COMMAND(get_active_window); - MV_ADD_COMMAND(get_focused_item); - MV_ADD_COMMAND(set_primary_window); - MV_ADD_COMMAND(push_container_stack); - MV_ADD_COMMAND(pop_container_stack); - MV_ADD_COMMAND(top_container_stack); - MV_ADD_COMMAND(empty_container_stack); - MV_ADD_COMMAND(last_item); - MV_ADD_COMMAND(last_container); - MV_ADD_COMMAND(last_root); - MV_ADD_COMMAND(unstage); - MV_ADD_COMMAND(reorder_items); - MV_ADD_COMMAND(show_imgui_demo); - MV_ADD_COMMAND(show_implot_demo); - MV_ADD_COMMAND(show_item_debug); - MV_ADD_COMMAND(get_item_info); - MV_ADD_COMMAND(set_item_alias); - MV_ADD_COMMAND(get_item_alias); - MV_ADD_COMMAND(get_item_types); - MV_ADD_COMMAND(get_item_configuration); - MV_ADD_COMMAND(get_item_state); - MV_ADD_COMMAND(configure_item); - MV_ADD_COMMAND(get_value); - MV_ADD_COMMAND(get_values); - MV_ADD_COMMAND(set_value); - MV_ADD_COMMAND(reset_pos); - MV_ADD_COMMAND(set_item_children); - MV_ADD_COMMAND(bind_item_handler_registry); - MV_ADD_COMMAND(bind_item_font); - MV_ADD_COMMAND(bind_item_theme); - MV_ADD_COMMAND(capture_next_item); - MV_ADD_COMMAND(get_platform); - - methods.push_back({ NULL, NULL, 0, NULL }); - - static PyModuleDef dearpyguiModule = { - PyModuleDef_HEAD_INIT, "_dearpygui", NULL, -1, methods.data(), - NULL, NULL, NULL, NULL - }; - - PyObject* m; - PymvBufferType.tp_new = PyType_GenericNew; - if (PyType_Ready(&PymvBufferType) < 0) - return NULL; - - PymvVec4Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&PymvVec4Type) < 0) - return NULL; - - PymvMat4Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&PymvMat4Type) < 0) - return NULL; - - m = PyModule_Create(&dearpyguiModule); - if (m == NULL) - return NULL; - - const auto& constants = GetModuleConstants(); - - // handled in the stub file - for (auto& item : constants) - PyModule_AddIntConstant(m, item.first.c_str(), item.second); - - auto MarvelError = PyErr_NewException("dearpygui.error", NULL, NULL); - Py_XINCREF(MarvelError); - if (PyModule_AddObject(m, "error", MarvelError) < 0) { - Py_XDECREF(MarvelError); - Py_CLEAR(MarvelError); - Py_DECREF(m); - return NULL; - } - - Py_INCREF(&PymvBufferType); - PyModule_AddObject(m, "mvBuffer", (PyObject*)&PymvBufferType); - - Py_INCREF(&PymvVec4Type); - PyModule_AddObject(m, "mvVec4", (PyObject*)&PymvVec4Type); - - Py_INCREF(&PymvMat4Type); - PyModule_AddObject(m, "mvMat4", (PyObject*)&PymvMat4Type); - - return m; -} \ No newline at end of file diff --git a/src/dearpygui.h b/src/dearpygui.h deleted file mode 100644 index 542b88e5a..000000000 --- a/src/dearpygui.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include -#include -#include "mvPyUtils.h" - -PyMODINIT_FUNC PyInit__dearpygui(void); - -const std::map& GetModuleParsers(); -const std::vector>& GetModuleConstants(); \ No newline at end of file diff --git a/src/dearpygui_commands.h b/src/dearpygui_commands.h deleted file mode 100644 index ed6653500..000000000 --- a/src/dearpygui_commands.h +++ /dev/null @@ -1,4241 +0,0 @@ -#include "mvAppItemCommons.h" -#include "mvFontManager.h" -#include "mvItemRegistry.h" -#include -#include -#include "mvToolManager.h" -#include "mvCustomTypes.h" -#include "mvPyUtils.h" -#include "mvViewport.h" -#include "stb_image.h" -#include "stb_image_write.h" -#include "mvProfiler.h" -#include "mvUtilities.h" -#include - -#ifndef _WIN32 -#define strnicmp(s1, s2, len) strncasecmp(s1, s2, len) -#endif - -static PyObject* -bind_colormap(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* sourceraw; - - if (!Parse((GetParsers())["bind_colormap"], args, kwargs, __FUNCTION__, &itemraw, &sourceraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID source = GetIDFromPyObject(sourceraw); - - auto aitem = GetItem((*GContext->itemRegistry), item); - if (aitem == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_colormap", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (source > 15) - { - auto asource = GetItem(*GContext->itemRegistry, source); - if (asource == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_colormap", - "Source Item not found: " + std::to_string(source), nullptr); - return nullptr; - } - - if (asource->type == mvAppItemType::mvColorMap) - { - mvColorMap* colormap = static_cast(asource); - source = colormap->configData.colorMap; - } - } - - if (aitem->type == mvAppItemType::mvPlot) - { - mvPlot* graph = static_cast(aitem); - graph->configData._colormap = (ImPlotColormap)source; - graph->configData._useColorMap = true; - graph->configData._newColorMap = true; - } - - else if (aitem->type == mvAppItemType::mvColorMapScale) - { - mvColorMapScale* graph = static_cast(aitem); - graph->configData.colorMap = (ImPlotColormap)source; - } - - else if (aitem->type == mvAppItemType::mvColorMapButton) - { - mvColorMapButton* graph = static_cast(aitem); - graph->configData.colorMap = (ImPlotColormap)source; - } - - else if (aitem->type == mvAppItemType::mvColorMapSlider) - { - mvColorMapSlider* graph = static_cast(aitem); - graph->configData.colorMap = (ImPlotColormap)source; - } - - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "bind_colormap", - "Incompatible type. Expected types include: mvPlot, mvColorMapScale, mvColorMapButton", aitem); - return nullptr; - } - - - return GetPyNone(); -} - -static PyObject* -sample_colormap(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - float t; - - if (!Parse((GetParsers())["sample_colormap"], args, kwargs, __FUNCTION__, &itemraw, &t)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (item > 15) - { - auto asource = GetItem((*GContext->itemRegistry), item); - if (asource == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "sample_colormap", - "Source Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (asource->type == mvAppItemType::mvColorMap) - { - mvColorMap* colormap = static_cast(asource); - item = colormap->configData.colorMap; - } - } - - - if (!GContext->started) - { - mvThrowPythonError(mvErrorCode::mvNone, "sample_colormap", "This command can only be ran once the app is started.", nullptr); - return nullptr; - } - - ImVec4 result = ImPlot::SampleColormap(t, (ImPlotColormap)item); - mvColor resultColor = mvColor(result.x, result.y, result.z, result.w); - return ToPyColor(resultColor); -} - -static PyObject* -get_colormap_color(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - int index; - - if (!Parse((GetParsers())["get_colormap_color"], args, kwargs, __FUNCTION__, &itemraw, &index)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (item > 15) - { - auto asource = GetItem((*GContext->itemRegistry), item); - if (asource == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_colormap_color", - "Source Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (asource->type == mvAppItemType::mvColorMap) - { - mvColorMap* colormap = static_cast(asource); - item = colormap->configData.colorMap; - } - } - - - ImVec4 result = ImPlot::GetColormapColor(index, (ImPlotColormap)item); - mvColor resultColor = mvColor(result.x, result.y, result.z, result.w); - return ToPyColor(resultColor); -} - -static PyObject* -get_file_dialog_info(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* file_dialog_raw; - - if (!Parse((GetParsers())["get_file_dialog_info"], args, kwargs, __FUNCTION__, &file_dialog_raw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID file_dialog = GetIDFromPyObject(file_dialog_raw); - - auto aplot = GetItem(*GContext->itemRegistry, file_dialog); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvNone, std::to_string(file_dialog) + " plot does not exist."); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvFileDialog) - { - mvThrowPythonError(mvErrorCode::mvNone, std::to_string(file_dialog) + " is not a plot."); - return nullptr; - } - - mvFileDialog* graph = static_cast(aplot); - - return graph->getInfoDict(); -} - -static PyObject* -set_x_scroll(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - float value; - int when = (int)mvSetScrollFlags_Delayed; - - if (!Parse((GetParsers())["set_x_scroll"], args, kwargs, __FUNCTION__, - &itemraw, &value, &when)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_x_scroll", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - window->config.scrollX = value; - window->config.scrollXFlags = (mvSetScrollFlags)when; - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_x_scroll", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -set_y_scroll(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - float value; - int when = (int)mvSetScrollFlags_Delayed; - - if (!Parse((GetParsers())["set_y_scroll"], args, kwargs, __FUNCTION__, - &itemraw, &value, &when)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_y_scroll", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - window->config.scrollY = value; - window->config.scrollYFlags = (mvSetScrollFlags)when; - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_y_scroll", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_x_scroll(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["get_x_scroll"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_x_scroll", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - return ToPyFloat(window->state.scrollPos.x); - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_x_scroll", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_y_scroll(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["get_y_scroll"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_y_scroll", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - return ToPyFloat(window->state.scrollPos.y); - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_y_scroll", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_x_scroll_max(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["get_x_scroll_max"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_x_scroll_max", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - return ToPyFloat(window->state.scrollMax.x); - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_x_scroll_max", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_y_scroll_max(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["get_y_scroll_max"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto window = GetItem((*GContext->itemRegistry), item); - if (window == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_y_scroll_max", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (DearPyGui::GetApplicableState(window->type) & MV_STATE_SCROLL) - { - return ToPyFloat(window->state.scrollMax.y); - } - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_y_scroll_max", - "Incompatible type. Expected types include: mvWindowAppItem, mvChildWindow, mvTable, mvListbox", window); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -set_clip_space(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - float topleftx = 0.0f; - float toplefty = 0.0f; - float width = 0.0f; - float height = 0.0f; - float mindepth = 0.0f; - float maxdepth = 0.0f; - - if (!Parse((GetParsers())["set_clip_space"], args, kwargs, __FUNCTION__, &itemraw, - &topleftx, &toplefty, &width, &height, &mindepth, &maxdepth)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto aitem = GetItem((*GContext->itemRegistry), item); - if (aitem == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "apply_transform", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (aitem->type == mvAppItemType::mvDrawLayer) - { - mvDrawLayer* graph = static_cast(aitem); - graph->drawInfo->clipViewport[0] = topleftx; - graph->drawInfo->clipViewport[1] = toplefty + height; - graph->drawInfo->clipViewport[2] = width; - graph->drawInfo->clipViewport[3] = height; - graph->drawInfo->clipViewport[4] = mindepth; - graph->drawInfo->clipViewport[5] = maxdepth; - - graph->drawInfo->transform = mvCreateMatrix( - width, 0.0f, 0.0f, topleftx + (width / 2.0f), - 0.0f, -height, 0.0f, toplefty + (height / 2.0f), - 0.0f, 0.0f, 0.25f, 0.5f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - } - - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "applydrawInfo->transform", - "Incompatible type. Expected types include: mvDrawLayer", aitem); - return nullptr; - } - - - return GetPyNone(); -} - -static PyObject* -apply_transform(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* transform; - - if (!Parse((GetParsers())["apply_transform"], args, kwargs, __FUNCTION__, &itemraw, &transform)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - PymvMat4* atransform = (PymvMat4*)transform; - - auto aitem = GetItem((*GContext->itemRegistry), item); - if (aitem == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "apply_transform", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (aitem->type == mvAppItemType::mvDrawNode) - { - mvDrawNode* graph = static_cast(aitem); - graph->drawInfo->appliedTransform = atransform->m; - } - - else - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "apply_transform", - "Incompatible type. Expected types include: mvDrawNode", aitem); - return nullptr; - } - - - return GetPyNone(); -} - -static PyObject* -create_rotation_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - static mvMat4 identity = mvIdentityMat4(); - float angle = 0.0f; - PyObject* axis; - - if (!Parse((GetParsers())["create_rotation_matrix"], args, kwargs, __FUNCTION__, &angle, &axis)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvVec4 aaxis = ToVec4(axis); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvRotate(identity, angle, aaxis.xyz()); - - return newbuffer; -} - -static PyObject* -create_perspective_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - float fov = 0.0f; - float aspect = 0.0f; - float zNear = 0.0f; - float zFar = 0.0f; - - if (!Parse((GetParsers())["create_perspective_matrix"], args, kwargs, __FUNCTION__, - &fov, &aspect, &zNear, &zFar)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvPerspectiveRH(fov, aspect, zNear, zFar); - - return newbuffer; -} - -static PyObject* -create_orthographic_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - float left = 0.0f; - float right = 0.0f; - float bottom = 0.0f; - float top = 0.0f; - float zNear = 0.0f; - float zFar = 0.0f; - - if (!Parse((GetParsers())["create_orthographic_matrix"], args, kwargs, __FUNCTION__, - &left, &right, &bottom, &top, &zNear, &zFar)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvOrthoRH(left, right, bottom, top, zNear, zFar); - - return newbuffer; -} - -static PyObject* -create_translation_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - static mvMat4 identity = mvIdentityMat4(); - PyObject* axis; - - if (!Parse((GetParsers())["create_translation_matrix"], args, kwargs, __FUNCTION__, &axis)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvVec4 aaxis = ToVec4(axis); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvTranslate(identity, aaxis.xyz()); - - return newbuffer; -} - -static PyObject* -create_scale_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - static mvMat4 identity = mvIdentityMat4(); - PyObject* axis; - - if (!Parse((GetParsers())["create_scale_matrix"], args, kwargs, __FUNCTION__, &axis)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvVec4 aaxis = ToVec4(axis); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvScale(identity, aaxis.xyz()); - - return newbuffer; -} - -static PyObject* -create_lookat_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - static mvMat4 identity = mvIdentityMat4(); - PyObject* eye; - PyObject* center; - PyObject* up; - - if (!Parse((GetParsers())["create_lookat_matrix"], args, kwargs, __FUNCTION__, - &eye, ¢er, &up)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvVec4 aeye = ToVec4(eye); - mvVec4 acenter = ToVec4(center); - mvVec4 aup = ToVec4(up); - - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvLookAtRH(aeye.xyz(), acenter.xyz(), aup.xyz()); - - return newbuffer; -} - -static PyObject* -create_fps_matrix(PyObject* self, PyObject* args, PyObject* kwargs) -{ - static mvMat4 identity = mvIdentityMat4(); - PyObject* eye; - f32 pitch = 0.0f; - f32 yaw = 0.0f; - - if (!Parse((GetParsers())["create_fps_matrix"], args, kwargs, __FUNCTION__, - &eye, &pitch, &yaw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvVec4 aeye = ToVec4(eye); - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - newbufferview->m = mvFPSViewRH(aeye.xyz(), pitch, yaw); - - return newbuffer; -} - -static PyObject* -bind_font(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["bind_font"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID itemId = GetIDFromPyObject(itemraw); - - if (itemId == 0) - { - mvToolManager::GetFontManager().clearDefaultFont(); - return GetPyNone(); - } - - auto item = GetRefItem((*GContext->itemRegistry), itemId); - if (item == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_font", - "Item not found: " + std::to_string(itemId), nullptr); - return nullptr; - } - - if (item->type != mvAppItemType::mvFont) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "bind_font", - "Incompatible type. Expected types include: mvFont", item.get()); - return nullptr; - } - - mvToolManager::GetFontManager().setDefaultFont(item); - - return GetPyNone(); -} - -static PyObject* -get_text_size(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* text; - float wrap_width = -1.0f; - PyObject* fontRaw; - - if (!Parse((GetParsers())["get_text_size"], args, kwargs, __FUNCTION__, - &text, &wrap_width, &fontRaw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID font = GetIDFromPyObject(fontRaw); - - if (font == 0) - { - if (GContext->frame < 1) - return GetPyNone(); - - ImVec2 size = ImGui::CalcTextSize(text, 0, false, wrap_width); - return ToPyPair(size.x, size.y); - } - - auto afont = GetItem((*GContext->itemRegistry), font); - if (afont == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_text_size", - "Item not found: " + std::to_string(font), nullptr); - return nullptr; - } - - if (afont->type != mvAppItemType::mvFont) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_text_size", - "Incompatible type. Expected types include: mvFont", afont); - return nullptr; - } - - mvFont* graph = static_cast(afont); - - if (graph->_fontPtr) - { - ImGuiContext& g = *GImGui; - ImFont* previousFont = g.Font; - float previousFontSize = g.FontSize; - g.Font = graph->_fontPtr; - g.FontSize = graph->_size; - ImVec2 size = ImGui::CalcTextSize(text, 0, false, wrap_width); - g.Font = previousFont; - g.FontSize = previousFontSize; - return ToPyPair(size.x, size.y); - } - - return GetPyNone(); -} - -static PyObject* -get_selected_nodes(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* node_editor_raw; - - if (!Parse((GetParsers())["get_selected_nodes"], args, kwargs, __FUNCTION__, &node_editor_raw)) - return ToPyBool(false); - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID node_editor = GetIDFromPyObject(node_editor_raw); - - auto anode_editor = GetItem(*GContext->itemRegistry, node_editor); - if (anode_editor == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_selected_nodes", - "Item not found: " + std::to_string(node_editor), nullptr); - return nullptr; - } - - if (anode_editor->type != mvAppItemType::mvNodeEditor) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_selected_nodes", - "Incompatible type. Expected types include: mvNodeEditor", anode_editor); - return nullptr; - } - - mvNodeEditor* editor = static_cast(anode_editor); - - auto selected_nodes = editor->getSelectedNodes(); - - return ToPyList(selected_nodes); - -} - -static PyObject* -get_selected_links(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* node_editor_raw; - - if (!Parse((GetParsers())["get_selected_links"], args, kwargs, __FUNCTION__, &node_editor_raw)) - return ToPyBool(false); - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID node_editor = GetIDFromPyObject(node_editor_raw); - - auto anode_editor = GetItem(*GContext->itemRegistry, node_editor); - if (anode_editor == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_selected_links", - "Item not found: " + std::to_string(node_editor), nullptr); - return nullptr; - } - - if (anode_editor->type != mvAppItemType::mvNodeEditor) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_selected_links", - "Incompatible type. Expected types include: mvNodeEditor", anode_editor); - return nullptr; - } - - mvNodeEditor* editor = static_cast(anode_editor); - - auto selected_links = editor->getSelectedLinks(); - - return ToPyList(selected_links); -} - -static PyObject* -clear_selected_links(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* node_editor_raw; - - if (!Parse((GetParsers())["clear_selected_links"], args, kwargs, __FUNCTION__, &node_editor_raw)) - return ToPyBool(false); - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID node_editor = GetIDFromPyObject(node_editor_raw); - - auto anode_editor = GetItem(*GContext->itemRegistry, node_editor); - if (anode_editor == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "clear_selected_links", - "Item not found: " + std::to_string(node_editor), nullptr); - return nullptr; - } - - if (anode_editor->type != mvAppItemType::mvNodeEditor) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "clear_selected_links", - "Incompatible type. Expected types include: mvNodeEditor", anode_editor); - return nullptr; - } - - mvNodeEditor* editor = static_cast(anode_editor); - editor->clearLinks(); - - return GetPyNone(); - -} - -static PyObject* -clear_selected_nodes(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* node_editor_raw; - - if (!Parse((GetParsers())["clear_selected_nodes"], args, kwargs, __FUNCTION__, &node_editor_raw)) - return ToPyBool(false); - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID node_editor = GetIDFromPyObject(node_editor_raw); - - auto anode_editor = GetItem(*GContext->itemRegistry, node_editor); - if (anode_editor == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "clear_selected_nodes", - "Item not found: " + std::to_string(node_editor), nullptr); - return nullptr; - } - - if (anode_editor->type != mvAppItemType::mvNodeEditor) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "clear_selected_nodes", - "Incompatible type. Expected types include: mvNodeEditor", anode_editor); - return nullptr; - } - - mvNodeEditor* editor = static_cast(anode_editor); - editor->clearNodes(); - - return GetPyNone(); - -} - -static PyObject* -get_plot_query_rects(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* plotraw; - auto tag = "get_plot_query_rects"; - - if (!Parse((GetParsers())[tag], args, kwargs, __FUNCTION__, &plotraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID plot = GetIDFromPyObject(plotraw); - - auto aplot = GetItem(*GContext->itemRegistry, plot); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, tag, "Item not found: " + std::to_string(plot), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlot) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, tag, "Incompatible type. Expected types include: mvPlot", aplot); - return nullptr; - } - - mvPlot* graph = static_cast(aplot); - - auto rects = graph->configData.rects; - PyObject* result = PyTuple_New(rects.size()); - for (int i = 0; i < rects.size(); ++i) { - auto rectMin = rects[i].Min(); - auto rectMax = rects[i].Max(); - PyTuple_SetItem(result, i, Py_BuildValue("(dddd)", rectMin.x, rectMin.y, rectMax.x, rectMax.y)); - } - return result; -} - -static PyObject* -set_axis_ticks(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* plotraw; - PyObject* label_pairs; - - if (!Parse((GetParsers())["set_axis_ticks"], args, kwargs, __FUNCTION__, &plotraw, &label_pairs)) - return nullptr; - - auto mlabel_pairs = ToVectPairStringFloat(label_pairs); - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID plot = GetIDFromPyObject(plotraw); - - auto aplot = GetItem(*GContext->itemRegistry, plot); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_axis_ticks", - "Item not found: " + std::to_string(plot), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_axis_ticks", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - - std::vector labels; - std::vector locations; - - for (const auto& item : mlabel_pairs) - { - labels.emplace_back(item.first.c_str()); - locations.emplace_back((double)item.second); - } - - graph->configData.labels.clear(); - graph->configData.clabels.clear(); - graph->configData.labelLocations.clear(); - graph->configData.labels = labels; - graph->configData.labelLocations = locations; - - for (const auto& item : graph->configData.labels) - graph->configData.clabels.push_back(item.data()); - - return GetPyNone(); -} - -static PyObject* -set_axis_limits_constraints(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - float vmin; - float vmax; - auto tag = "set_axis_limits_constraints"; - - if (!Parse((GetParsers())[tag], args, kwargs, __FUNCTION__, &axisraw, &vmin, &vmax)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, tag, - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, tag, - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - graph->configData.setLimitsRange = true; - graph->configData.constraints_range = ImVec2(vmin, vmax); - return GetPyNone(); -} - -static PyObject* -reset_axis_limits_constraints(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - auto tag = "reset_axis_limits_constraints"; - - if (!Parse((GetParsers())[tag], args, kwargs, __FUNCTION__, &axisraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, tag, - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, tag, - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - graph->configData.setLimitsRange = false; - return GetPyNone(); -} - -static PyObject* -set_axis_zoom_constraints(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - float vmin; - float vmax; - auto tag = "set_axis_zoom_constraints"; - - if (!Parse((GetParsers())[tag], args, kwargs, __FUNCTION__, &axisraw, &vmin, &vmax)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, tag, - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, tag, - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - graph->configData.setZoomRange = true; - graph->configData.zoom_range = ImVec2(vmin, vmax); - return GetPyNone(); -} - - -static PyObject* -reset_axis_zoom_constraints(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - auto tag = "reset_axis_zoom_constraints"; - - if (!Parse((GetParsers())[tag], args, kwargs, __FUNCTION__, &axisraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, tag, - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, tag, - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - graph->configData.setZoomRange = false; - - return GetPyNone(); -} - -static PyObject* -set_axis_limits(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - float ymin; - float ymax; - - if (!Parse((GetParsers())["set_axis_limits"], args, kwargs, __FUNCTION__, &axisraw, &ymin, &ymax)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_axis_limits", - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_axis_limits", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - graph->configData.setLimits = true; - graph->configData.limits = ImVec2(ymin, ymax); - return GetPyNone(); -} - -static PyObject* -set_axis_limits_auto(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - - if (!Parse((GetParsers())["set_axis_limits_auto"], args, kwargs, __FUNCTION__, &axisraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_axis_limits", - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_axis_limits", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - - graph->configData.setLimits = false; - - return GetPyNone(); -} - -static PyObject* -fit_axis_data(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* axisraw; - - if (!Parse((GetParsers())["fit_axis_data"], args, kwargs, __FUNCTION__, &axisraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID axis = GetIDFromPyObject(axisraw); - - auto aplot = GetItem(*GContext->itemRegistry, axis); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "fit_axis_data", - "Item not found: " + std::to_string(axis), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "fit_axis_data", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - - // fit axis data - static_cast(graph->info.parentPtr)->configData._fitDirty = true; - static_cast(graph->info.parentPtr)->configData._axisfitDirty[graph->configData.axis] = true; - - return GetPyNone(); -} - -static PyObject* -get_axis_limits(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* plotraw; - - if (!Parse((GetParsers())["get_axis_limits"], args, kwargs, __FUNCTION__, &plotraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID plot = GetIDFromPyObject(plotraw); - - auto aplot = GetItem(*GContext->itemRegistry, plot); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_axis_limits", - "Item not found: " + std::to_string(plot), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "get_axis_limits", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - - const ImVec2& lim = graph->configData.limits_actual; - return ToPyPair(lim.x, lim.y); -} - -static PyObject* -reset_axis_ticks(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* plotraw; - - if (!Parse((GetParsers())["reset_axis_ticks"], args, kwargs, __FUNCTION__, &plotraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID plot = GetIDFromPyObject(plotraw); - - auto aplot = GetItem(*GContext->itemRegistry, plot); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "reset_axis_ticks", - "Item not found: " + std::to_string(plot), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvPlotAxis) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "reset_axis_ticks", - "Incompatible type. Expected types include: mvPlotAxis", aplot); - return nullptr; - } - - mvPlotAxis* graph = static_cast(aplot); - - graph->configData.labels.clear(); - graph->configData.clabels.clear(); - graph->configData.labelLocations.clear(); - - return GetPyNone(); -} - -static PyObject* -highlight_table_column(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int column = 0; - PyObject* color; - - if (!Parse((GetParsers())["highlight_table_column"], args, kwargs, __FUNCTION__, &tableraw, &column, &color)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "highlight_table_column", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "highlight_table_column", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (column >= tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "highlight_table_column", - "Column out of range", tablecast); - return nullptr; - } - - mvColor finalColor = ToColor(color); - tablecast->_columnColorsSet[column] = true; - tablecast->_columnColors[column] = finalColor; - - return GetPyNone(); -} - -static PyObject* -unhighlight_table_column(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int column = 0; - - if (!Parse((GetParsers())["unhighlight_table_column"], args, kwargs, __FUNCTION__, &tableraw, &column)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "unhighlight_table_column", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "unhighlight_table_column", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (column >= tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "unhighlight_table_column", - "Column out of range", tablecast); - return nullptr; - } - - tablecast->_columnColorsSet[column] = false; - - return GetPyNone(); -} - -static PyObject* -set_table_row_color(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - PyObject* color; - - if (!Parse((GetParsers())["set_table_row_color"], args, kwargs, __FUNCTION__, &tableraw, &row, &color)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_table_row_color", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "set_table_row_color", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows) - { - mvThrowPythonError(mvErrorCode::mvNone, "set_table_row_color", - "Row out of range", tablecast); - return nullptr; - } - - mvColor finalColor = ToColor(color); - tablecast->_rowColorsSet[row] = finalColor.a >= 0.0f; - tablecast->_rowColors[row] = finalColor; - - return GetPyNone(); -} - -static PyObject* -unset_table_row_color(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - - if (!Parse((GetParsers())["unset_table_row_color"], args, kwargs, __FUNCTION__, &tableraw, &row)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "unset_table_row_color", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "unset_table_row_color", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows) - { - mvThrowPythonError(mvErrorCode::mvNone, "set_table_row_color", - "Row out of range", tablecast); - return nullptr; - } - - tablecast->_rowColorsSet[row] = false; - return GetPyNone(); -} - -static PyObject* -highlight_table_row(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - PyObject* color; - - if (!Parse((GetParsers())["highlight_table_row"], args, kwargs, __FUNCTION__, &tableraw, &row, &color)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "highlight_table_row", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "highlight_table_row", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows) - { - mvThrowPythonError(mvErrorCode::mvNone, "highlight_table_row", - "Row out of range", tablecast); - return nullptr; - } - - mvColor finalColor = ToColor(color); - tablecast->_rowSelectionColorsSet[row] = true; - tablecast->_rowSelectionColors[row] = finalColor; - - return GetPyNone(); -} - -static PyObject* -unhighlight_table_row(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - - if (!Parse((GetParsers())["unhighlight_table_row"], args, kwargs, __FUNCTION__, &tableraw, &row)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "unhighlight_table_row", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "unhighlight_table_row", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows) - { - mvThrowPythonError(mvErrorCode::mvNone, "unselect_table_row", - "Row out of range", tablecast); - return nullptr; - } - - tablecast->_rowSelectionColorsSet[row] = false; - - return GetPyNone(); -} - -static PyObject* -highlight_table_cell(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - int column = 0; - PyObject* color; - - if (!Parse((GetParsers())["highlight_table_cell"], args, kwargs, __FUNCTION__, &tableraw, &row, &column, &color)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "highlight_table_cell", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "highlight_table_cell", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows || column > tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "highlight_table_cell", - "Row/Column out of range", tablecast); - return nullptr; - } - - mvColor finalColor = ToColor(color); - tablecast->_cellColorsSet[row][column] = true; - tablecast->_cellColors[row][column] = finalColor; - - return GetPyNone(); -} - -static PyObject* -unhighlight_table_cell(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - int column = 0; - - if (!Parse((GetParsers())["unhighlight_table_cell"], args, kwargs, __FUNCTION__, &tableraw, &row, &column)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "unhighlight_table_cell", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "unhighlight_table_cell", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows || column > tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "unhighlight_table_cell", - "Row/Column out of range", tablecast); - return nullptr; - } - - tablecast->_cellColorsSet[row][column] = false; - - return GetPyNone(); -} - -static PyObject* -is_table_cell_highlighted(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - int column = 0; - - if (!Parse((GetParsers())["is_table_cell_highlighted"], args, kwargs, __FUNCTION__, &tableraw, &row, &column)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "is_table_cell_highlighted", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "is_table_cell_highlighted", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows || column > tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "is_table_cell_highlighted", - "Row/Column out of range", tablecast); - return nullptr; - } - - if (tablecast->_cellColorsSet[row][column]) - return ToPyBool(true); - if (tablecast->_rowColorsSet[row]) - return ToPyBool(true); - if (tablecast->_columnColorsSet[column]) - return ToPyBool(true); - - return ToPyBool(false); -} - -static PyObject* -is_table_row_highlighted(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int row = 0; - - if (!Parse((GetParsers())["is_table_row_highlighted"], args, kwargs, __FUNCTION__, &tableraw, &row)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "is_table_row_highlighted", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "is_table_row_highlighted", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (row >= tablecast->_rows) - { - mvThrowPythonError(mvErrorCode::mvNone, "is_table_row_highlighted", - "Row out of range", tablecast); - return nullptr; - } - - return ToPyBool(tablecast->_rowSelectionColorsSet[row]); -} - -static PyObject* -is_table_column_highlighted(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* tableraw; - int column = 0; - - if (!Parse((GetParsers())["is_table_column_highlighted"], args, kwargs, __FUNCTION__, &tableraw, &column)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID table = GetIDFromPyObject(tableraw); - - auto atable = GetItem(*GContext->itemRegistry, table); - if (atable == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "is_table_column_highlighted", - "Item not found: " + std::to_string(table), nullptr); - return nullptr; - } - - if (atable->type != mvAppItemType::mvTable) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "is_table_column_highlighted", - "Incompatible type. Expected types include: mvTable", atable); - return nullptr; - } - - mvTable* tablecast = static_cast(atable); - - if (column >= tablecast->_columns) - { - mvThrowPythonError(mvErrorCode::mvNone, "is_table_column_highlighted", - "Column out of range", tablecast); - return nullptr; - } - - return ToPyBool(tablecast->_columnColorsSet[column]); -} - -static PyObject* -bind_theme(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["bind_theme"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (item == 0) - { - GContext->resetTheme = true; - ResetTheme((*GContext->itemRegistry)); - return GetPyNone(); - } - - auto aplot = GetItem((*GContext->itemRegistry), item); - if (aplot == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_theme", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - if (aplot->type != mvAppItemType::mvTheme) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "bind_theme", - "Incompatible type. Expected types include: mvTheme", aplot); - return nullptr; - } - - mvTheme* graph = static_cast(aplot); - - ResetTheme(*GContext->itemRegistry); - - graph->config.show = true; - - return GetPyNone(); -} - -static PyObject* -set_global_font_scale(PyObject* self, PyObject* args, PyObject* kwargs) -{ - float scale; - - if (!Parse((GetParsers())["set_global_font_scale"], args, kwargs, __FUNCTION__, &scale)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - mvToolManager::GetFontManager().setGlobalFontScale(scale); - - return GetPyNone(); -} - -static PyObject* -get_global_font_scale(PyObject* self, PyObject* args, PyObject* kwargs) -{ - return ToPyFloat(mvToolManager::GetFontManager().getGlobalFontScale()); -} - -static PyObject* -show_tool(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* toolraw; - - if (!Parse((GetParsers())["show_tool"], args, kwargs, __FUNCTION__, - &toolraw)) - return nullptr; - - mvUUID tool = GetIDFromPyObject(toolraw); - - mvToolManager::ShowTool(tool); - - return GetPyNone(); -} - -/* -static PyObject* -set_decimal_point(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const unsigned int* point; - const bool* from_locale; - - if (!Parse((GetParsers())["set_decimal_point"], args, kwargs, __FUNCTION__, &point, &from_locale)) - return GetPyNone(); - - mvPySafeLockGuard lk(GContext->mutex); - - GContext->IO.decimalPoint = *point; - ImGui::GetIO().PlatformLocaleDecimalPoint = GContext->IO.decimalPoint; - return GetPyNone(); -} -*/ - -static PyObject* -set_frame_callback(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 frame = 0; - PyObject* callback; - PyObject* user_data=nullptr; - - if (!Parse((GetParsers())["set_frame_callback"], args, kwargs, __FUNCTION__, - &frame, &callback, &user_data)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - if (frame > GContext->callbackRegistry->highestFrame) - GContext->callbackRegistry->highestFrame = frame; - - GContext->callbackRegistry->frameCallbacks.insert_or_assign(frame, mvPyObject(callback, true)); - GContext->callbackRegistry->frameCallbacksUserData.insert_or_assign(frame, mvPyObject(user_data, true)); - - return GetPyNone(); -} - -static PyObject* -set_exit_callback(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* callback; - PyObject* user_data = nullptr; - - if (!Parse((GetParsers())["set_exit_callback"], args, kwargs, __FUNCTION__, &callback, - &user_data)) - return nullptr; - - *GContext->callbackRegistry->onCloseCallback = mvPyObject(callback == Py_None? nullptr : callback, true); - *GContext->callbackRegistry->onCloseCallbackUserData = mvPyObject(user_data, true); - - return GetPyNone(); -} - -static PyObject* -set_viewport_resize_callback(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* callback = nullptr; - PyObject* user_data = nullptr; - - if (!Parse((GetParsers())["set_viewport_resize_callback"], args, kwargs, __FUNCTION__, - &callback, &user_data)) - return nullptr; - - *GContext->callbackRegistry->resizeCallback = mvPyObject(callback == Py_None? nullptr : callback, true); - *GContext->callbackRegistry->resizeCallbackUserData = mvPyObject(user_data, true); - - return GetPyNone(); -} - -static PyObject* -get_viewport_configuration(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - - mvViewport* viewport = GContext->viewport; - if (!viewport) - { - mvThrowPythonError(mvErrorCode::mvNone, "No viewport created"); - return nullptr; - } - - PyObject* pdict = PyDict_New(); - - PyDict_SetItemString(pdict, "clear_color", mvPyObject(ToPyColor(viewport->clearColor))); - PyDict_SetItemString(pdict, "small_icon", mvPyObject(ToPyString(viewport->small_icon))); - PyDict_SetItemString(pdict, "large_icon", mvPyObject(ToPyString(viewport->large_icon))); - PyDict_SetItemString(pdict, "x_pos", mvPyObject(ToPyInt(viewport->xpos))); - PyDict_SetItemString(pdict, "y_pos", mvPyObject(ToPyInt(viewport->ypos))); - PyDict_SetItemString(pdict, "width", mvPyObject(ToPyInt(viewport->actualWidth))); - PyDict_SetItemString(pdict, "height", mvPyObject(ToPyInt(viewport->actualHeight))); - PyDict_SetItemString(pdict, "client_width", mvPyObject(ToPyInt(viewport->clientWidth))); - PyDict_SetItemString(pdict, "client_height", mvPyObject(ToPyInt(viewport->clientHeight))); - PyDict_SetItemString(pdict, "resizable", mvPyObject(ToPyBool(viewport->resizable))); - PyDict_SetItemString(pdict, "vsync", mvPyObject(ToPyBool(viewport->vsync))); - PyDict_SetItemString(pdict, "min_width", mvPyObject(ToPyInt(viewport->minwidth))); - PyDict_SetItemString(pdict, "max_width", mvPyObject(ToPyInt(viewport->maxwidth))); - PyDict_SetItemString(pdict, "min_height", mvPyObject(ToPyInt(viewport->minheight))); - PyDict_SetItemString(pdict, "max_height", mvPyObject(ToPyInt(viewport->maxheight))); - PyDict_SetItemString(pdict, "always_on_top", mvPyObject(ToPyBool(viewport->alwaysOnTop))); - PyDict_SetItemString(pdict, "decorated", mvPyObject(ToPyBool(viewport->decorated))); - PyDict_SetItemString(pdict, "title", mvPyObject(ToPyString(viewport->title))); - - return pdict; -} - -static PyObject* -is_viewport_ok(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - mvViewport* viewport = GContext->viewport; - if (viewport) - { - if (viewport->shown) - return ToPyBool(true); - } - - return ToPyBool(false); -} - -static PyObject* -create_viewport(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const char* title = "Dear PyGui"; - const char* small_icon = ""; - const char* large_icon = ""; - i32 width = 1280; - i32 height = 800; - i32 x_pos = 100; - i32 y_pos = 100; - i32 min_width = 250; - i32 max_width = 10000; - i32 min_height = 250; - i32 max_height = 10000; - - b32 resizable = true; - b32 vsync = true; - b32 always_on_top = false; - b32 decorated = true; - b32 disable_close = false; - - PyObject* color = PyList_New(4); - PyList_SetItem(color, 0, PyFloat_FromDouble(0.0)); - PyList_SetItem(color, 1, PyFloat_FromDouble(0.0)); - PyList_SetItem(color, 2, PyFloat_FromDouble(0.0)); - PyList_SetItem(color, 3, PyFloat_FromDouble(1.0)); - - - if (!Parse((GetParsers())["create_viewport"], args, kwargs, __FUNCTION__, - &title, &small_icon, &large_icon, &width, &height, &x_pos, &y_pos, &min_width, &max_width, &min_height, &max_height, - &resizable, &vsync, &always_on_top, &decorated, &color, &disable_close - )) - return nullptr; - - mvViewport* viewport = mvCreateViewport(); - if (PyObject* item = PyDict_GetItemString(kwargs, "clear_color")) viewport->clearColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "small_icon")) viewport->small_icon = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "large_icon")) viewport->large_icon = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "x_pos")) { viewport->posDirty = true; viewport->xpos = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "y_pos")) { viewport->posDirty = true; viewport->ypos = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "width")) { viewport->sizeDirty = true; viewport->actualWidth = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "height")) { viewport->sizeDirty = true; viewport->actualHeight = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "resizable")) { viewport->modesDirty = true; viewport->resizable = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "vsync")) viewport->vsync = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "min_width")) viewport->minwidth = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "max_width")) viewport->maxwidth = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "min_height")) viewport->minheight = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "max_height")) viewport->maxheight = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "always_on_top")) { viewport->modesDirty = true; viewport->alwaysOnTop = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "decorated")) { viewport->modesDirty = true; viewport->decorated = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "title")) { viewport->titleDirty = true; viewport->title = ToString(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "disable_close")) { viewport->modesDirty = true; viewport->disableClose = ToBool(item); } - - GContext->viewport = viewport; - - return GetPyNone(); -} - -static PyObject* -show_viewport(PyObject* self, PyObject* args, PyObject* kwargs) -{ - b32 minimized = false; - b32 maximized = false; - - if (!Parse((GetParsers())["show_viewport"], args, kwargs, __FUNCTION__, - &minimized, &maximized)) - return nullptr; - - mvViewport* viewport = GContext->viewport; - if (viewport) - { - mvShowViewport(*viewport, minimized, maximized); - GContext->graphics = setup_graphics(*viewport); - viewport->shown = true; - } - else - { - mvThrowPythonError(mvErrorCode::mvNone, "No viewport created"); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -configure_viewport(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - mvViewport* viewport = GContext->viewport; - if (viewport) - { - if (PyObject* item = PyDict_GetItemString(kwargs, "clear_color")) viewport->clearColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "small_icon")) viewport->small_icon = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "large_icon")) viewport->large_icon = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "x_pos")) { viewport->posDirty = true; viewport->xpos = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "y_pos")) { viewport->posDirty = true; viewport->ypos = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "width")) { viewport->sizeDirty = true; viewport->actualWidth = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "height")) { viewport->sizeDirty = true; viewport->actualHeight = ToInt(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "resizable")) { viewport->modesDirty = true; viewport->resizable = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "vsync")) viewport->vsync = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "min_width")) viewport->minwidth = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "max_width")) viewport->maxwidth = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "min_height")) viewport->minheight = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "max_height")) viewport->maxheight = ToInt(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "always_on_top")) { viewport->modesDirty = true; viewport->alwaysOnTop = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "decorated")) { viewport->modesDirty = true; viewport->decorated = ToBool(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "title")) { viewport->titleDirty = true; viewport->title = ToString(item); } - if (PyObject* item = PyDict_GetItemString(kwargs, "disable_close")) { viewport->modesDirty = true; viewport->disableClose = ToBool(item); } - - - } - else - { - mvThrowPythonError(mvErrorCode::mvNone, "No viewport created"); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -maximize_viewport(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - mvSubmitTask([=]() - { - mvMaximizeViewport(*GContext->viewport); - }); - - return GetPyNone(); -} - -static PyObject* -minimize_viewport(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - mvSubmitTask([=]() - { - mvMinimizeViewport(*GContext->viewport); - }); - - return GetPyNone(); -} - -static PyObject* -toggle_viewport_fullscreen(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - mvSubmitTask([=]() - { - mvToggleFullScreen(*GContext->viewport); - }); - - return GetPyNone(); -} - -static PyObject* -save_init_file(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const char* file; - - if (!Parse((GetParsers())["save_init_file"], args, kwargs, __FUNCTION__, &file)) - return nullptr; - - if (GContext->started) - ImGui::SaveIniSettingsToDisk(file); - else - { - mvThrowPythonError(mvErrorCode::mvNone, "Dear PyGui must be started to use \"save_init_file\"."); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -split_frame(PyObject* self, PyObject* args, PyObject* kwargs) -{ - if (!Parse((GetParsers())["split_frame"], args, kwargs, __FUNCTION__)) - return nullptr; - - if (GContext->running) - { - Py_BEGIN_ALLOW_THREADS; - std::unique_lock lk(GContext->frameEndedMutex); - GContext->frameEnded = false; - GContext->frameEndedEvent.wait(lk, []{return GContext->frameEnded;}); - lk.unlock(); - - Py_END_ALLOW_THREADS; - } - - // Now let's see if it was successful (there's a chance that DPG got stopped while we were waiting) - if (!GContext->running) - { - mvThrowPythonError(mvErrorCode::mvNone, "split_frame is exiting: there is no active rendering loop."); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -lock_mutex(PyObject* self, PyObject* args, PyObject* kwargs) -{ - // Since we may enter waiting state on mutex.lock(), we must release the - // GIL while attempting to lock the mutex; otherwise, we'd risk getting - // into a deadlock. - Py_BEGIN_ALLOW_THREADS; - GContext->mutex.lock(); - Py_END_ALLOW_THREADS; - - return GetPyNone(); -} - -static PyObject* -unlock_mutex(PyObject* self, PyObject* args, PyObject* kwargs) -{ - GContext->mutex.unlock(); - return GetPyNone(); -} - -static PyObject* -get_frame_count(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - return ToPyInt(GContext->frame); -} - -static PyObject* -load_image(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const char* file; - f32 gamma = 1.0f; - f32 gamma_scale = 1.0f; - - if (!Parse((GetParsers())["load_image"], args, kwargs, __FUNCTION__, - &file, &gamma, &gamma_scale)) - return nullptr; - - // Vout = (Vin / 255)^v; Where v = gamma - - if (stbi_is_hdr(file)) - { - stbi_hdr_to_ldr_gamma(gamma); - stbi_hdr_to_ldr_scale(gamma_scale); - } - else - { - stbi_ldr_to_hdr_gamma(gamma); - stbi_ldr_to_hdr_scale(gamma_scale); - } - - - // Load from disk into a raw RGBA buffer - i32 image_width = 0; - i32 image_height = 0; - - // automatic gamma correction - f32* image_data = stbi_loadf(file, &image_width, &image_height, NULL, 4); - if (image_data == NULL) - return GetPyNone(); - - PyObject* newbuffer = nullptr; - PymvBuffer* newbufferview = nullptr; - newbufferview = PyObject_New(PymvBuffer, &PymvBufferType); - newbufferview->arr.length = image_width * image_height * 4; - newbufferview->arr.data = (f32*)image_data; - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvBufferType); - - PyObject* result = PyTuple_New(4); - PyTuple_SetItem(result, 0, Py_BuildValue("i", image_width)); - PyTuple_SetItem(result, 1, Py_BuildValue("i", image_height)); - PyTuple_SetItem(result, 2, PyLong_FromLong(4)); - PyTuple_SetItem(result, 3, newbuffer); - - return result; -} - -/* returns 1 iff str ends with suffix */ -static int -str_ends_with(const char * str, const char * suffix) { - - /* note - it would be better to abort or return an error code here; see the comments */ - if( str == NULL || suffix == NULL ) - return 0; - - size_t str_len = strlen(str); - size_t suffix_len = strlen(suffix); - - if(suffix_len > str_len) - return 0; - - return 0 == strnicmp( str + str_len - suffix_len, suffix, suffix_len ); -} - -static PyObject* -save_image(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const char* file; - i32 width; - i32 height; - PyObject* data; - //i32 stride_in_bytes = 1; - i32 components = 4; - i32 quality = 50; - - if (!Parse((GetParsers())["save_image"], args, kwargs, __FUNCTION__, - &file, &width, &height, &data, &components, &quality)) - return nullptr; - - enum ImageType_ - { - MV_IMAGE_TYPE_INVALID_, - MV_IMAGE_TYPE_PNG_, - MV_IMAGE_TYPE_BMP_, - MV_IMAGE_TYPE_TGA_, - MV_IMAGE_TYPE_HDR_, - MV_IMAGE_TYPE_JPG_ - }; - - ImageType_ imageType = MV_IMAGE_TYPE_INVALID_; - size_t filepathLength = strlen(file); - - // most include atleast 4 chars ".png" - assert(filepathLength > 4 && "Invalid file for image"); - assert(components < 5 && components > 0); - assert(quality > 0 && quality < 101); - - // sanity checks - if (filepathLength < 5) - { - mvThrowPythonError(mvErrorCode::mvNone, "File path for 'save_image(...)' must be of the form 'name.png'."); - return nullptr; - } - - if (components > 4 || components < 1) - { - mvThrowPythonError(mvErrorCode::mvNone, "Component count for 'save_image(...)' must be between 1 and 4."); - return nullptr; - } - - if (quality < 1 || quality > 100) - { - mvThrowPythonError(mvErrorCode::mvNone, "Quality must be between 1 and 100."); - return nullptr; - } - - // TODO: support other formats - if (str_ends_with(file, ".png")) - { - imageType = MV_IMAGE_TYPE_PNG_; - } - else if (str_ends_with(file, ".bmp")) - { - imageType = MV_IMAGE_TYPE_BMP_; - } - else if (str_ends_with(file, ".tga")) - { - imageType = MV_IMAGE_TYPE_TGA_; - } - else if (str_ends_with(file, ".hdr")) - { - imageType = MV_IMAGE_TYPE_HDR_; - } - else if (str_ends_with(file, ".jpg")) - { - imageType = MV_IMAGE_TYPE_JPG_; - } - else - { - mvThrowPythonError(mvErrorCode::mvNone, "File path for 'save_image(...)' must be of the form 'name.png'."); - return nullptr; - } - - switch (imageType) - { - case MV_IMAGE_TYPE_PNG_: - { - std::vector convertedData = ToUCharVect(data); - int result = stbi_write_png(file, width, height, components, convertedData.data(), sizeof(unsigned char)*components*width); - break; - } - case MV_IMAGE_TYPE_BMP_: - { - std::vector convertedData = ToUCharVect(data); - int result = stbi_write_bmp(file, width, height, components, convertedData.data()); - break; - } - case MV_IMAGE_TYPE_TGA_: - { - std::vector convertedData = ToUCharVect(data); - int result = stbi_write_tga(file, width, height, components, convertedData.data()); - break; - } - case MV_IMAGE_TYPE_HDR_: - { - std::vector convertedData = ToFloatVect(data); - int result = stbi_write_hdr(file, width, height, components, convertedData.data()); - break; - } - case MV_IMAGE_TYPE_JPG_: - { - std::vector convertedData = ToUCharVect(data); - int result = stbi_write_jpg(file, width, height, components, convertedData.data(), quality); - break; - } - default: break; - } - - return GetPyNone(); -} - -static PyObject* -output_frame_buffer(PyObject* self, PyObject* args, PyObject* kwargs) -{ - const char* file = ""; - PyObject* callback = nullptr; - - if (!Parse((GetParsers())["output_frame_buffer"], args, kwargs, __FUNCTION__, - &file, &callback)) - return nullptr; - - - size_t filepathLength = strlen(file); - - if (filepathLength == 0 && callback) // not specified, return array instead - { - PyObject* newbuffer = nullptr; - PymvBuffer* newbufferview = PyObject_New(PymvBuffer, &PymvBufferType); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvBufferType); - - // Making an owned ref while we're still holding GIL (can't do this within mvSubmitTask). - auto stored_callback = std::make_shared(callback, true); - // We need to schedule this into the rendering thread because OutputFrameBufferArray - // accesses the rendering API, which might well have thread-local things in the context. - mvSubmitTask([stored_callback, newbuffer, newbufferview]() { - OutputFrameBufferArray(newbufferview); - mvAddOwnerlessCallback( - stored_callback, std::make_shared(nullptr), - 0, "", - // Note: the callback queue will DECREF the value returned by this - // lambda, effectively deleting `newbuffer` so that we don't need - // to perform any special cleanup. We just pass the value as it is, - // keeping a refcount of 1 all the time until the callback is done. - [=]() { return newbuffer; } - ); - }); - - return GetPyNone(); - } - - // most include atleast 4 chars ".png" - assert(filepathLength > 4 && "Invalid file for image"); - - // sanity checks - if (filepathLength < 5) - { - mvThrowPythonError(mvErrorCode::mvNone, "File path for 'output_frame_buffer(...)' must be of the form 'name.png'."); - return nullptr; - } - - // TODO: support other formats - if (str_ends_with(file, ".png")) - { - std::string fileStored = file; - mvSubmitTask([fileStored](){ - OutputFrameBuffer(fileStored.c_str()); - }); - - } - else - { - mvThrowPythonError(mvErrorCode::mvNone, "File path for 'output_frame_buffer(...)' must be of the form 'name.png'."); - return nullptr; - } - - return GetPyNone(); -} - - -static PyObject* -is_dearpygui_running(PyObject* self, PyObject* args, PyObject* kwargs) -{ - return ToPyBool(GContext->running); -} - -static PyObject* -setup_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - Py_BEGIN_ALLOW_THREADS; - std::lock_guard lk(GContext->mutex); - - - if (GContext->started) - { - mvThrowPythonError(mvErrorCode::mvNone, "Cannot call \"setup_dearpygui\" while a Dear PyGUI app is already running."); - return nullptr; - } - - // Clear the containers stack. Unfortunately std::stack doesn't have a clear() call, - // but assigning a new empty stack does just the same. - mvItemRegistry::threadContext.containers = {}; - GContext->started = true; - GContext->running = true; - GContext->future = std::async(std::launch::async, []() {return mvRunCallbacks(); }); - Py_END_ALLOW_THREADS; - return GetPyNone(); -} - -static PyObject* -render_dearpygui_frame(PyObject* self, PyObject* args, PyObject* kwargs) -{ - MV_PROFILE_SCOPE("Frame") - - Py_BEGIN_ALLOW_THREADS; - auto window = GContext->viewport; - mvRenderFrame(); - Py_END_ALLOW_THREADS; - - if (GContext->viewport->resized) - { - mvOnResize(); - GContext->viewport->resized = false; - } - - return GetPyNone(); -} - -static PyObject* -create_context(PyObject* self, PyObject* args, PyObject* kwargs) -{ - Py_BEGIN_ALLOW_THREADS; - - if (GContext) - { - assert(false); - } - else - { - GContext = new mvContext(); - - GContext->itemRegistry = new mvItemRegistry(); - GContext->callbackRegistry = new mvCallbackRegistry(); - - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImPlot::CreateContext(); - ImNodes::CreateContext(); - - // Configure some defaults that are common across platforms - ImGuiIO &io = ImGui::GetIO(); - io.ConfigErrorRecoveryEnableAssert = true; - // We disable the log by default so that if something goes awry and ImGui - // starts spitting an error every frame, the DebugLogBuf doesn't grow unlimited - // in production code. Logging can always be enabled via show_imgui_demo -> Configuration. - io.ConfigErrorRecoveryEnableDebugLog = false; - io.ConfigErrorRecoveryEnableTooltip = false; - } - - Py_END_ALLOW_THREADS; - return GetPyNone(); -} - -static PyObject* -destroy_context(PyObject* self, PyObject* args, PyObject* kwargs) -{ - if (GContext == nullptr) - { - assert(false); - } - - else - { - // Make sure everyone knows we're shutting down, even if stop_dearpygui - // was not called. This also releases any waiting split_frame calls. - StopRendering(); - - Py_BEGIN_ALLOW_THREADS; - - // Queue the close callback, if any. The environment is still healthy enough - // for it to run, except that no more frames will be rendered with the current GContext. - mvAddOwnerlessCallback(GContext->callbackRegistry->onCloseCallback, GContext->callbackRegistry->onCloseCallbackUserData); - - // Shutting down the callback loop - this will run right after the close callback - mvSubmitCallback([]() { - GContext->callbackRegistry->running = false; - }, true); - // Waiting for it to complete all tasks and shut down - if (GContext->future.valid()) - GContext->future.get(); - - // The rest of cleanup must be done with GIL locked because it might lead - // to occasional DECREFs on Python objects (e.g. a callback or user_data). - Py_END_ALLOW_THREADS; - - mvContext* context_to_delete = nullptr; - { - // Even though the handlers thread is down, there's still a chance that - // the user calls DPG from another Python thread. We'd better lock the - // mutex while we're tinkering with all the global structures. - mvPySafeLockGuard lk(GContext->mutex); - - mvToolManager::Reset(); - ClearItemRegistry(*GContext->itemRegistry); - - ImNodes::DestroyContext(); - ImPlot::DestroyContext(); - ImGui::DestroyContext(); - - #define X(el) DearPyGui::GetClassThemeComponent(mvAppItemType::el) = nullptr; DearPyGui::GetDisabledClassThemeComponent(mvAppItemType::el) = nullptr; - MV_ITEM_TYPES - X(All) - #undef X - - if (GContext->viewport) - delete GContext->viewport; - - delete GContext->itemRegistry; - delete GContext->callbackRegistry; - context_to_delete = GContext; - GContext = nullptr; - } - delete context_to_delete; - } - - return GetPyNone(); -} - -static PyObject* -stop_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs) -{ - StopRendering(); - mvPySafeLockGuard lk(GContext->mutex); - auto viewport = GContext->viewport; - if (viewport) - viewport->running = false; - return GetPyNone(); -} - -static PyObject* -get_total_time(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - return ToPyFloat((f32)GContext->time); -} - -static PyObject* -get_delta_time(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - return ToPyFloat(GContext->deltaTime); - -} - -static PyObject* -get_frame_rate(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - return ToPyFloat((f32)GContext->framerate); - -} - -static PyObject* -generate_uuid(PyObject* self, PyObject* args, PyObject* kwargs) -{ - return ToPyUUID(GenerateUUID(), ""); -} - -static PyObject* -configure_app(PyObject* self, PyObject* args, PyObject* kwargs) -{ - if (kwargs == nullptr) - return GetPyNone(); - - if (VerifyKeywordArguments(GetParsers()["configure_app"], kwargs)) - return GetPyNone(); - - if (PyArg_ValidateKeywordArguments(kwargs) == 0) - { - assert(false); - mvThrowPythonError(mvErrorCode::mvNone, "Dictionary keywords must be strings"); - return nullptr; - } - - mvPySafeLockGuard lk(GContext->mutex); - - if (PyObject* item = PyDict_GetItemString(kwargs, "auto_device")) GContext->IO.info_auto_device = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "docking")) GContext->IO.docking = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "docking_space")) GContext->IO.dockingViewport = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "docking_shift_only")) GContext->IO.dockingShiftOnly = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "load_init_file")) - { - std::string load_init_file = ToString(item); - GContext->IO.iniFile = load_init_file; - GContext->IO.loadIniFile = true; - } - - if (PyObject* item = PyDict_GetItemString(kwargs, "allow_alias_overwrites")) GContext->IO.allowAliasOverwrites = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "manual_alias_management")) GContext->IO.manualAliasManagement = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "skip_keyword_args")) GContext->IO.skipKeywordArgs = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "skip_positional_args")) GContext->IO.skipPositionalArgs = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "skip_required_args")) GContext->IO.skipRequiredArgs = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "auto_save_init_file")) GContext->IO.autoSaveIniFile = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "wait_for_input")) GContext->IO.waitForInput = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "manual_callback_management")) GContext->IO.manualCallbacks = ToBool(item); - - if (PyObject* item = PyDict_GetItemString(kwargs, "init_file")) GContext->IO.iniFile = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "device_name")) GContext->IO.info_device_name = ToString(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "device")) GContext->IO.info_device = ToInt(item); - - if (PyObject* item = PyDict_GetItemString(kwargs, "keyboard_navigation")) GContext->IO.kbdNavigation = ToBool(item); - - ImGuiStyle& style = ImGui::GetStyle(); - if (PyObject* item = PyDict_GetItemString(kwargs, "anti_aliased_lines")) style.AntiAliasedLines = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "anti_aliased_lines_use_tex")) style.AntiAliasedLinesUseTex = ToBool(item); - if (PyObject* item = PyDict_GetItemString(kwargs, "anti_aliased_fill")) style.AntiAliasedFill = ToBool(item); - - if (PyObject* item = PyDict_GetItemString(kwargs, "win32_alt_enter_fullscreen")) GContext->IO.altEnterFullscreen = ToBool(item); - - return GetPyNone(); -} - -static PyObject* -get_app_configuration(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - PyObject* pdict = PyDict_New(); - PyDict_SetItemString(pdict, "auto_device", mvPyObject(ToPyBool(GContext->IO.info_auto_device))); - PyDict_SetItemString(pdict, "docking", mvPyObject(ToPyBool(GContext->IO.docking))); - PyDict_SetItemString(pdict, "docking_space", mvPyObject(ToPyBool(GContext->IO.docking))); - PyDict_SetItemString(pdict, "docking_shift_only", mvPyObject(ToPyBool(GContext->IO.dockingShiftOnly))); - PyDict_SetItemString(pdict, "load_init_file", mvPyObject(ToPyBool(GContext->IO.loadIniFile))); - PyDict_SetItemString(pdict, "version", mvPyObject(ToPyString(MV_SANDBOX_VERSION))); - PyDict_SetItemString(pdict, "major_version", mvPyObject(ToPyInt(MV_DPG_MAJOR_VERSION))); - PyDict_SetItemString(pdict, "minor_version", mvPyObject(ToPyInt(MV_DPG_MINOR_VERSION))); - PyDict_SetItemString(pdict, "init_file", mvPyObject(ToPyString(GContext->IO.iniFile))); - PyDict_SetItemString(pdict, "platform", mvPyObject(ToPyString(MV_PLATFORM))); - PyDict_SetItemString(pdict, "device", mvPyObject(ToPyInt(GContext->IO.info_device))); - PyDict_SetItemString(pdict, "device_name", mvPyObject(ToPyString(GContext->IO.info_device_name))); - PyDict_SetItemString(pdict, "allow_alias_overwrites", mvPyObject(ToPyBool(GContext->IO.allowAliasOverwrites))); - PyDict_SetItemString(pdict, "manual_alias_management", mvPyObject(ToPyBool(GContext->IO.manualAliasManagement))); - PyDict_SetItemString(pdict, "skip_keyword_args", mvPyObject(ToPyBool(GContext->IO.skipKeywordArgs))); - PyDict_SetItemString(pdict, "skip_positional_args", mvPyObject(ToPyBool(GContext->IO.skipPositionalArgs))); - PyDict_SetItemString(pdict, "skip_required_args", mvPyObject(ToPyBool(GContext->IO.skipRequiredArgs))); - PyDict_SetItemString(pdict, "auto_save_init_file", mvPyObject(ToPyBool(GContext->IO.autoSaveIniFile))); - PyDict_SetItemString(pdict, "wait_for_input", mvPyObject(ToPyBool(GContext->IO.waitForInput))); - PyDict_SetItemString(pdict, "manual_callback_management", mvPyObject(ToPyBool(GContext->IO.manualCallbacks))); - PyDict_SetItemString(pdict, "keyboard_navigation", mvPyObject(ToPyBool(GContext->IO.kbdNavigation))); - - ImGuiStyle& style = ImGui::GetStyle(); - PyDict_SetItemString(pdict, "anti_aliased_lines", mvPyObject(ToPyBool(style.AntiAliasedLines))); - PyDict_SetItemString(pdict, "anti_aliased_lines_use_tex", mvPyObject(ToPyBool(style.AntiAliasedLinesUseTex))); - PyDict_SetItemString(pdict, "anti_aliased_fill", mvPyObject(ToPyBool(style.AntiAliasedFill))); - - PyDict_SetItemString(pdict, "win32_alt_enter_fullscreen", mvPyObject(ToPyBool(GContext->IO.altEnterFullscreen))); - - return pdict; -} - -static PyObject* -get_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) -{ - b32 local = true; - - if (!Parse((GetParsers())["get_mouse_pos"], args, kwargs, __FUNCTION__, &local)) - return nullptr; - - auto pos = mvVec2(); - - if (local) - pos = { (f32)GContext->input.mousePos.x, (f32)GContext->input.mousePos.y }; - else - pos = { (f32)GContext->input.mouseGlobalPos.x, (f32)GContext->input.mouseGlobalPos.y }; - - return ToPyPair(pos.x, pos.y); -} - -static PyObject* -get_plot_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - if (!Parse((GetParsers())["get_plot_mouse_pos"], args, kwargs, __FUNCTION__)) - return nullptr; - - mvVec2 pos = { (f32)GContext->input.mousePlotPos.x, (f32)GContext->input.mousePlotPos.y }; - - return ToPyPair(pos.x, pos.y); -} - -static PyObject* -get_drawing_mouse_pos(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - if (!Parse((GetParsers())["get_drawing_mouse_pos"], args, kwargs, __FUNCTION__)) - return nullptr; - - mvVec2 pos = { (f32)GContext->input.mouseDrawingPos.x, (f32)GContext->input.mouseDrawingPos.y }; - - return ToPyPair(pos.x, pos.y); -} - -static PyObject* -get_mouse_drag_delta(PyObject* self, PyObject* arg, PyObject* kwargss) -{ - - mvVec2 pos = { (f32)GContext->input.mouseDragDelta.x, (f32)GContext->input.mouseDragDelta.y }; - return ToPyPair(pos.x, pos.y); -} - -static PyObject* -is_key_pressed(PyObject* self, PyObject* args, PyObject* kwargs) -{ - ImGuiKey key; - - if (!Parse((GetParsers())["is_key_pressed"], args, kwargs, __FUNCTION__, &key)) - return nullptr; - - return ToPyBool(ImGui::IsKeyPressed(key)); -} - -static PyObject* -is_key_released(PyObject* self, PyObject* args, PyObject* kwargs) -{ - ImGuiKey key; - - if (!Parse((GetParsers())["is_key_released"], args, kwargs, __FUNCTION__, &key)) - return nullptr; - - return ToPyBool(ImGui::IsKeyReleased(key)); -} - -static PyObject* -is_key_down(PyObject* self, PyObject* args, PyObject* kwargs) -{ - ImGuiKey key; - - if (!Parse((GetParsers())["is_key_down"], args, kwargs, __FUNCTION__, &key)) - return nullptr; - - return ToPyBool(ImGui::IsKeyDown(key)); -} - -static PyObject* -is_mouse_button_dragging(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 button; - f32 threshold; - - if (!Parse((GetParsers())["is_mouse_button_dragging"], args, kwargs, __FUNCTION__, &button, &threshold)) - return nullptr; - - // TODO: Can this be changed? - return ToPyBool((f32)ImGui::GetIO().MouseDownDuration[button] >= threshold); -} - -static PyObject* -is_mouse_button_down(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 button; - - if (!Parse((GetParsers())["is_mouse_button_down"], args, kwargs, __FUNCTION__, &button)) - return nullptr; - - return ToPyBool(ImGui::IsMouseDown(button)); -} - -static PyObject* -is_mouse_button_clicked(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 button; - - if (!Parse((GetParsers())["is_mouse_button_clicked"], args, kwargs, __FUNCTION__, &button)) - return nullptr; - - return ToPyBool(ImGui::IsMouseClicked(button)); -} - -static PyObject* -is_mouse_button_double_clicked(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 button; - - if (!Parse((GetParsers())["is_mouse_button_double_clicked"], args, kwargs, __FUNCTION__, &button)) - return nullptr; - - return ToPyBool(ImGui::IsMouseDoubleClicked(button)); -} - -static PyObject* -is_mouse_button_released(PyObject* self, PyObject* args, PyObject* kwargs) -{ - i32 button; - - if (!Parse((GetParsers())["is_mouse_button_released"], args, kwargs, __FUNCTION__, &button)) - return nullptr; - - return ToPyBool(ImGui::IsMouseReleased(button)); -} - -static PyObject* -pop_container_stack(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - auto& containers = mvItemRegistry::threadContext.containers; - if (containers.empty()) - { - mvThrowPythonError(mvErrorCode::mvContainerStackEmpty, "No container to pop."); - assert(false); - return nullptr; - } - - PyObject* top = ToPyUUIDOrNone(containers.top().get()); - containers.pop(); - - return top; - -} - -static PyObject* -empty_container_stack(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - // Clear the containers stack. Unfortunately std::stack doesn't have a clear() call, - // but assigning a new empty stack does just the same. - mvItemRegistry::threadContext.containers = {}; - return GetPyNone(); -} - -static PyObject* -top_container_stack(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - mvAppItem* item = nullptr; - auto& containers = mvItemRegistry::threadContext.containers; - if (!containers.empty()) - item = containers.top().get(); - - return ToPyUUIDOrNone(item); -} - -static PyObject* -last_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - return PyUUIDFromItem(mvItemRegistry::threadContext.lastItemAdded); -} - -static PyObject* -last_container(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - return PyUUIDFromItem(mvItemRegistry::threadContext.lastContainerAdded); -} - -static PyObject* -last_root(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - return PyUUIDFromItem(mvItemRegistry::threadContext.lastRootAdded); -} - -static PyObject* -push_container_stack(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["push_container_stack"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto parent = GetRefItem((*GContext->itemRegistry), item); - if (parent) - { - if (DearPyGui::GetEntityDesciptionFlags(parent->type) & MV_ITEM_DESC_CONTAINER) - { - mvItemRegistry::threadContext.containers.push(parent); - return ToPyBool(true); - } - } - return ToPyBool(false); -} - -static PyObject* -set_primary_window(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - i32 value = 1; - - if (!VerifyRequiredArguments(GetParsers()["set_primary_window"], args)) - return GetPyNoneOrError(); - - if (!Parse((GetParsers())["set_primary_window"], args, kwargs, __FUNCTION__, &itemraw, &value)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - mvWindowAppItem* window = GetWindow(*GContext->itemRegistry, item); - - if (!window) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_primary_window", - "Item not found: " + std::to_string(item), nullptr); - assert(false); - return nullptr; - } - - if (window->configData.mainWindow == (bool)value) - // Nothing to do! - return GetPyNone(); - - // Now, we either demote this (primary) window back to a regular window, or demote - // another window and set this one to be the new primary. The `value` shows us - // the direction. - mvWindowAppItem* old_primary = nullptr; - - if (value) - { - // Find old primary, if any. Also re-focus all windows except the current one - // so that they float atop of the primary window (otherwise they'd stay hidden - // behind it). Unfortunately ImGui does not have better means for controlling z-order. - for (auto& root : GContext->itemRegistry->windowRoots) - { - mvWindowAppItem* cur_window = static_cast(root.get()); - if (cur_window->configData.mainWindow) - old_primary = cur_window; - - cur_window->info.focusNextFrame = (cur_window->uuid != item); - } - - // Select the window passed in as a primary - window->configData.mainWindow = true; - window->configData._oldxpos = window->state.pos.x; - window->configData._oldypos = window->state.pos.y; - window->configData._oldWidth = window->config.width; - window->configData._oldHeight = window->config.height; - } - else - // Just demote this window, nothing special - old_primary = window; - - // Now whatever old primary was there (it might be the window passed in - - // if `value` is False), we want to make it a regular window. - if (old_primary) - { - old_primary->configData.mainWindow = false; - old_primary->state.pos = { old_primary->configData._oldxpos , old_primary->configData._oldypos }; - old_primary->config.width = old_primary->configData._oldWidth; - old_primary->config.height = old_primary->configData._oldHeight; - old_primary->info.dirtyPos = true; - old_primary->info.dirty_size = true; - } - - return GetPyNone(); -} - -static PyObject* -get_active_window(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - return PyUUIDFromItem(GContext->activeWindow); -} - -static PyObject* -get_focused_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - mvPySafeLockGuard lk(GContext->mutex); - - return PyUUIDFromItem(GContext->focusedItem); -} - -static PyObject* -move_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - PyObject* parentraw = nullptr; - PyObject* beforeraw = nullptr; - - if (!Parse((GetParsers())["move_item"], args, kwargs, __FUNCTION__, - &itemraw, &parentraw, &beforeraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID parent = GetIDFromPyObject(parentraw); - mvUUID before = GetIDFromPyObject(beforeraw); - - if (before == 0 && parent == 0) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item", - "move_item requires either `parent` or `before` to be specified.", nullptr); - return nullptr; - } - - if (!MoveItem((*GContext->itemRegistry), item, parent, before)) - return nullptr; - - return GetPyNone(); -} - -static PyObject* -delete_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - b32 childrenOnly = false; - i32 slot = -1; - - if (!Parse((GetParsers())["delete_item"], args, kwargs, __FUNCTION__, &itemraw, &childrenOnly, &slot)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if(item != 0) - DeleteItem((*GContext->itemRegistry), item, childrenOnly, slot); - - return GetPyNone(); - -} - -static PyObject* -does_item_exist(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["does_item_exist"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (GetItem((*GContext->itemRegistry), item)) - return ToPyBool(true); - return ToPyBool(false); -} - -static PyObject* -move_item_up(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["move_item_up"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (!MoveItemUp((*GContext->itemRegistry), item)) - return nullptr; - - return GetPyNone(); - -} - -static PyObject* -move_item_down(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw; - - if (!Parse((GetParsers())["move_item_down"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (!MoveItemDown((*GContext->itemRegistry), item)) - return nullptr; - - return GetPyNone(); -} - -static PyObject* -reorder_items(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* containerraw; - i32 slot = 0; - PyObject* new_order = nullptr; - - if (!Parse((GetParsers())["reorder_items"], args, kwargs, __FUNCTION__, - &containerraw, &slot, &new_order)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - auto anew_order = ToUUIDVect(new_order); - mvUUID container = GetIDFromPyObject(containerraw); - - if (!ReorderChildren(*GContext->itemRegistry, container, slot, anew_order)) - return nullptr; - - return GetPyNone(); -} - -static PyObject* -unstage(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw = nullptr; - - if (!Parse((GetParsers())["unstage"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - b8 item_found = false; - for (auto& aitem : GContext->itemRegistry->stagingRoots) - { - if (aitem->uuid == item && aitem->type == mvAppItemType::mvStage) - { - for (auto& children : aitem->childslots) - { - for (auto& child : children) - AddItemWithRuntimeChecks(*GContext->itemRegistry, child, 0, 0); - } - - item_found = true; - break; - } - } - - if (item_found) - return GetPyNone(); - - mvThrowPythonError(mvErrorCode::mvItemNotFound, "unstage", - "Stage not found: " + std::to_string(item), nullptr); - assert(false); - - return nullptr; -} - -static PyObject* -show_item_debug(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - PyObject* itemraw = nullptr; - - if (!Parse((GetParsers())["show_item_debug"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - auto actualItem = GetRefItem((*GContext->itemRegistry), item); - if (actualItem) - { - actualItem->info.showDebug = true; - GContext->itemRegistry->debugWindows.push_back(actualItem); - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "show_item_debug", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - return GetPyNone(); -} - -static void -GetAllItemsRoot(std::vector>& roots, std::vector& childList) -{ - // to help recursively retrieve children - std::function)> ChildRetriever; - ChildRetriever = [&childList, &ChildRetriever](std::shared_ptr item) { - auto& children0 = item->childslots[0]; - auto& children1 = item->childslots[1]; - auto& children2 = item->childslots[2]; - for (auto& child : children0) - { - childList.emplace_back(child->uuid); - if (DearPyGui::GetEntityDesciptionFlags(child->type) & MV_ITEM_DESC_CONTAINER) - ChildRetriever(child); - } - for (auto& child : children1) - { - childList.emplace_back(child->uuid); - if (DearPyGui::GetEntityDesciptionFlags(child->type) & MV_ITEM_DESC_CONTAINER) - ChildRetriever(child); - } - for (auto& child : children2) - { - if (child) - { - childList.emplace_back(child->uuid); - if (DearPyGui::GetEntityDesciptionFlags(child->type) & MV_ITEM_DESC_CONTAINER) - ChildRetriever(child); - } - } - - }; - - for (auto& root : roots) - { - childList.emplace_back(root->uuid); - ChildRetriever(root); - } -} - -static PyObject* -get_all_items(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - std::vector childList; - - GetAllItemsRoot(GContext->itemRegistry->colormapRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->filedialogRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->stagingRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->viewportMenubarRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->windowRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->fontRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->handlerRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->textureRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->valueRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->themeRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->itemTemplatesRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->itemHandlerRegistryRoots, childList); - GetAllItemsRoot(GContext->itemRegistry->viewportDrawlistRoots, childList); - - return ToPyList(childList); -} - -static PyObject* -show_imgui_demo(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - GContext->itemRegistry->showImGuiDebug = true; - return GetPyNone(); -} - -static PyObject* -show_implot_demo(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - GContext->itemRegistry->showImPlotDebug = true; - return GetPyNone(); -} - -static PyObject* -get_windows(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - std::vector childList; - for (auto& root : GContext->itemRegistry->colormapRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->filedialogRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->stagingRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->viewportMenubarRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->windowRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->fontRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->handlerRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->textureRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->valueRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->themeRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->itemTemplatesRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->itemHandlerRegistryRoots) childList.emplace_back(root->uuid); - for (auto& root : GContext->itemRegistry->viewportDrawlistRoots) childList.emplace_back(root->uuid); - - return ToPyList(childList); -} - -static PyObject* -add_alias(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* alias; - PyObject* itemraw; - - if (!Parse((GetParsers())["add_alias"], args, kwargs, __FUNCTION__, &alias, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - AddAlias((*GContext->itemRegistry), alias, item); - - return GetPyNone(); - -} - -static PyObject* -remove_alias(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* alias; - - if (!Parse((GetParsers())["remove_alias"], args, kwargs, __FUNCTION__, &alias)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - RemoveAlias((*GContext->itemRegistry), alias); - - return GetPyNone(); - -} - -static PyObject* -does_alias_exist(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* alias; - - if (!Parse((GetParsers())["does_alias_exist"], args, kwargs, __FUNCTION__, &alias)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - bool result = GContext->itemRegistry->aliases.count(alias) != 0; - - return ToPyBool(result); -} - -static PyObject* -get_alias_id(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* alias; - - if (!Parse((GetParsers())["get_alias_id"], args, kwargs, __FUNCTION__, &alias)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID result = GetIdFromAlias((*GContext->itemRegistry), alias); - - return ToPyUUID(result, ""); -} - -static PyObject* -get_aliases(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - std::vector aliases; - - for (const auto& alias : GContext->itemRegistry->aliases) - aliases.push_back(alias.first); - - return ToPyList(aliases); -} - -static PyObject* -focus_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["focus_item"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - - if (!GContext->started) - { - for (size_t i = 0; i < GContext->itemRegistry->windowRoots.size(); i++) - { - if (GContext->itemRegistry->windowRoots[i]->uuid == item) - { - std::shared_ptr oldItem = GContext->itemRegistry->windowRoots.back(); - GContext->itemRegistry->windowRoots[GContext->itemRegistry->windowRoots.size() - 1] = GContext->itemRegistry->windowRoots[i]; - GContext->itemRegistry->windowRoots[i] = oldItem; - break; - } - } - } - - mvAppItem* appitem = GetItem(*GContext->itemRegistry, item); - - if (appitem) - { - appitem->info.focusNextFrame = true; - if (auto parent = GetItemRoot(*GContext->itemRegistry, item)) - parent->info.focusNextFrame = true; - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "focus_item", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - return GetPyNone(); -} - -static std::vector> -GetItemChildren(mvItemRegistry& registry, mvUUID uuid) -{ - - mvAppItem* item = GetItem(registry, uuid); - - std::vector> childList; - - if (item) - { - for (auto& children : item->childslots) - { - std::vector childSlot; - for (auto& child : children) - { - if (child) - childSlot.emplace_back(child->uuid); - } - childList.push_back(childSlot); - } - - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_item_children", - "Item not found: " + std::to_string(uuid), nullptr); - assert(false && "Item not found."); - } - - return childList; -} - -static PyObject* -get_item_info(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["get_item_info"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - - if (!appitem) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_item_info", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - PyObject* pdict = PyDict_New(); - - std::string parserCommand = GetEntityCommand(appitem->type); - - auto children = GetItemChildren(*GContext->itemRegistry, appitem->uuid); - if (children.empty()) - PyDict_SetItemString(pdict, "children", mvPyObject(GetPyNone())); - else - { - PyObject* pyChildren = PyDict_New(); - i32 i = 0; - for (const auto& slot : children) - { - PyDict_SetItem(pyChildren, ToPyInt(i), mvPyObject(ToPyList(slot))); - i++; - } - PyDict_SetItemString(pdict, "children", mvPyObject(pyChildren)); - } - - PyDict_SetItemString(pdict, "type", mvPyObject(ToPyString(DearPyGui::GetEntityTypeString(appitem->type)))); - PyDict_SetItemString(pdict, "target", mvPyObject(ToPyInt(DearPyGui::GetEntityTargetSlot(appitem->type)))); - - PyDict_SetItemString(pdict, "parent", mvPyObject(ToPyUUIDOrNone(appitem->info.parentPtr))); - PyDict_SetItemString(pdict, "theme", mvPyObject(ToPyUUIDOrNone(appitem->theme.get()))); - PyDict_SetItemString(pdict, "font", mvPyObject(ToPyUUIDOrNone(appitem->font.get()))); - PyDict_SetItemString(pdict, "handlers", mvPyObject(ToPyUUIDOrNone(appitem->handlerRegistry.get()))); - - if (DearPyGui::GetEntityDesciptionFlags(appitem->type) & MV_ITEM_DESC_CONTAINER) - PyDict_SetItemString(pdict, "container", mvPyObject(ToPyBool(true))); - else - PyDict_SetItemString(pdict, "container", mvPyObject(ToPyBool(false))); - - i32 applicableState = DearPyGui::GetApplicableState(appitem->type); - PyDict_SetItemString(pdict, "hover_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_HOVER))); - PyDict_SetItemString(pdict, "active_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_ACTIVE))); - PyDict_SetItemString(pdict, "focus_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_FOCUSED))); - PyDict_SetItemString(pdict, "clicked_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_CLICKED))); - PyDict_SetItemString(pdict, "visible_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_VISIBLE))); - PyDict_SetItemString(pdict, "edited_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_EDITED))); - PyDict_SetItemString(pdict, "activated_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_ACTIVATED))); - PyDict_SetItemString(pdict, "deactivated_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_DEACTIVATED))); - PyDict_SetItemString(pdict, "deactivatedae_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_DEACTIVATEDAE))); - PyDict_SetItemString(pdict, "toggled_open_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_TOGGLED_OPEN))); - PyDict_SetItemString(pdict, "resized_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_RECT_SIZE))); - PyDict_SetItemString(pdict, "scroll_handler_applicable", mvPyObject(ToPyBool(applicableState & MV_STATE_SCROLL))); - - return pdict; -} - -static PyObject* -get_item_configuration(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["get_item_configuration"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (!appitem) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_item_configuration", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - PyObject* pdict = PyDict_New(); - - // config py objects - mvPyObject py_filter_key = ToPyString(appitem->config.filter); - mvPyObject py_payload_type = ToPyString(appitem->config.payloadType); - mvPyObject py_label = ToPyString(appitem->config.specifiedLabel); - mvPyObject py_use_internal_label = ToPyBool(appitem->config.useInternalLabel); - mvPyObject py_source = PyUUIDFromItem(appitem->config.source); - mvPyObject py_show = ToPyBool(appitem->config.show); - mvPyObject py_enabled = ToPyBool(appitem->config.enabled); - mvPyObject py_tracked = ToPyBool(appitem->config.tracked); - mvPyObject py_width = ToPyInt(appitem->config.width); - mvPyObject py_track_offset = ToPyFloat(appitem->config.trackOffset); - mvPyObject py_height = ToPyInt(appitem->config.height); - mvPyObject py_indent = ToPyInt((i32)appitem->config.indent); - - PyDict_SetItemString(pdict, "filter_key", py_filter_key); - PyDict_SetItemString(pdict, "payload_type", py_payload_type); - PyDict_SetItemString(pdict, "label", py_label); - PyDict_SetItemString(pdict, "use_internal_label", py_use_internal_label); - PyDict_SetItemString(pdict, "source", py_source); - PyDict_SetItemString(pdict, "show", py_show); - PyDict_SetItemString(pdict, "enabled", py_enabled); - PyDict_SetItemString(pdict, "tracked", py_tracked); - PyDict_SetItemString(pdict, "width", py_width); - PyDict_SetItemString(pdict, "track_offset", py_track_offset); - PyDict_SetItemString(pdict, "height", py_height); - PyDict_SetItemString(pdict, "indent", py_indent); - - PyObject* callback = appitem->config.callback; - PyDict_SetItemString(pdict, "callback", callback? callback : Py_None); - - PyObject* dropCallback = appitem->config.dropCallback; - PyDict_SetItemString(pdict, "drop_callback", dropCallback? dropCallback : Py_None); - - PyObject* dragCallback = appitem->config.dragCallback; - PyDict_SetItemString(pdict, "drag_callback", dragCallback? dragCallback : Py_None); - - PyObject* user_data = *(appitem->config.user_data); - PyDict_SetItemString(pdict, "user_data", user_data? user_data : Py_None); - - appitem->getSpecificConfiguration(pdict); - - return pdict; -} - -static PyObject* -set_item_children(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* sourceraw; - i32 slot; - - if (!Parse((GetParsers())["set_item_children"], args, kwargs, __FUNCTION__, - &itemraw, &sourceraw, &slot)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID source = GetIDFromPyObject(sourceraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - auto& staging = GContext->itemRegistry->stagingRoots; - - b8 stage_found = false; - std::shared_ptr staging_container = nullptr; - - for (auto& stage : staging) - { - if (stage->uuid == source) - { - staging_container = stage; - stage_found = true; - break; - } - } - - if (!stage_found) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_item_children", - "Stage item not found: " + std::to_string(item), nullptr); - assert(false); - return nullptr; - } - - - if (appitem) - { - auto& oldChildren = appitem->childslots[slot]; - oldChildren.reserve(staging_container->childslots[slot].size()); - oldChildren = std::move(staging_container->childslots[slot]); - for (auto& child : oldChildren) - { - child->config.parent = item; - child->info.parentPtr = appitem; - } - - // update locations - for (i32 i = 0; i < 4; i++) - { - i32 index = 0; - for (auto& child : appitem->childslots[i]) - { - child->info.location = index; - index++; - } - } - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_item_children", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - DeleteItem(*GContext->itemRegistry, source); - - return GetPyNone(); -} - -static PyObject* -bind_item_font(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* fontraw; - - if (!Parse((GetParsers())["bind_item_font"], args, kwargs, __FUNCTION__, - &itemraw, &fontraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID font = GetIDFromPyObject(fontraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - auto appfont = GetRefItem(*GContext->itemRegistry, font); - - if (appitem) - { - if (font == 0) - { - appitem->font = nullptr; - return GetPyNone(); - } - - if (appfont) - { - appitem->font = appfont; - return GetPyNone(); - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_font", - "Font item not found: " + std::to_string(item), nullptr); - } - } - else - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_font", - "Item not found: " + std::to_string(item), nullptr); - - return nullptr; -} - -static PyObject* -bind_item_theme(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* themeraw; - - if (!Parse((GetParsers())["bind_item_theme"], args, kwargs, __FUNCTION__, - &itemraw, &themeraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID theme = GetIDFromPyObject(themeraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (appitem) - { - if (theme == 0) - { - appitem->theme = nullptr; - return GetPyNone(); - } - - auto apptheme = GetRefItem(*GContext->itemRegistry, theme); - - if (apptheme) - { - if (apptheme->type == mvAppItemType::mvTheme) - { - appitem->theme = *(std::shared_ptr*)(&apptheme); - return GetPyNone(); - } - else - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "bind_item_theme", - "Item not a theme: " + std::to_string(theme), nullptr); - } - else - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_theme", - "Theme item not found: " + std::to_string(item), nullptr); - } - else - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_theme", - "Item not found: " + std::to_string(item), nullptr); - - return nullptr; -} - -static PyObject* -bind_item_handler_registry(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - PyObject* regraw; - - if (!Parse((GetParsers())["bind_item_handler_registry"], args, kwargs, __FUNCTION__, - &itemraw, ®raw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvUUID reg = GetIDFromPyObject(regraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (appitem) - { - if (reg == 0) - { - appitem->handlerRegistry = nullptr; - return GetPyNone(); - } - - auto handler_registry = GetRefItem(*GContext->itemRegistry, reg); - - if (handler_registry) - { - if (handler_registry->type == mvAppItemType::mvItemHandlerRegistry) - { - appitem->handlerRegistry = *(std::shared_ptr*)(&handler_registry); - appitem->handlerRegistry->onBind(appitem); - return GetPyNoneOrError(); - } - else - mvThrowPythonError(mvErrorCode::mvIncompatibleType, "bind_item_handler_registry", - "Item not handler registry: " + std::to_string(reg), nullptr); - } - else - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_handler_registry", - "Item Handler Registry not found: " + std::to_string(reg), nullptr); - } - else - mvThrowPythonError(mvErrorCode::mvItemNotFound, "bind_item_handler_registry", - "Item not found: " + std::to_string(item), nullptr); - - return nullptr; -} - -static PyObject* -reset_pos(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["reset_pos"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (appitem) - appitem->info.dirtyPos = false; - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "reset_pos", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_item_state(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["get_item_state"], args, kwargs, __FUNCTION__, &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (!appitem) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_item_state", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - PyObject* pdict = PyDict_New(); - FillAppItemState(pdict, appitem->state, DearPyGui::GetApplicableState(appitem->type)); - - return pdict; -} - -static PyObject* -get_item_types(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - PyObject* pdict = PyDict_New(); - #define X(el) PyDict_SetItemString(pdict, #el, mvPyObject(PyLong_FromLong((int)mvAppItemType::el))); - MV_ITEM_TYPES - #undef X - - return pdict; -} - -static PyObject* -configure_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(PyTuple_GetItem(args, 0)); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - - if (appitem) - { - //appitem->checkArgs(args, kwargs); - appitem->handleKeywordArgs(kwargs, GetEntityCommand(appitem->type)); - } - else - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "configure_item", - "Item not found: " + std::to_string(item), nullptr); - return nullptr; - } - - return GetPyNone(); -} - -static PyObject* -get_value(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* nameraw; - - if (!Parse((GetParsers())["get_value"], args, kwargs, __FUNCTION__, &nameraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID name = GetIDFromPyObject(nameraw); - mvAppItem* item = GetItem(*GContext->itemRegistry, name); - if (item) - return item->getPyValue(); - - return GetPyNone(); -} - -static PyObject* -get_values(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* items; - - if (!Parse((GetParsers())["get_values"], args, kwargs, __FUNCTION__, &items)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - auto aitems = ToUUIDVect(items); - PyObject* pyvalues = PyList_New(aitems.size()); - - for (size_t i = 0; i < aitems.size(); i++) - { - auto item = GetItem(*GContext->itemRegistry, aitems[i]); - if (item) - PyList_SetItem(pyvalues, i, item->getPyValue()); - else - { - // TODO: decide whether we want to raise an exception or return None's. - // These two variants are mutually exclusive. If we raise an exception, - // we must return nullptr, not pyvalues. - mvThrowPythonError(mvErrorCode::mvItemNotFound, "get_values", - "Item not found: " + std::to_string(aitems[i]), nullptr); - PyList_SetItem(pyvalues, i, GetPyNone()); - } - } - - return pyvalues; -} - -static PyObject* -set_value(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* nameraw; - PyObject* value; - - if (!Parse((GetParsers())["set_value"], args, kwargs, __FUNCTION__, &nameraw, &value)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID name = GetIDFromPyObject(nameraw); - - mvAppItem* item = GetItem(*GContext->itemRegistry, name); - if (!item) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_value", - "Item not found: " + std::to_string(name), nullptr); - return nullptr; - } - - Py_XINCREF(value); - item->setPyValue(value); - Py_XDECREF(value); - - return GetPyNone(); -} - -static PyObject* -set_item_alias(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - const char* alias; - - if (!Parse((GetParsers())["set_item_alias"], args, kwargs, __FUNCTION__, - &itemraw, &alias)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - if (appitem) - appitem->config.alias = alias; - return GetPyNone(); -} - -static PyObject* -get_item_alias(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* itemraw; - - if (!Parse((GetParsers())["get_item_alias"], args, kwargs, __FUNCTION__, - &itemraw)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvUUID item = GetIDFromPyObject(itemraw); - mvAppItem* appitem = GetItem((*GContext->itemRegistry), item); - if (appitem) - return ToPyString(appitem->config.alias); - return GetPyNone(); -} - -static PyObject* -capture_next_item(PyObject* self, PyObject* args, PyObject* kwargs) -{ - PyObject* callable; - PyObject* user_data; - - if (!Parse((GetParsers())["capture_next_item"], args, kwargs, __FUNCTION__, - &callable, &user_data)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - mvItemRegistry::threadContext.captureCallback = mvPyObject(callable == Py_None? nullptr : callable, true); - mvItemRegistry::threadContext.captureCallbackUserData = mvPyObject(user_data, true); - - return GetPyNone(); -} - -static PyObject* -get_callback_queue(PyObject* self, PyObject* args, PyObject* kwargs) -{ - if (GContext->callbackRegistry->jobs.empty()) - return GetPyNone(); - - mvPySafeLockGuard lk(GContext->mutex); - - PyObject* pArgs = PyTuple_New(GContext->callbackRegistry->jobs.size()); - for (int i = 0; i < GContext->callbackRegistry->jobs.size(); i++) - { - PyObject* job = PyTuple_New(4); - const mvCallbackJob& cur_entry = GContext->callbackRegistry->jobs[i]; - - PyObject* callback; - if (cur_entry.ownerless_callback) - { - callback = *cur_entry.ownerless_callback; - Py_XINCREF(callback); - } - else - { - auto liveOwner = cur_entry.owner.lock(); - // If the owner of this entry is gone, we'll just set the callback to None. - // This lets us create the output list right away, without the need to collect - // valid callbacks first. Also, this mimicks the behavior of widgets without - // a `callback` set on them, which in the "manual" mode put null callbacks into - // the queue. It's mostly a debug/diagnostic mode anyway - captures everything. - callback = liveOwner? cur_entry.callback : nullptr; - // Must only be done while we own liveOwner. - Py_XINCREF(callback); - } - PyTuple_SetItem(job, 0, callback? callback : GetPyNone()); - - PyTuple_SetItem(job, 1, ToPyUUID(cur_entry.sender, cur_entry.alias)); - - // app_data_func() returns a new PyObject reference (passing ownership to us), - // therefore we don't need to INCREF it. - PyObject* app_data = cur_entry.app_data_func(); - PyTuple_SetItem(job, 2, app_data? app_data : GetPyNone()); - - PyObject* user_data = *cur_entry.user_data; - Py_XINCREF(user_data); - PyTuple_SetItem(job, 3, user_data? user_data : GetPyNone()); - - PyTuple_SetItem(pArgs, i, job); - } - - GContext->callbackRegistry->jobs.clear(); - return pArgs; -} - -static PyObject* -set_clipboard_text(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - const char* text; - - if (!Parse((GetParsers())["set_clipboard_text"], args, kwargs, __FUNCTION__, - &text)) - return nullptr; - - mvPySafeLockGuard lk(GContext->mutex); - - ImGui::SetClipboardText(text); - - return GetPyNone(); -} - -static PyObject* -get_clipboard_text(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - - const char* text = ImGui::GetClipboardText(); - - return ToPyString(text); -} - -static PyObject* -get_platform(PyObject* self, PyObject* args, PyObject* kwargs) -{ - - mvPySafeLockGuard lk(GContext->mutex); - -#ifdef _WIN32 - return ToPyInt(0L); -#elif __APPLE__ - return ToPyInt(1L); -#else - return ToPyInt(2L); -#endif -} \ No newline at end of file diff --git a/src/dearpygui_parsers.h b/src/dearpygui_parsers.h deleted file mode 100644 index d51c48604..000000000 --- a/src/dearpygui_parsers.h +++ /dev/null @@ -1,1984 +0,0 @@ -#include "mvFontManager.h" -#include "mvItemRegistry.h" -#include -#include -#include "mvToolManager.h" -#include "mvCustomTypes.h" -#include "mvPyUtils.h" -#include "mvViewport.h" -#include -#include "mvProfiler.h" - -static void -InsertParser_Block0(std::map& parsers) -{ - //----------------------------------------------------------------------------- - // callback registry - //----------------------------------------------------------------------------- - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "frame" }); - args.push_back({ mvPyDataType::Callable, "callback" }); - args.push_back({ mvPyDataType::Object, "user_data", mvArgType::KEYWORD_ARG, "None", "New in 1.3. Optional user data to send to the callback"}); - - mvPythonParserSetup setup; - setup.about = "Sets a callback to run on first frame."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_frame_callback", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Callable, "callback" }); - args.push_back({ mvPyDataType::Object, "user_data", mvArgType::KEYWORD_ARG, "None", "New in 1.3. Optional user data to send to the callback" }); - - mvPythonParserSetup setup; - setup.about = "Sets a callback to run on last frame."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_exit_callback", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Callable, "callback" }); - args.push_back({ mvPyDataType::Object, "user_data", mvArgType::KEYWORD_ARG, "None", "New in 1.3. Optional user data to send to the callback" }); - - mvPythonParserSetup setup; - setup.about = "Sets a callback to run on viewport resize."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_viewport_resize_callback", parser }); - } - - //----------------------------------------------------------------------------- - // themes - //----------------------------------------------------------------------------- - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "theme" }); - - mvPythonParserSetup setup; - setup.about = "Binds a global theme."; - setup.category = { "Themes" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "bind_theme", parser }); - } - - //----------------------------------------------------------------------------- - // tables - //----------------------------------------------------------------------------- - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "column" }); - args.push_back({ mvPyDataType::IntList, "color" }); - - mvPythonParserSetup setup; - setup.about = "Highlight specified table column."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "highlight_table_column", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "column" }); - - mvPythonParserSetup setup; - setup.about = "Unhighlight specified table column."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unhighlight_table_column", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - args.push_back({ mvPyDataType::IntList, "color" }); - - mvPythonParserSetup setup; - setup.about = "Set table row color."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_table_row_color", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - - mvPythonParserSetup setup; - setup.about = "Remove user set table row color."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unset_table_row_color", parser }); - } - - { - std::vector args; - args.reserve(4); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - args.push_back({ mvPyDataType::Integer, "column" }); - args.push_back({ mvPyDataType::IntList, "color" }); - - mvPythonParserSetup setup; - setup.about = "Highlight specified table cell."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "highlight_table_cell", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - args.push_back({ mvPyDataType::Integer, "column" }); - - mvPythonParserSetup setup; - setup.about = "Unhighlight specified table cell."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unhighlight_table_cell", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - args.push_back({ mvPyDataType::IntList, "color" }); - - mvPythonParserSetup setup; - setup.about = "Highlight specified table row."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "highlight_table_row", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - - mvPythonParserSetup setup; - setup.about = "Unhighlight specified table row."; - setup.category = { "Tables", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unhighlight_table_row", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "column" }); - - mvPythonParserSetup setup; - setup.about = "Checks if a table column is highlighted."; - setup.category = { "Tables", "App Item Operations" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_table_column_highlighted", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - - mvPythonParserSetup setup; - setup.about = "Checks if a table row is highlighted."; - setup.category = { "Tables", "App Item Operations" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_table_row_highlighted", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "table" }); - args.push_back({ mvPyDataType::Integer, "row" }); - args.push_back({ mvPyDataType::Integer, "column" }); - - mvPythonParserSetup setup; - setup.about = "Checks if a table cell is highlighted."; - setup.category = { "Tables", "App Item Operations" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_table_cell_highlighted", parser }); - } - - //----------------------------------------------------------------------------- - // plots - //----------------------------------------------------------------------------- - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "plot" }); - - mvPythonParserSetup setup; - setup.about = "Returns the query rects of the plot. Returns an array of array containing the top-left coordinates and bottom-right coordinates of the plot area."; - setup.category = { "Plotting", "App Item Operations" }; - setup.returnType = mvPyDataType::ListFloatList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_plot_query_rects", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Get the specified axis limits."; - setup.category = { "Plotting", "App Item Operations" }; - setup.returnType = mvPyDataType::FloatList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_axis_limits", parser }); - } - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "axis" }); - args.push_back({ mvPyDataType::Float, "vmin" }); - args.push_back({ mvPyDataType::Float, "vmax" }); - - mvPythonParserSetup setup; - setup.about = "Sets an axis' limits constraints so that users can't pan beyond a min or max value"; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_axis_limits_constraints", parser }); - } - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Remove an axis' limits constraints"; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "reset_axis_limits_constraints", parser }); - } - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "axis" }); - args.push_back({ mvPyDataType::Float, "vmin" }); - args.push_back({ mvPyDataType::Float, "vmax" }); - - mvPythonParserSetup setup; - setup.about = "Sets an axis' zoom constraints so that users can't zoom beyond a min or max value"; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_axis_zoom_constraints", parser }); - } - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Remove an axis' zoom constraints"; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "reset_axis_zoom_constraints", parser }); - } - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "axis" }); - args.push_back({ mvPyDataType::Float, "ymin" }); - args.push_back({ mvPyDataType::Float, "ymax" }); - - mvPythonParserSetup setup; - setup.about = "Sets limits on the axis for pan and zoom."; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_axis_limits", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Removes all limits on specified axis."; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_axis_limits_auto", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Sets the axis boundaries max/min in the data series currently on the plot."; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "fit_axis_data", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "axis" }); - - mvPythonParserSetup setup; - setup.about = "Removes the manually set axis ticks and applies the default axis ticks"; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "reset_axis_ticks", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "axis" }); - args.push_back({ mvPyDataType::Object, "label_pairs", mvArgType::REQUIRED_ARG, "...", "Tuples of label and value in the form '((label, axis_value), (label, axis_value), ...)'" }); - - mvPythonParserSetup setup; - setup.about = "Replaces axis ticks with 'label_pairs' argument."; - setup.category = { "Plotting", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_axis_ticks", parser }); - } - - //----------------------------------------------------------------------------- - // viewport - //----------------------------------------------------------------------------- - { - std::vector args; - args.reserve(16); - args.push_back({ mvPyDataType::String, "title", mvArgType::KEYWORD_ARG, "'Dear PyGui'", "Sets the title of the viewport." }); - args.push_back({ mvPyDataType::String, "small_icon", mvArgType::KEYWORD_ARG, "''", "Sets the small icon that is found in the viewport's decorator bar. Must be ***.ico on windows and either ***.ico or ***.png on mac." }); - args.push_back({ mvPyDataType::String, "large_icon", mvArgType::KEYWORD_ARG, "''", "Sets the large icon that is found in the task bar while the app is running. Must be ***.ico on windows and either ***.ico or ***.png on mac." }); - args.push_back({ mvPyDataType::Integer, "width", mvArgType::KEYWORD_ARG, "1280", "Sets the width of the drawable space on the viewport. Does not inclue the border." }); - args.push_back({ mvPyDataType::Integer, "height", mvArgType::KEYWORD_ARG, "800", "Sets the height of the drawable space on the viewport. Does not inclue the border or decorator bar." }); - args.push_back({ mvPyDataType::Integer, "x_pos", mvArgType::KEYWORD_ARG, "100", "Sets x position the viewport will be drawn in screen coordinates." }); - args.push_back({ mvPyDataType::Integer, "y_pos", mvArgType::KEYWORD_ARG, "100", "Sets y position the viewport will be drawn in screen coordinates." }); - args.push_back({ mvPyDataType::Integer, "min_width", mvArgType::KEYWORD_ARG, "250", "Applies a minimuim limit to the width of the viewport." }); - args.push_back({ mvPyDataType::Integer, "max_width", mvArgType::KEYWORD_ARG, "10000", "Applies a maximum limit to the width of the viewport." }); - args.push_back({ mvPyDataType::Integer, "min_height", mvArgType::KEYWORD_ARG, "250", "Applies a minimuim limit to the height of the viewport." }); - args.push_back({ mvPyDataType::Integer, "max_height", mvArgType::KEYWORD_ARG, "10000", "Applies a maximum limit to the height of the viewport." }); - args.push_back({ mvPyDataType::Bool, "resizable", mvArgType::KEYWORD_ARG, "True", "Enables and Disables user ability to resize the viewport." }); - args.push_back({ mvPyDataType::Bool, "vsync", mvArgType::KEYWORD_ARG, "True", "Enables and Disables the renderloop vsync limit. vsync frame value is set by refresh rate of display." }); - args.push_back({ mvPyDataType::Bool, "always_on_top", mvArgType::KEYWORD_ARG, "False", "Forces the viewport to always be drawn ontop of all other viewports." }); - args.push_back({ mvPyDataType::Bool, "decorated", mvArgType::KEYWORD_ARG, "True", "Enabled and disabled the decorator bar at the top of the viewport." }); - args.push_back({ mvPyDataType::FloatList, "clear_color", mvArgType::KEYWORD_ARG, "(0, 0, 0, 255)", "Sets the color of the back of the viewport." }); - args.push_back({ mvPyDataType::Bool, "disable_close", mvArgType::KEYWORD_ARG, "False", "Disables the viewport close button. can be used with set_exit_callback" }); - - mvPythonParserSetup setup; - setup.about = "Creates a viewport. Viewports are required."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "create_viewport", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Bool, "minimized", mvArgType::KEYWORD_ARG, "False", "Sets the state of the viewport to minimized" }); - args.push_back({ mvPyDataType::Bool, "maximized", mvArgType::KEYWORD_ARG, "False", "Sets the state of the viewport to maximized" }); - args.push_back({ mvPyDataType::UUID, "viewport", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - - mvPythonParserSetup setup; - setup.about = "Shows the main viewport."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "show_viewport", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Configures a viewport."; - setup.category = { "General" }; - setup.unspecifiedKwargs = true; - setup.internal = true; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "configure_viewport", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns a viewport's configuration."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_viewport_configuration", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Checks if a viewport has been created and shown."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_viewport_ok", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Maximizes the viewport."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "maximize_viewport", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Minimizes a viewport."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "minimize_viewport", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Toggle viewport fullscreen mode.."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "toggle_viewport_fullscreen", parser }); - } -} - -static void -InsertParser_Block1(std::map& parsers) -{ - //----------------------------------------------------------------------------- - // context - //----------------------------------------------------------------------------- - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns app configuration."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_app_configuration", parser }); - } - - { - std::vector args; - args.reserve(11); - args.push_back({ mvPyDataType::String, "load_init_file", mvArgType::KEYWORD_ARG, "''", "Load .ini file." }); - args.push_back({ mvPyDataType::Bool, "docking", mvArgType::KEYWORD_ARG, "False", "Enables docking support." }); - args.push_back({ mvPyDataType::Bool, "docking_space", mvArgType::KEYWORD_ARG, "False", "add explicit dockspace over viewport" }); - args.push_back({ mvPyDataType::Bool, "docking_shift_only", mvArgType::KEYWORD_ARG, "False", "When False, pressing Shift will disable docking feature, when True, pressing Shift will enable it." }); - args.push_back({ mvPyDataType::String, "init_file", mvArgType::KEYWORD_ARG, "''" }); - args.push_back({ mvPyDataType::Bool, "auto_save_init_file", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Integer, "device", mvArgType::KEYWORD_ARG, "-1", "Which display adapter to use. (-1 will use default)" }); - args.push_back({ mvPyDataType::Bool, "auto_device", mvArgType::KEYWORD_ARG, "False", "Let us pick the display adapter." }); - args.push_back({ mvPyDataType::Bool, "allow_alias_overwrites", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "manual_alias_management", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "skip_required_args", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "skip_positional_args", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "skip_keyword_args", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "wait_for_input", mvArgType::KEYWORD_ARG, "False", "New in 1.1. Only update when user input occurs" }); - args.push_back({ mvPyDataType::Bool, "manual_callback_management", mvArgType::KEYWORD_ARG, "False", "New in 1.2"}); - args.push_back({ mvPyDataType::Bool, "keyboard_navigation", mvArgType::KEYWORD_ARG, "False", "Keyboard navigation using arrow keys" }); - args.push_back({ mvPyDataType::Bool, "anti_aliased_lines", mvArgType::KEYWORD_ARG, "False", "Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame." }); - args.push_back({ mvPyDataType::Bool, "anti_aliased_lines_use_tex", mvArgType::KEYWORD_ARG, "False", "Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame." }); - args.push_back({ mvPyDataType::Bool, "anti_aliased_fill", mvArgType::KEYWORD_ARG, "False", "Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame." }); - args.push_back({ mvPyDataType::Bool, "win32_alt_enter_fullscreen", mvArgType::KEYWORD_ARG, "False", "Windows only: configures Alt+Enter as a fullscreen hotkey." }); - - mvPythonParserSetup setup; - setup.about = "Configures app."; - setup.category = { "General" }; - setup.unspecifiedKwargs = true; - setup.internal = true; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "configure_app", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::String, "file" }); - - mvPythonParserSetup setup; - setup.about = "Save dpg.ini file."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "save_init_file", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "delay", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "32", "Do not use it anymore, it has no effect." }); - - mvPythonParserSetup setup; - setup.about = "Waits one frame."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "split_frame", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns frame count."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Integer; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_frame_count", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::String, "file" }); - args.push_back({ mvPyDataType::Float, "gamma", mvArgType::KEYWORD_ARG, "1.0", "Gamma correction factor. (default is 1.0 to avoid automatic gamma correction on loading." }); - args.push_back({ mvPyDataType::Float, "gamma_scale_factor", mvArgType::KEYWORD_ARG, "1.0", "Gamma scale factor." }); - - mvPythonParserSetup setup; - setup.about = "Loads an image. Returns width, height, channels, mvBuffer"; - setup.category = { "Textures", "Utilities" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "load_image", parser }); - } - - { - std::vector args; - args.reserve(5); - args.push_back({ mvPyDataType::String, "file" }); - args.push_back({ mvPyDataType::Integer, "width" }); - args.push_back({ mvPyDataType::Integer, "height" }); - args.push_back({ mvPyDataType::Object, "data" }); - args.push_back({ mvPyDataType::Integer, "components", mvArgType::KEYWORD_ARG, "4", "Number of components (1-4). Default of 4."}); - //args.push_back({ mvPyDataType::Integer, "stride_in_bytes", mvArgType::KEYWORD_ARG, "1.0", "Stride in bytes (only used for png)." }); - args.push_back({ mvPyDataType::Integer, "quality", mvArgType::KEYWORD_ARG, "50", "Stride in bytes (only used for jpg)." }); - - mvPythonParserSetup setup; - setup.about = "Saves an image. Possible formats: png, bmp, tga, hdr, jpg."; - setup.category = { "Textures", "Utilities" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "save_image", parser }); - } - - /* - // TODO: Implement this when it won't be broken anymore https://github.com/ocornut/imgui/issues/6719#issuecomment-1988531279 - // FIXME: https://github.com/hoffstadt/DearPyGui/pull/2275#discussion_r1542495486 - { - std::vector args; - args.reserve(1); - args.push_back({ mvPyDataType::String, "decimal_point" }); - args.push_back({ mvPyDataType::Bool, "from_locale", mvArgType::POSITIONAL_ARG, "False"}); // TODO: To be implemented set_decimal_point(locale.localeconv()["decimal_point"]) - - mvPythonParserSetup setup; - setup.about = "Change the default decimal_point. Use only single character strings."; - setup.category = { "Utilities" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_decimal_point", parser }); - } */ - - { - std::vector args; - args.reserve(1); - args.push_back({ mvPyDataType::String, "file", mvArgType::POSITIONAL_ARG, "''"}); - args.push_back({ mvPyDataType::Callable, "callback", mvArgType::KEYWORD_ARG, "None", "Callback will return framebuffer as an array through the second arg."}); - - mvPythonParserSetup setup; - setup.about = "Outputs frame buffer as a png if file is specified or through the second argument of a callback if specified. Render loop must have been started."; - setup.category = { "Textures", "Utilities" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "output_frame_buffer", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Generate a new UUID."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "generate_uuid", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Locks render thread mutex."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "lock_mutex", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Unlocks render thread mutex"; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unlock_mutex", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Checks if Dear PyGui is running"; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_dearpygui_running", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Sets up Dear PyGui"; - setup.category = { "General" }; - - args.push_back({ mvPyDataType::UUID, "viewport", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "setup_dearpygui", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Render a single Dear PyGui frame."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "render_dearpygui_frame", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Destroys the Dear PyGui context."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "destroy_context", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Creates the Dear PyGui context."; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "create_context", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Stops Dear PyGui"; - setup.category = { "General" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "stop_dearpygui", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns total time since Dear PyGui has started."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Float; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_total_time", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns time since last frame."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Float; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_delta_time", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the average frame rate across 120 frames."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Float; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_frame_rate", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Bool, "local", mvArgType::KEYWORD_ARG, "True" }); - - mvPythonParserSetup setup; - setup.about = "Returns mouse position."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::IntList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_mouse_pos", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns mouse position in plot."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::IntList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_plot_mouse_pos", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns mouse position in drawing."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::IntList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_drawing_mouse_pos", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns mouse drag delta."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Float; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_mouse_drag_delta", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "button" }); - args.push_back({ mvPyDataType::Float, "threshold" }); - - mvPythonParserSetup setup; - setup.about = "Checks if mouse button is down and dragging."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_mouse_button_dragging", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "button" }); - - mvPythonParserSetup setup; - setup.about = "Checks if mouse button is down."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_mouse_button_down", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "button" }); - - mvPythonParserSetup setup; - setup.about = "Checks if mouse button is clicked."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_mouse_button_clicked", parser }); - } - - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "button" }); - - mvPythonParserSetup setup; - setup.about = "Checks if mouse button is released."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_mouse_button_released", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "button" }); - - mvPythonParserSetup setup; - setup.about = "Checks if mouse button is double clicked."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_mouse_button_double_clicked", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "key" }); - - mvPythonParserSetup setup; - setup.about = "Checks if key is pressed."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_key_pressed", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "key" }); - - mvPythonParserSetup setup; - setup.about = "Checks if key is released."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_key_released", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Integer, "key" }); - - mvPythonParserSetup setup; - setup.about = "Checks if key is down."; - setup.category = { "Input Polling" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "is_key_down", parser }); - } -} - -static void -InsertParser_Block2(std::map& parsers) -{ - { - std::vector args; - args.push_back({ mvPyDataType::String, "alias" }); - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Adds an alias."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "add_alias", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::Callable, "callback" }); - args.push_back({ mvPyDataType::Object, "user_data", mvArgType::KEYWORD_ARG, "None", "New in 1.3. Optional user data to send to the callback" }); - - mvPythonParserSetup setup; - setup.about = "Captures the next item."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "capture_next_item", parser }); - } - - - { - std::vector args; - args.push_back({ mvPyDataType::String, "alias" }); - - mvPythonParserSetup setup; - setup.about = "Removes an alias."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "remove_alias", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::String, "alias" }); - - mvPythonParserSetup setup; - setup.about = "Checks if an alias exist."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "does_alias_exist", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::String, "alias" }); - - mvPythonParserSetup setup; - setup.about = "Returns the ID associated with an alias."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_alias_id", parser }); - } - - { - - mvPythonParserSetup setup; - setup.about = "Pops the top item off the parent stack and return its ID."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, {}); - parsers.insert({ "pop_container_stack", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Shows the imgui demo."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "show_imgui_demo", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Shows the implot demo."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "show_implot_demo", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "container" }); - args.push_back({ mvPyDataType::Integer, "slot" }); - args.push_back({ mvPyDataType::UUIDList, "new_order" }); - - mvPythonParserSetup setup; - setup.about = "Reorders an item's children."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "reorder_items", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Unstages an item."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "unstage", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Shows an item's debug window"; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "show_item_debug", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Pushes an item onto the container stack."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "push_container_stack", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the item on the top of the container stack."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "top_container_stack", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the last item added."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "last_item", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the last container item added."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "last_container", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the last root added (registry or window)."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "last_root", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Emptyes the container stack."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "empty_container_stack", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::UUID, "before", mvArgType::KEYWORD_ARG, "0" }); - - mvPythonParserSetup setup; - setup.about = "Moves an item to a new location."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "move_item", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns all windows."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUIDList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_windows", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns all items."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUIDList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_all_items", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns all aliases."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::StringList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_aliases", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::Bool, "children_only", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Integer, "slot", mvArgType::KEYWORD_ARG, "-1" }); - - mvPythonParserSetup setup; - setup.about = "Deletes an item.."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "delete_item", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Checks if an item exist.."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::Bool; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "does_item_exist", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Moves an item up."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "move_item_up", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Moves an item down."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "move_item_down", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the active window."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_active_window", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "Returns the item currently having focus."; - setup.category = { "Item Registry" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_focused_item", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "window" }); - args.push_back({ mvPyDataType::Bool, "value", mvArgType::POSITIONAL_ARG, "True", "True to select this window as primary, False to make it a regular window (without any primary window). Only one window at a time can be primary." }); - - mvPythonParserSetup setup; - setup.about = "Sets the primary window."; - setup.category = { "Item Registry" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_primary_window", parser }); - } -} - -static void -InsertParser_Block3(std::map& parsers) -{ - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Focuses an item."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "focus_item", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns an item's information."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_item_info", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns an item's configuration."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_item_configuration", parser }); - } - - { - - mvPythonParserSetup setup; - setup.about = "Returns an item types."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, {}); - parsers.insert({ "get_item_types", parser }); - } - - { - std::vector args; - args.reserve(3); - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::UUID, "source" }); - args.push_back({ mvPyDataType::Integer, "slot" }); - - mvPythonParserSetup setup; - setup.about = "Sets an item's children."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_item_children", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::UUID, "font" }); - - mvPythonParserSetup setup; - setup.about = "Sets an item's font."; - setup.category = { "Fonts", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "bind_item_font", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::String, "alias" }); - - mvPythonParserSetup setup; - setup.about = "Sets an item's alias."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_item_alias", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns an item's alias."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_item_alias", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::UUID, "handler_registry" }); - - mvPythonParserSetup setup; - setup.about = "Binds an item handler registry to an item."; - setup.category = { "App Item Operations", "Events" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "bind_item_handler_registry", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::UUID, "theme" }); - - mvPythonParserSetup setup; - setup.about = "Binds a theme to an item."; - setup.category = { "App Item Operations", "Themes" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "bind_item_theme", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns an item's state."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_item_state", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Configures an item."; - setup.category = { "App Item Operations" }; - setup.unspecifiedKwargs = true; - setup.internal = true; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "configure_item", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Returns an item's value."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Any; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_value", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUIDList, "items" }); - - mvPythonParserSetup setup; - setup.about = "Returns values of a list of items."; - setup.category = { "App Item Operations" }; - setup.returnType = mvPyDataType::Any; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_values", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::Object, "value" }); - - mvPythonParserSetup setup; - setup.about = "Set's an item's value."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_value", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - - mvPythonParserSetup setup; - setup.about = "Resets an item's position after using 'set_item_pos'."; - setup.category = { "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "reset_pos", parser }); - } -} - -static void -InsertParser_Block4(std::map& parsers) -{ - //----------------------------------------------------------------------------- - // node editor - //----------------------------------------------------------------------------- - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "node_editor" }); - - mvPythonParserSetup setup; - setup.about = "Returns a node editor's selected nodes."; - setup.category = { "Node Editor", "App Item Operations" }; - setup.returnType = mvPyDataType::UUIDList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_selected_nodes", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "node_editor" }); - - mvPythonParserSetup setup; - setup.about = "Returns a node editor's selected links."; - setup.category = { "Node Editor", "App Item Operations" }; - setup.returnType = mvPyDataType::ListStrList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_selected_links", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "node_editor" }); - - mvPythonParserSetup setup; - setup.about = "Clears a node editor's selected links."; - setup.category = { "Node Editor", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "clear_selected_links", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "node_editor" }); - - mvPythonParserSetup setup; - setup.about = "Clears a node editor's selected nodes."; - setup.category = { "Node Editor", "App Item Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "clear_selected_nodes", parser }); - } - - //----------------------------------------------------------------------------- - // fonts - //----------------------------------------------------------------------------- - { - std::vector args; - - args.push_back({ mvPyDataType::Float, "scale" }); - - mvPythonParserSetup setup; - setup.about = "Sets global font scale."; - setup.category = { "Fonts" }; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_global_font_scale", parser }); - } - - { - - mvPythonParserSetup setup; - setup.about = "Returns global font scale."; - setup.category = { "Fonts" }; - setup.returnType = mvPyDataType::Float; - mvPythonParser parser = FinalizeParser(setup, {}); - parsers.insert({ "get_global_font_scale", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "font" }); - - mvPythonParserSetup setup; - setup.about = "Binds a global font."; - setup.category = { "Fonts" }; - setup.returnType = mvPyDataType::UUID; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "bind_font", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::String, "text" }); - args.push_back({ mvPyDataType::Float, "wrap_width", mvArgType::KEYWORD_ARG, "-1.0", "Wrap width to use (-1.0 turns wrap off)." }); - args.push_back({ mvPyDataType::UUID, "font", mvArgType::KEYWORD_ARG, "0", "Font to use." }); - - mvPythonParserSetup setup; - setup.about = "Returns width/height of text with specified font (must occur after 1st frame)."; - setup.category = { "Fonts" }; - setup.returnType = mvPyDataType::FloatList; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_text_size", parser }); - } - - //----------------------------------------------------------------------------- - // drawings - //----------------------------------------------------------------------------- - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "item", mvArgType::REQUIRED_ARG, "", "draw layer to set clip space" }); - args.push_back({ mvPyDataType::Float, "top_left_x", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::Float, "top_left_y", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::Float, "width", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::Float, "height", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::Float, "min_depth", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::Float, "max_depth", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Set the clip space for depth clipping and 'viewport' transformation."; - setup.category = { "Drawlist", "Widgets" }; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "set_clip_space", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "item", mvArgType::REQUIRED_ARG, "", "Drawing node to apply transform to." }); - args.push_back({ mvPyDataType::Object, "transform", mvArgType::REQUIRED_ARG, "", "Transformation matrix." }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Applies a transformation matrix to a layer."; - setup.category = { "Drawlist", "Matrix Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "apply_transform", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::Float, "angle", mvArgType::REQUIRED_ARG, "", "angle to rotate" }); - args.push_back({ mvPyDataType::FloatList, "axis", mvArgType::REQUIRED_ARG, "", "axis to rotate around" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Applies a transformation matrix to a layer."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_rotation_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::FloatList, "scales", mvArgType::REQUIRED_ARG, "", "scale values per axis" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Applies a transformation matrix to a layer."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_scale_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::FloatList, "translation", mvArgType::REQUIRED_ARG, "", "translation vector" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Creates a translation matrix."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_translation_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::FloatList, "eye", mvArgType::REQUIRED_ARG, "", "eye position" }); - args.push_back({ mvPyDataType::FloatList, "target", mvArgType::REQUIRED_ARG, "", "target position" }); - args.push_back({ mvPyDataType::FloatList, "up", mvArgType::REQUIRED_ARG, "", "up vector" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Creates a 'Look at matrix'."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_lookat_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::Float, "fov", mvArgType::REQUIRED_ARG, "", "Field of view (in radians)" }); - args.push_back({ mvPyDataType::Float, "aspect", mvArgType::REQUIRED_ARG, "", "Aspect ratio (width/height)" }); - args.push_back({ mvPyDataType::Float, "zNear", mvArgType::REQUIRED_ARG, "", "Near clipping plane." }); - args.push_back({ mvPyDataType::Float, "zFar", mvArgType::REQUIRED_ARG, "", "Far clipping plane." }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Creates a perspective matrix."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_perspective_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::Float, "left", mvArgType::REQUIRED_ARG, "", "left plane" }); - args.push_back({ mvPyDataType::Float, "right", mvArgType::REQUIRED_ARG, "", "right plane" }); - args.push_back({ mvPyDataType::Float, "bottom", mvArgType::REQUIRED_ARG, "", "bottom plane" }); - args.push_back({ mvPyDataType::Float, "top", mvArgType::REQUIRED_ARG, "", "top plane" }); - args.push_back({ mvPyDataType::Float, "zNear", mvArgType::REQUIRED_ARG, "", "Near clipping plane." }); - args.push_back({ mvPyDataType::Float, "zFar", mvArgType::REQUIRED_ARG, "", "Far clipping plane." }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Creates an orthographic matrix."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_orthographic_matrix", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::FloatList, "eye", mvArgType::REQUIRED_ARG, "", "eye position" }); - args.push_back({ mvPyDataType::Float, "pitch", mvArgType::REQUIRED_ARG, "", "pitch (in radians)" }); - args.push_back({ mvPyDataType::Float, "yaw", mvArgType::REQUIRED_ARG, "", "yaw (in radians)" }); - - mvPythonParserSetup setup; - setup.about = "New in 1.1. Create a 'first person shooter' matrix."; - setup.category = { "Drawlist", "Matrix Operations" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "create_fps_matrix", parser }); - } - - //----------------------------------------------------------------------------- - // windows - //----------------------------------------------------------------------------- - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::Float, "value", mvArgType::REQUIRED_ARG, "", "Scroll position"}); - args.push_back({ mvPyDataType::Integer, "when", mvArgType::KEYWORD_ARG, "internal_dpg.mvSetScrollFlags_Delayed", - "Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with " - "a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better " - "if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used " - "to set the position twice." }); - - mvPythonParserSetup setup; - setup.about = "Sets horizontal scroll position."; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_x_scroll", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - args.push_back({ mvPyDataType::Float, "value", mvArgType::REQUIRED_ARG, "", "Scroll position"}); - args.push_back({ mvPyDataType::Integer, "when", mvArgType::KEYWORD_ARG, "internal_dpg.mvSetScrollFlags_Delayed", - "Specifies whether the scroll position will be set in the nearest frame (mvSetScrollFlags_Now) or with " - "a 1-frame delay (mvSetScrollFlags_Delayed). The former prevents flickering, the latter works better " - "if contents change in the same frame as when set_x_scroll called. mvSetScrollFlags_Both can also be used " - "to set the position twice." }); - - mvPythonParserSetup setup; - setup.about = "Sets vertical scroll position."; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_y_scroll", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID , "item" }); - mvPythonParserSetup setup; - setup.returnType = mvPyDataType::Float; - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_x_scroll", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - mvPythonParserSetup setup; - setup.returnType = mvPyDataType::Float; - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_y_scroll", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID , "item" }); - mvPythonParserSetup setup; - setup.returnType = mvPyDataType::Float; - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_x_scroll_max", parser }); - } - - { - std::vector args; - args.push_back({ mvPyDataType::UUID, "item" }); - mvPythonParserSetup setup; - setup.returnType = mvPyDataType::Float; - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_y_scroll_max", parser }); - } - - //----------------------------------------------------------------------------- - // file dialogs - //----------------------------------------------------------------------------- - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "file_dialog" }); - - mvPythonParserSetup setup; - setup.about = "Returns information related to the file dialog. Typically used while the file dialog is in use to query data about the state or info related to the file dialog."; - setup.category = { "Widgets", "File Dialog" }; - setup.returnType = mvPyDataType::Dict; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_file_dialog_info", parser }); - } - - //----------------------------------------------------------------------------- - // color maps - //----------------------------------------------------------------------------- - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "item", mvArgType::REQUIRED_ARG, "", "item that the color map will be applied to" }); - args.push_back({ mvPyDataType::UUID, "source", mvArgType::REQUIRED_ARG, "", "The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_***" }); - - mvPythonParserSetup setup; - setup.about = "Sets the color map for widgets that accept it."; - setup.category = { "Widget Operations" }; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "bind_colormap", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "colormap", mvArgType::REQUIRED_ARG, "", "The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_***" }); - args.push_back({ mvPyDataType::Float, "t", mvArgType::REQUIRED_ARG, "", "Value of the colormap to sample between 0.0-1.0" }); - - mvPythonParserSetup setup; - setup.about = "Returns a color from a colormap given t between 0.0-1.0."; - setup.category = { "Widget Operations" }; - setup.returnType = mvPyDataType::IntList; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "sample_colormap", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "colormap", mvArgType::REQUIRED_ARG, "", "The colormap tag. This should come from a colormap that was added to a colormap registry. Built in color maps are accessible through their corresponding constants mvPlotColormap_Twilight, mvPlotColormap_***" }); - args.push_back({ mvPyDataType::Integer, "index", mvArgType::REQUIRED_ARG, "", "Desired position of the color in the colors list value of the colormap being quiered " }); - - mvPythonParserSetup setup; - setup.about = "Returns a color from a colormap given an index >= 0. (ex. 0 will be the first color in the color list of the color map) Modulo will be performed against the number of items in the color list."; - setup.category = { "Widget Operations" }; - setup.returnType = mvPyDataType::IntList; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "get_colormap_color", parser }); - } - - { - std::vector args; - - args.push_back({ mvPyDataType::UUID, "tool" }); - - mvPythonParserSetup setup; - setup.about = "Shows a built in tool."; - setup.category = { "Widgets" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - - parsers.insert({ "show_tool", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "New in 1.2. Returns and clears callback queue."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Object; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_callback_queue", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "New in 1.3. Sets the clipboard text."; - setup.category = { "General" }; - - args.push_back({ mvPyDataType::String, "text" }); - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "set_clipboard_text", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "New in 1.3. Gets the clipboard text."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::String; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_clipboard_text", parser }); - } - - { - std::vector args; - - mvPythonParserSetup setup; - setup.about = "New in 1.6. Returns platform constant."; - setup.category = { "General" }; - setup.returnType = mvPyDataType::Integer; - - mvPythonParser parser = FinalizeParser(setup, args); - parsers.insert({ "get_platform", parser }); - } -} \ No newline at end of file diff --git a/src/distribution.cmake b/src/distribution.cmake deleted file mode 100644 index c94305365..000000000 --- a/src/distribution.cmake +++ /dev/null @@ -1,82 +0,0 @@ -cmake_minimum_required (VERSION 3.16) - -find_package (Python ${MV_PY_VERSION} EXACT COMPONENTS Development) -if(NOT Python_Development_FOUND) - message(FATAL_ERROR "The python3 development library from your distribution repo need to be installed first!") -endif() - -add_library(_dearpygui SHARED) - -set_target_properties(_dearpygui - PROPERTIES - CXX_STANDARD 17 - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/cmake-build-local/DearPyGui/" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/cmake-build-local/DearPyGui/" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/cmake-build-local/DearPyGui/" - ) - -target_sources(_dearpygui PRIVATE ${MARVEL_SOURCES}) - -target_include_directories(_dearpygui - PRIVATE - ${Python_INCLUDE_DIRS} - ${MARVEL_INCLUDE_DIR} - ) - -target_link_directories(_dearpygui - PRIVATE - "$<$:/usr/lib>" - ${Python_LIBRARY_DIRS} - ) - -target_compile_definitions(_dearpygui - - PRIVATE - $<$:MV_RELEASE> -) - -if(WIN32) - target_precompile_headers(_dearpygui - PRIVATE mvPyUtils.h - ) -endif() - -if(WIN32) - - set_target_properties(_dearpygui PROPERTIES SUFFIX ".pyd") - set_target_properties(_dearpygui PROPERTIES PREFIX "") - target_link_libraries(_dearpygui PUBLIC d3d11 dxgi dwmapi ${Python_LIBRARIES} freetype) - -elseif(APPLE) - - add_definitions(-DAPPLE) - set_target_properties(_dearpygui PROPERTIES SUFFIX ".so") - set_target_properties(_dearpygui PROPERTIES PREFIX "") - SET_PROPERTY(TARGET _dearpygui APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc -fno-common -dynamic -DNDEBUG -fwrapv -O3") - target_link_libraries(_dearpygui - - PRIVATE - glfw - "-undefined dynamic_lookup" - "-framework Metal" - "-framework MetalKit" - "-framework Cocoa" - "-framework CoreVideo" - "-framework IOKit" - "-framework QuartzCore" - ) -else() # Linux - - add_definitions(-DLINUX) - add_definitions(-DUNIX) - set_target_properties(_dearpygui PROPERTIES PREFIX "") - set_property(TARGET _dearpygui APPEND_STRING PROPERTY COMPILE_FLAGS "-fPIC -DNDEBUG -fwrapv -O3") - add_definitions(-DIMGUI_IMPL_OPENGL_LOADER_GL3W) - target_link_libraries(_dearpygui - PRIVATE - "-fPIC -lcrypt -lpthread -ldl -lutil -lm" - GL - glfw - ) - -endif() diff --git a/src/mvAboutWindow.cpp b/src/mvAboutWindow.cpp deleted file mode 100644 index 9e1f9953f..000000000 --- a/src/mvAboutWindow.cpp +++ /dev/null @@ -1,160 +0,0 @@ -#include "mvAboutWindow.h" - -#include "mvContext.h" - -static std::vector founders = -{ -"Anthony Tanbakuchi", -"Marco Studer", -"Wiebe Van der Waals", -"Anthony Doupe", -"Dean Keinan", -"He Lingfeng", -"Ray Heasman", -"Anthony Hernandez", -"Alexander G. Morano", -"Derek Barker", -"Caden Bloxham", -"Yan Zaretskiy", -"Barney Mannerings", -"Leron Gray", -"RB Blackstone", -"Charles Ray", -"Jonathan Matthysen", -"Keith Cuff", -"Emmanuel Aubert", -"Tollis Hunt", -"Torsten Rehn", -"Storm Coates", -"Arad F.", -"John S.", -"Jeremy Anderson", -"SafetyEagleEye", -"Jan Kolda", -"Alex Davies", -"Sepehr Ghavam", -"Rahul Ravikumar", -"Alex(Chr0my)", -"Trinnik", -"Michael Kadziela", -"George Auer", -"Dick Kluis", -"Nikki Luzader", -"Diego Dorn (CozyFractal)", -"Fabian Schneider", -"Rand Anderson", -"Johannes Kargl", -"Seth Weil", -"Harvey de Meester", -"Daniel Werbin", -"Praveen Kulkarni" -}; - -mvAboutWindow::mvAboutWindow() -{ - m_windowflags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings; -} - -void mvAboutWindow::drawWidgets() -{ - - ImGui::Text("Dear PyGui %s", MV_SANDBOX_VERSION); - ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); - ImGui::Separator(); - ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Authors"); - ImGui::BulletText("Jonathan Hoffstadt"); - ImGui::BulletText("Preston Cothren"); - ImGui::Text("Dear PyGui is licensed under the MIT License, see LICENSE for more information."); - ImGui::Separator(); - ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Founding Sponsors"); - ImGui::BeginChild("Founding Sponsors##aboutsponsorschild", ImVec2(0.0, 100.0f)); - - for (int i = 0; i < founders.size(); i++) - { - if (i % 2 == 0) - { - ImGui::TextColored(ImVec4(0.0f, 1.0f, (float)i / (float)founders.size(), 1.0f), "%s", founders[i].c_str()); - ImGui::SameLine(250.0f); - } - else - ImGui::TextColored(ImVec4((float)i / (float)founders.size(), 1.0f, 0.0f, 1.0f), "%s", founders[i].c_str()); - } - - ImGui::EndChild(); - ImGui::Separator(); - ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "ImPlot"); - ImGui::Text("ImPlot Author, Evan Pezent."); - ImGui::Separator(); - ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "imnodes"); - ImGui::Text("imnodes Author, Johann Muszynski."); - ImGui::Separator(); - ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Dear ImGui"); - ImGui::Text("Dear ImGui Author, Omar Cornut and all Dear ImGui contributors."); - ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); - - static bool show_config_info = false; - ImGui::Checkbox("Config/Build Information", &show_config_info); - if (show_config_info) - { - ImGuiIO& io = ImGui::GetIO(); - ImGuiStyle& style = ImGui::GetStyle(); - - bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); - ImGui::BeginChild(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiChildFlags_FrameStyle, ImGuiWindowFlags_NoMove); - if (copy_to_clipboard) - { - ImGui::LogToClipboard(); - ImGui::LogText("```\n"); // Back quotes will make the text appears without formatting when pasting to GitHub - } - - ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); - ImGui::Separator(); - ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert)); - ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); - ImGui::Text("define: _WIN32"); - ImGui::Text("define: _WIN64"); -#if defined (_WIN32) - ImGui::Text("define: _MSC_VER=%d", _MSC_VER); -#endif - ImGui::Separator(); - ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); - ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL"); - ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags); - if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard"); - if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad"); - if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse"); - if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange"); - if (io.ConfigNavMoveSetMousePos) ImGui::Text("io.ConfigNavMoveSetMousePos"); - if (io.ConfigNavCaptureKeyboard) ImGui::Text("io.ConfigNavCaptureKeyboard"); - if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); - if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); - if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); - if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); - if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); - ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); - if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); - if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); - if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); - if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); - ImGui::Separator(); - ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexData->Width, io.Fonts->TexData->Height); - ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); - ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); - ImGui::Separator(); - ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); - ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); - ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y); - ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding); - ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize); - ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y); - ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y); - - if (copy_to_clipboard) - { - ImGui::LogText("\n```\n"); - ImGui::LogFinish(); - } - ImGui::EndChild(); - } - -} diff --git a/src/mvAboutWindow.h b/src/mvAboutWindow.h deleted file mode 100644 index 6fe94b71c..000000000 --- a/src/mvAboutWindow.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "mvToolWindow.h" - -class mvAboutWindow final : public mvToolWindow -{ - -public: - - mvAboutWindow(); - - [[nodiscard]] mvUUID getUUID() const override { return MV_TOOL_ABOUT_UUID; } - [[nodiscard]] const char* getTitle() const override { return "About Dear PyGui"; } - -protected: - - void drawWidgets() override; - -}; \ No newline at end of file diff --git a/src/mvAppItem.cpp b/src/mvAppItem.cpp deleted file mode 100644 index 0445af410..000000000 --- a/src/mvAppItem.cpp +++ /dev/null @@ -1,5707 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvAppItem.h" - -#include "mvCore.h" -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "mvAppItemCommons.h" - -static void -UpdateLocations(std::vector>* children, i32 slots) -{ - for (i32 i = 0; i < slots; i++) - { - i32 index = 0; - for (auto& child : children[i]) - { - child->info.location = index; - index++; - } - } -} - -mvAppItem::mvAppItem(mvUUID uuid) -{ - this->uuid = uuid; - info.internalLabel = "###" + std::to_string(uuid); - state.parent = this; -} - -mvAppItem::~mvAppItem() -{ - for (auto& childset : childslots) - { - childset.clear(); - } - - if (type == mvAppItemType::mvTable) - static_cast(this)->onChildrenRemoved(); - - // in case item registry is destroyed - if (GContext->itemRegistry) - { - if (GContext->itemRegistry->aliases.count(config.alias) != 0) - { - if (!GContext->IO.manualAliasManagement) - GContext->itemRegistry->aliases.erase(config.alias); - } - GContext->itemRegistry->allItems.erase(uuid); - } -} - -void mvAppItem::submitCallback() -{ - submitCallbackEx([]() -> PyObject* { return nullptr; }); -} - -template<> -void mvAppItem::submitCallback(std::string app_data) -{ - submitCallbackEx([app_data=std::move(app_data)]() { return ToPyString(app_data); }); -} - -template<> -void mvAppItem::submitCallback(bool app_data) -{ - submitCallbackEx([=]() { return ToPyBool(app_data); }); -} - -template<> -void mvAppItem::submitCallback(float app_data) -{ - submitCallbackEx([=]() { return ToPyFloat(app_data); }); -} - -template<> -void mvAppItem::submitCallback(double app_data) -{ - submitCallbackEx([=]() { return ToPyDouble(app_data); }); -} - -template<> -void mvAppItem::submitCallback(int app_data) -{ - submitCallbackEx([=]() { return ToPyInt(app_data); }); -} - -template<> -void mvAppItem::submitCallback(std::array app_data) -{ - submitCallbackEx([app_data=std::move(app_data)]() { return ToPyIntList(app_data.data(), (int) app_data.size()); }); -} - -template<> -void mvAppItem::submitCallback(std::array app_data) -{ - submitCallbackEx([app_data=std::move(app_data)]() { return ToPyFloatList(app_data.data(), (int) app_data.size()); }); -} - -template<> -void mvAppItem::submitCallback(std::array app_data) -{ - submitCallbackEx([app_data=std::move(app_data)]() { return ToPyFloatList(app_data.data(), (int) app_data.size()); }); -} - -template<> -void mvAppItem::submitCallback(mvColor app_data) -{ - submitCallbackEx([=]() { return ToPyColor(app_data); }); -} - -template<> -void mvAppItem::submitCallback(mvAppItem* app_data) -{ - submitCallbackEx([=]() { return ToPyUUID(app_data); }); -} - -template<> -void mvAppItem::submitCallback(tm app_data) -{ - submitCallbackEx([=]() { return ToPyTime(app_data); }); -} - -template<> -void mvAppItem::submitCallback(ImVec2 app_data) -{ - submitCallbackEx([=]() { return ToPyPair(app_data.x, app_data.y); }); -} - -template<> -void mvAppItem::submitCallback(ImGuiKey app_data) -{ - submitCallbackEx([=]() { return ToPyInt(app_data); }); -} - -void -mvAppItem::handleKeywordArgs(PyObject* dict, const std::string& parser) -{ - if (dict == nullptr) - return; - - if (VerifyKeywordArguments(GetParsers()[parser], dict)) - return; - - if (PyArg_ValidateKeywordArguments(dict) == 0) - { - assert(false); - mvThrowPythonError(mvErrorCode::mvNone, "Dictionary keywords must be strings"); - return; - } - - if (PyObject* item = PyDict_GetItemString(dict, "use_internal_label")) config.useInternalLabel = ToBool(item); // must be before label - - if (PyObject* item = PyDict_GetItemString(dict, "label")) - { - if (item != Py_None) - { - const std::string label = ToString(item); - config.specifiedLabel = label; - if (config.useInternalLabel) - info.internalLabel = label + "###" + std::to_string(uuid); - else - info.internalLabel = label; - } - } - - if (PyObject* item = PyDict_GetItemString(dict, "width")) - { - info.dirty_size = true; - config.width = ToInt(item); - } - if (PyObject* item = PyDict_GetItemString(dict, "height")) - { - info.dirty_size = true; - config.height = ToInt(item); - } - - if (PyObject* item = PyDict_GetItemString(dict, "pos")) { - std::vector position = ToFloatVect(item); - if (!position.empty()) - { - info.dirtyPos = true; - state.pos = mvVec2{ position[0], position[1] }; - } - } - if (PyObject* item = PyDict_GetItemString(dict, "indent")) config.indent = (f32)ToInt(item); - if (PyObject* item = PyDict_GetItemString(dict, "show")) - { - config.show = ToBool(item); - if (config.show) - info.shownLastFrame = true; - else - info.hiddenLastFrame = true; - } - - if (PyObject* item = PyDict_GetItemString(dict, "filter_key")) config.filter = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "payload_type")) config.payloadType = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "source")) - { - if (isPyObject_Int(item)) - setDataSource(ToUUID(item)); - else if (isPyObject_String(item)) - { - std::string alias = ToString(item); - setDataSource(GetIdFromAlias(*GContext->itemRegistry, alias)); - } - } - if (PyObject* item = PyDict_GetItemString(dict, "enabled")) - { - b8 value = ToBool(item); - - if (config.enabled != value) - { - config.enabled = value; - - if (value) - info.enabledLastFrame = true; - else - info.disabledLastFrame = true; - } - } - if (PyObject* item = PyDict_GetItemString(dict, "tracked")) config.tracked = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "track_offset")) - { - config.trackOffset = ToFloat(item); - } - if (PyObject* item = PyDict_GetItemString(dict, "default_value")) - { - if(config.source == 0) - setPyValue(item); - } - - if (PyObject* item = PyDict_GetItemString(dict, "callback")) - { - config.callback = mvPyObject(item == Py_None? nullptr : item, true); - } - - if (PyObject* item = PyDict_GetItemString(dict, "drag_callback")) - { - config.dragCallback = mvPyObject(item == Py_None? nullptr : item, true); - } - - if (PyObject* item = PyDict_GetItemString(dict, "drop_callback")) - { - config.dropCallback = mvPyObject(item == Py_None? nullptr : item, true); - } - - if (PyObject* item = PyDict_GetItemString(dict, "user_data")) - { - *config.user_data = mvPyObject(item == Py_None? nullptr : item, true); - } - - handleSpecificKeywordArgs(dict); -} - -void -mvAppItem::setDataSource(mvUUID value) -{ - config.source = value; -} - -void -mvAppItem::handleImmediateScroll() -{ - if (!((config.scrollXFlags | config.scrollYFlags) & mvSetScrollFlags_Now)) - return; - - ImVec2 scroll = { (config.scrollXFlags & mvSetScrollFlags_Now)? config.scrollX : -1, - (config.scrollYFlags & mvSetScrollFlags_Now)? config.scrollY : -1 }; - ImGui::SetNextWindowScroll(scroll); -} - -void -mvAppItem::handleDelayedScroll() -{ - if (config.scrollXFlags & mvSetScrollFlags_Delayed) - { - if (config.scrollX < 0.0f) - ImGui::SetScrollHereX(1.0f); - else - ImGui::SetScrollX(config.scrollX); - } - - if (config.scrollYFlags & mvSetScrollFlags_Delayed) - { - if (config.scrollY < 0.0f) - ImGui::SetScrollHereY(1.0f); - else - ImGui::SetScrollY(config.scrollY); - } -} - -static bool -CanItemTypeBeHovered(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImage: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvNode: - case mvAppItemType::mvNodeAttribute: - case mvAppItemType::mvNodeEditor: - case mvAppItemType::mvNodeLink: - case mvAppItemType::mvPlot: - case mvAppItemType::mvTableColumn: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeActive(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeFocused(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeClicked(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvImage: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvNode: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeVisible(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImage: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenuBar: - case mvAppItemType::mvTab: - case mvAppItemType::mvTabBar: - case mvAppItemType::mvTooltip: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvTimePicker: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvNode: - case mvAppItemType::mvNodeEditor: - case mvAppItemType::mvPlot: - case mvAppItemType::mvTable: - case mvAppItemType::mvTableColumn: - case mvAppItemType::mvTableRow: - case mvAppItemType::mvSyncedTables: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeEdited(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvGroup: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvCombo: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeActivated(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeDeactivated(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeDeactivatedAE(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvCombo: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvGroup: - case mvAppItemType::mvCheckbox: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeToggledOpen(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvCollapsingHeader: return true; - default: return false; - } - -} - -static bool -CanItemTypeHaveRectMin(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImage: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvTab: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvTimePicker: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvNode: - case mvAppItemType::mvNodeEditor: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeHaveRectMax(mvAppItemType type) -{ - return CanItemTypeHaveRectMin(type); -} - -static bool -CanItemTypeHaveRectSize(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImage: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvMenu: - case mvAppItemType::mvTab: - case mvAppItemType::mvTooltip: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvTimePicker: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvNode: - case mvAppItemType::mvNodeEditor: - case mvAppItemType::mvPlot: - case mvAppItemType::mvTableColumn: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeHaveContAvail(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvCheckbox: - case mvAppItemType::mvCombo: - case mvAppItemType::mvDragInt: - case mvAppItemType::mvDragIntMulti: - case mvAppItemType::mvDragFloat: - case mvAppItemType::mvDragFloatMulti: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvImage: - case mvAppItemType::mvImageButton: - case mvAppItemType::mvInputText: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvListbox: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvText: - case mvAppItemType::mvColorButton: - case mvAppItemType::mvColorEdit: - case mvAppItemType::mvColorMapButton: - case mvAppItemType::mvColorMapScale: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvGroup: - case mvAppItemType::mvTab: - case mvAppItemType::mvTooltip: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvDatePicker: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvLoadingIndicator: - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvDrawlist: - case mvAppItemType::mvPlot: - case mvAppItemType::mvButton: return true; - default: return false; - } - -} - -static bool -CanItemTypeBeScrolled(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvTable: - case mvAppItemType::mvListbox: return true; - default: return false; - } - -} - -int -DearPyGui::GetApplicableState(mvAppItemType type) -{ - i32 applicableState = MV_STATE_NONE; - if(CanItemTypeBeHovered(type)) applicableState |= MV_STATE_HOVER; - if(CanItemTypeBeActive(type)) applicableState |= MV_STATE_ACTIVE; - if(CanItemTypeBeFocused(type)) applicableState |= MV_STATE_FOCUSED; - if(CanItemTypeBeClicked(type)) applicableState |= MV_STATE_CLICKED; - if(CanItemTypeBeVisible(type)) applicableState |= MV_STATE_VISIBLE; - if(CanItemTypeBeEdited(type)) applicableState |= MV_STATE_EDITED; - if(CanItemTypeBeActivated(type)) applicableState |= MV_STATE_ACTIVATED; - if(CanItemTypeBeDeactivated(type)) applicableState |= MV_STATE_DEACTIVATED; - if(CanItemTypeBeDeactivatedAE(type)) applicableState |= MV_STATE_DEACTIVATEDAE; - if(CanItemTypeBeToggledOpen(type)) applicableState |= MV_STATE_TOGGLED_OPEN; - if(CanItemTypeHaveRectMin(type)) applicableState |= MV_STATE_RECT_MIN; - if(CanItemTypeHaveRectMax(type)) applicableState |= MV_STATE_RECT_MAX; - if(CanItemTypeHaveRectSize(type)) applicableState |= MV_STATE_RECT_SIZE; - if(CanItemTypeHaveContAvail(type)) applicableState |= MV_STATE_CONT_AVAIL; - if(CanItemTypeBeScrolled(type)) applicableState |= MV_STATE_SCROLL; - - return applicableState; -} - -int -DearPyGui::GetEntityDesciptionFlags(mvAppItemType type) -{ - switch (type) - { - - case mvAppItemType::mvDrawBezierCubic: - case mvAppItemType::mvDrawBezierQuadratic: - case mvAppItemType::mvDrawCircle: - case mvAppItemType::mvDrawEllipse: - case mvAppItemType::mvDrawImage: - case mvAppItemType::mvDrawImageQuad: - case mvAppItemType::mvDrawLine: - case mvAppItemType::mvDrawPolygon: - case mvAppItemType::mvDrawPolyline: - case mvAppItemType::mvDrawQuad: - case mvAppItemType::mvDrawRect: - case mvAppItemType::mvDrawText: - case mvAppItemType::mvDrawTriangle: - case mvAppItemType::mvDrawArrow: return MV_ITEM_DESC_DRAW_CMP; - - case mvAppItemType::mvDrawNode: - case mvAppItemType::mvDrawLayer: - case mvAppItemType::mvDrawlist: return MV_ITEM_DESC_DRAW_CMP | MV_ITEM_DESC_CONTAINER; - - case mvAppItemType::mvThemeComponent: - case mvAppItemType::mvTable: - case mvAppItemType::mvTableCell: - case mvAppItemType::mvTableRow: - case mvAppItemType::mvSyncedTables: - case mvAppItemType::mv2dHistogramSeries: - case mvAppItemType::mvAreaSeries: - case mvAppItemType::mvBarSeries: - case mvAppItemType::mvBarGroupSeries: - case mvAppItemType::mvCandleSeries: - case mvAppItemType::mvCustomSeries: - case mvAppItemType::mvErrorSeries: - case mvAppItemType::mvHeatSeries: - case mvAppItemType::mvHistogramSeries: - case mvAppItemType::mvDigitalSeries: - case mvAppItemType::mvImageSeries: - case mvAppItemType::mvInfLineSeries: - case mvAppItemType::mvLabelSeries: - case mvAppItemType::mvLineSeries: - case mvAppItemType::mvPieSeries: - case mvAppItemType::mvScatterSeries: - case mvAppItemType::mvShadeSeries: - case mvAppItemType::mvStairSeries: - case mvAppItemType::mvStemSeries: - case mvAppItemType::mvPlot: - case mvAppItemType::mvSubPlots: - case mvAppItemType::mvPlotAxis: - case mvAppItemType::mvPlotLegend: - case mvAppItemType::mvNode: - case mvAppItemType::mvNodeAttribute: - case mvAppItemType::mvNodeEditor: - case mvAppItemType::mvFont: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvTab: - case mvAppItemType::mvTabBar: - case mvAppItemType::mvMenuBar: - case mvAppItemType::mvMenu: - case mvAppItemType::mvGroup: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvClipper: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvFilterSet: return MV_ITEM_DESC_CONTAINER; - - case mvAppItemType::mvActivatedHandler: - case mvAppItemType::mvActiveHandler: - case mvAppItemType::mvClickedHandler: - case mvAppItemType::mvDoubleClickedHandler: - case mvAppItemType::mvDeactivatedAfterEditHandler: - case mvAppItemType::mvDeactivatedHandler: - case mvAppItemType::mvEditedHandler: - case mvAppItemType::mvFocusHandler: - case mvAppItemType::mvHoverHandler: - case mvAppItemType::mvResizeHandler: - case mvAppItemType::mvToggledOpenHandler: - case mvAppItemType::mvScrollHandler: - case mvAppItemType::mvVisibleHandler: return MV_ITEM_DESC_HANDLER; - - case mvAppItemType::mvTooltip: - case mvAppItemType::mvDragPayload: return MV_ITEM_DESC_CONTAINER | MV_ITEM_DESC_HANDLER; - - case mvAppItemType::mvTheme: - case mvAppItemType::mvValueRegistry: - case mvAppItemType::mvItemHandlerRegistry: - case mvAppItemType::mvTextureRegistry: - case mvAppItemType::mvHandlerRegistry: - case mvAppItemType::mvFontRegistry: - case mvAppItemType::mvWindowAppItem: - case mvAppItemType::mvViewportDrawlist: - case mvAppItemType::mvViewportMenuBar: - case mvAppItemType::mvTemplateRegistry: - case mvAppItemType::mvFileDialog: - case mvAppItemType::mvColorMapRegistry: - case mvAppItemType::mvStage: return MV_ITEM_DESC_ROOT | MV_ITEM_DESC_CONTAINER; - default: return MV_ITEM_DESC_DEFAULT; - } -} - -int -DearPyGui::GetEntityTargetSlot(mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvFileExtension: - case mvAppItemType::mvNodeLink: - case mvAppItemType::mvAnnotation: - case mvAppItemType::mvDragLine: - case mvAppItemType::mvDragPoint: - case mvAppItemType::mvDragRect: - case mvAppItemType::mvPlotLegend: - case mvAppItemType::mvTableColumn: return 0; - - case mvAppItemType::mvDrawBezierCubic: - case mvAppItemType::mvDrawBezierQuadratic: - case mvAppItemType::mvDrawCircle: - case mvAppItemType::mvDrawEllipse: - case mvAppItemType::mvDrawImage: - case mvAppItemType::mvDrawImageQuad: - case mvAppItemType::mvDrawLayer: - case mvAppItemType::mvDrawLine: - case mvAppItemType::mvDrawNode: - case mvAppItemType::mvDrawPolygon: - case mvAppItemType::mvDrawPolyline: - case mvAppItemType::mvDrawQuad: - case mvAppItemType::mvDrawRect: - case mvAppItemType::mvDrawText: - case mvAppItemType::mvDrawTriangle: - case mvAppItemType::mvDrawArrow: return 2; - - case mvAppItemType::mvDragPayload: return 3; - - default: return 1; - } -} - -StorageValueTypes -DearPyGui::GetEntityValueType(mvAppItemType type) -{ - switch (type) - { - - case mvAppItemType::mvTimePicker: - case mvAppItemType::mvDatePicker: return StorageValueTypes::Time; - - case mvAppItemType::mvTabBar: return StorageValueTypes::UUID; - - case mvAppItemType::mvColorValue: - case mvAppItemType::mvThemeColor: - case mvAppItemType::mvColorPicker: - case mvAppItemType::mvColorEdit: return StorageValueTypes::Color; - - case mvAppItemType::mvIntValue: - case mvAppItemType::mvSliderInt: - case mvAppItemType::mvInputInt: - case mvAppItemType::mvDragInt: return StorageValueTypes::Int; - - case mvAppItemType::mvFloatValue: - case mvAppItemType::mvProgressBar: - case mvAppItemType::mvKnobFloat: - case mvAppItemType::mvColorMapSlider: - case mvAppItemType::mvSliderFloat: - case mvAppItemType::mvInputFloat: - case mvAppItemType::mvDragFloat: return StorageValueTypes::Float; - - case mvAppItemType::mvFloat4Value: - case mvAppItemType::mvThemeStyle: - - case mvAppItemType::mvSlider3D: - case mvAppItemType::mvInputFloatMulti: - case mvAppItemType::mvSliderFloatMulti: - case mvAppItemType::mvDragFloatMulti: return StorageValueTypes::Float4; - - case mvAppItemType::mvInt4Value: - case mvAppItemType::mvInputIntMulti: - case mvAppItemType::mvSliderIntMulti: - case mvAppItemType::mvDragIntMulti: return StorageValueTypes::Int4; - - case mvAppItemType::mvStringValue: - case mvAppItemType::mvText: - case mvAppItemType::mvRadioButton: - case mvAppItemType::mvListbox: - case mvAppItemType::mvInputText: - case mvAppItemType::mvCombo: return StorageValueTypes::String; - - case mvAppItemType::mvBoolValue: - case mvAppItemType::mvTreeNode: - case mvAppItemType::mvTooltip: - case mvAppItemType::mvTab: - case mvAppItemType::mvMenuBar: - case mvAppItemType::mvMenu: - case mvAppItemType::mvCollapsingHeader: - case mvAppItemType::mvChildWindow: - case mvAppItemType::mvFileDialog: - case mvAppItemType::mvSelectable: - case mvAppItemType::mvMenuItem: - case mvAppItemType::mvCheckbox: return StorageValueTypes::Bool; - - case mvAppItemType::mvSeriesValue: - case mvAppItemType::mv2dHistogramSeries: - case mvAppItemType::mvAreaSeries: - case mvAppItemType::mvBarSeries: - case mvAppItemType::mvBarGroupSeries: - case mvAppItemType::mvCandleSeries: - case mvAppItemType::mvCustomSeries: - case mvAppItemType::mvErrorSeries: - case mvAppItemType::mvHeatSeries: - case mvAppItemType::mvHistogramSeries: - case mvAppItemType::mvDigitalSeries: - case mvAppItemType::mvImageSeries: - case mvAppItemType::mvInfLineSeries: - case mvAppItemType::mvLabelSeries: - case mvAppItemType::mvLineSeries: - case mvAppItemType::mvPieSeries: - case mvAppItemType::mvScatterSeries: - case mvAppItemType::mvShadeSeries: - case mvAppItemType::mvStairSeries: - case mvAppItemType::mvStemSeries: return StorageValueTypes::Series; - - case mvAppItemType::mvDoubleValue: - case mvAppItemType::mvDragDouble: - case mvAppItemType::mvAxisTag: - case mvAppItemType::mvInputDouble: - case mvAppItemType::mvSliderDouble: - case mvAppItemType::mvDragLine: return StorageValueTypes::Double; - - case mvAppItemType::mvDouble4Value: - case mvAppItemType::mvDragDoubleMulti: - case mvAppItemType::mvInputDoubleMulti: - case mvAppItemType::mvSliderDoubleMulti: - case mvAppItemType::mvAnnotation: - case mvAppItemType::mvDragRect: return StorageValueTypes::Double4; - - case mvAppItemType::mvDragPoint: - case mvAppItemType::mvStaticTexture: - case mvAppItemType::mvDynamicTexture: - case mvAppItemType::mvSimplePlot: return StorageValueTypes::FloatVect; - - default: return StorageValueTypes::None; - } -} - -const char* -DearPyGui::GetEntityTypeString(mvAppItemType type) -{ - #define X(el) "mvAppItemType::" #el, - static const char* entity_type_strings[(size_t)mvAppItemType::ItemTypeCount] = - { - "All, an error occured", // shouldn't actually occur - MV_ITEM_TYPES - }; - #undef X - return entity_type_strings[(size_t)type]; -} - -std::shared_ptr -DearPyGui::CreateEntity(mvAppItemType type, mvUUID id) -{ - #define X(el) case mvAppItemType::el: {auto item = std::make_shared(id); item->type = mvAppItemType::el; return item;}; - switch (type) - { - MV_ITEM_TYPES - default: return nullptr; - } - #undef X -} - -const std::vector>& -DearPyGui::GetAllowableParents(mvAppItemType type) -{ - - // TODO: possibly index into array instead of switch - - #define MV_ADD_PARENT(x){#x, (int)x} - #define MV_START_PARENTS {static std::vector> parents = { - #define MV_END_PARENTS };return parents;} - - switch (type) - { - - case mvAppItemType::mvActivatedHandler: - case mvAppItemType::mvActiveHandler: - case mvAppItemType::mvClickedHandler: - case mvAppItemType::mvDoubleClickedHandler: - case mvAppItemType::mvDeactivatedAfterEditHandler: - case mvAppItemType::mvDeactivatedHandler: - case mvAppItemType::mvEditedHandler: - case mvAppItemType::mvFocusHandler: - case mvAppItemType::mvHoverHandler: - case mvAppItemType::mvResizeHandler: - case mvAppItemType::mvToggledOpenHandler: - case mvAppItemType::mvScrollHandler: - case mvAppItemType::mvVisibleHandler: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvItemHandlerRegistry) - MV_END_PARENTS - - case mvAppItemType::mvBoolValue: - case mvAppItemType::mvColorValue: - case mvAppItemType::mvDouble4Value: - case mvAppItemType::mvDoubleValue: - case mvAppItemType::mvFloat4Value: - case mvAppItemType::mvFloatValue: - case mvAppItemType::mvFloatVectValue: - case mvAppItemType::mvInt4Value: - case mvAppItemType::mvIntValue: - case mvAppItemType::mvSeriesValue: - case mvAppItemType::mvStringValue: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvValueRegistry) - MV_END_PARENTS - - case mvAppItemType::mvThemeComponent: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTheme), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry) - MV_END_PARENTS - - case mvAppItemType::mvThemeStyle: - case mvAppItemType::mvThemeColor: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvThemeComponent), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_END_PARENTS - - case mvAppItemType::mvDynamicTexture: - case mvAppItemType::mvStaticTexture: - case mvAppItemType::mvRawTexture: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvTextureRegistry) - MV_END_PARENTS - - case mvAppItemType::mvTableCell: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvTableRow) - MV_END_PARENTS - - case mvAppItemType::mvTableColumn: - case mvAppItemType::mvTableRow: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvTable) - MV_END_PARENTS - - case mvAppItemType::mvDrawBezierCubic: - case mvAppItemType::mvDrawBezierQuadratic: - case mvAppItemType::mvDrawCircle: - case mvAppItemType::mvDrawEllipse: - case mvAppItemType::mvDrawImage: - case mvAppItemType::mvDrawImageQuad: - case mvAppItemType::mvDrawLine: - case mvAppItemType::mvDrawPolygon: - case mvAppItemType::mvDrawPolyline: - case mvAppItemType::mvDrawQuad: - case mvAppItemType::mvDrawRect: - case mvAppItemType::mvDrawText: - case mvAppItemType::mvDrawTriangle: - case mvAppItemType::mvDrawArrow: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvDrawlist), - MV_ADD_PARENT(mvAppItemType::mvDrawLayer), - MV_ADD_PARENT(mvAppItemType::mvWindowAppItem), - MV_ADD_PARENT(mvAppItemType::mvPlot), - MV_ADD_PARENT(mvAppItemType::mvDrawNode), - MV_ADD_PARENT(mvAppItemType::mvViewportDrawlist), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvCustomSeries), - MV_END_PARENTS - - case mvAppItemType::mvDrawLayer: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvDrawlist), - MV_ADD_PARENT(mvAppItemType::mvWindowAppItem), - MV_ADD_PARENT(mvAppItemType::mvPlot), - MV_ADD_PARENT(mvAppItemType::mvViewportDrawlist) - MV_END_PARENTS - - case mvAppItemType::mvDrawNode: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvDrawlist), - MV_ADD_PARENT(mvAppItemType::mvDrawLayer), - MV_ADD_PARENT(mvAppItemType::mvWindowAppItem), - MV_ADD_PARENT(mvAppItemType::mvPlot), - MV_ADD_PARENT(mvAppItemType::mvViewportDrawlist), - MV_ADD_PARENT(mvAppItemType::mvDrawNode), - MV_END_PARENTS - - case mvAppItemType::mvMenuBar: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvWindowAppItem), - MV_ADD_PARENT(mvAppItemType::mvChildWindow), - MV_ADD_PARENT(mvAppItemType::mvNodeEditor), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_END_PARENTS - - case mvAppItemType::mvColorMap: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvColorMapRegistry), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry) - MV_END_PARENTS - - case mvAppItemType::mvFileExtension: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvFileDialog), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_END_PARENTS - - case mvAppItemType::mvTab: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTabBar), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_END_PARENTS - - case mvAppItemType::mvTabButton: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTabBar), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry) - MV_END_PARENTS - - case mvAppItemType::mvNodeAttribute: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvNode) - MV_END_PARENTS - - case mvAppItemType::mvNodeLink: - case mvAppItemType::mvNode: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvNodeEditor) - MV_END_PARENTS - - case mvAppItemType::mvPlotLegend: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvPlot), - MV_ADD_PARENT(mvAppItemType::mvSubPlots) - MV_END_PARENTS - - case mvAppItemType::mvPlotAxis: - case mvAppItemType::mvDragLine: - case mvAppItemType::mvDragRect: - case mvAppItemType::mvDragPoint: - case mvAppItemType::mvAnnotation: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvPlot) - MV_END_PARENTS - - case mvAppItemType::mvAxisTag: - case mvAppItemType::mvAreaSeries: - case mvAppItemType::mvBarSeries: - case mvAppItemType::mvBarGroupSeries: - case mvAppItemType::mvCandleSeries: - case mvAppItemType::mvErrorSeries: - case mvAppItemType::mvHeatSeries: - case mvAppItemType::mvHistogramSeries: - case mvAppItemType::mvDigitalSeries: - case mvAppItemType::mvImageSeries: - case mvAppItemType::mvInfLineSeries: - case mvAppItemType::mvLabelSeries: - case mvAppItemType::mvLineSeries: - case mvAppItemType::mvPieSeries: - case mvAppItemType::mvScatterSeries: - case mvAppItemType::mvShadeSeries: - case mvAppItemType::mvStairSeries: - case mvAppItemType::mvStemSeries: - case mvAppItemType::mv2dHistogramSeries: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvPlotAxis), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_END_PARENTS - - case mvAppItemType::mvMouseClickHandler: - case mvAppItemType::mvMouseDoubleClickHandler: - case mvAppItemType::mvMouseDownHandler: - case mvAppItemType::mvMouseDragHandler: - case mvAppItemType::mvMouseMoveHandler: - case mvAppItemType::mvMouseReleaseHandler: - case mvAppItemType::mvMouseWheelHandler: - case mvAppItemType::mvKeyPressHandler: - case mvAppItemType::mvKeyReleaseHandler: - case mvAppItemType::mvKeyDownHandler: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvStage), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry), - MV_ADD_PARENT(mvAppItemType::mvHandlerRegistry) - MV_END_PARENTS - - case mvAppItemType::mvCharRemap: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvFont), - MV_ADD_PARENT(mvAppItemType::mvTemplateRegistry) - MV_END_PARENTS - - case mvAppItemType::mvFont: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvFontRegistry) - MV_END_PARENTS - - case mvAppItemType::mvDragPayload: - MV_START_PARENTS - MV_ADD_PARENT(mvAppItemType::mvButton), - MV_ADD_PARENT(mvAppItemType::mvCheckbox), - MV_ADD_PARENT(mvAppItemType::mvCombo), - MV_ADD_PARENT(mvAppItemType::mvDragIntMulti), - MV_ADD_PARENT(mvAppItemType::mvDragFloatMulti), - MV_ADD_PARENT(mvAppItemType::mvDragDoubleMulti), - MV_ADD_PARENT(mvAppItemType::mvDragInt), - MV_ADD_PARENT(mvAppItemType::mvDragFloat), - MV_ADD_PARENT(mvAppItemType::mvDragDouble), - MV_ADD_PARENT(mvAppItemType::mvImage), - MV_ADD_PARENT(mvAppItemType::mvImageButton), - MV_ADD_PARENT(mvAppItemType::mvInputIntMulti), - MV_ADD_PARENT(mvAppItemType::mvInputFloatMulti), - MV_ADD_PARENT(mvAppItemType::mvInputDoubleMulti), - MV_ADD_PARENT(mvAppItemType::mvInputInt), - MV_ADD_PARENT(mvAppItemType::mvInputFloat), - MV_ADD_PARENT(mvAppItemType::mvInputDouble), - MV_ADD_PARENT(mvAppItemType::mvInputText), - MV_ADD_PARENT(mvAppItemType::mvListbox), - MV_ADD_PARENT(mvAppItemType::mvMenuItem), - MV_ADD_PARENT(mvAppItemType::mvRadioButton), - MV_ADD_PARENT(mvAppItemType::mvSelectable), - MV_ADD_PARENT(mvAppItemType::mvSliderIntMulti), - MV_ADD_PARENT(mvAppItemType::mvSliderFloatMulti), - MV_ADD_PARENT(mvAppItemType::mvSliderDoubleMulti), - MV_ADD_PARENT(mvAppItemType::mvSliderInt), - MV_ADD_PARENT(mvAppItemType::mvSliderFloat), - MV_ADD_PARENT(mvAppItemType::mvSliderDouble), - MV_ADD_PARENT(mvAppItemType::mvTabButton), - MV_ADD_PARENT(mvAppItemType::mvText), - MV_ADD_PARENT(mvAppItemType::mvColorButton), - MV_ADD_PARENT(mvAppItemType::mvColorEdit), - MV_ADD_PARENT(mvAppItemType::mvColorMapButton), - MV_ADD_PARENT(mvAppItemType::mvColorPicker), - MV_ADD_PARENT(mvAppItemType::mvCollapsingHeader), - MV_ADD_PARENT(mvAppItemType::mvGroup), - MV_ADD_PARENT(mvAppItemType::mvTreeNode), - MV_ADD_PARENT(mvAppItemType::mvDatePicker), - MV_ADD_PARENT(mvAppItemType::mvKnobFloat), - MV_ADD_PARENT(mvAppItemType::mvLoadingIndicator), - MV_ADD_PARENT(mvAppItemType::mvSlider3D), - MV_ADD_PARENT(mvAppItemType::mvTimePicker), - MV_ADD_PARENT(mvAppItemType::mvProgressBar), - MV_ADD_PARENT(mvAppItemType::mvNode), - MV_ADD_PARENT(mvAppItemType::mvPlot) - MV_END_PARENTS - - default: - { - static std::vector> parents = { {"All", 0} }; - return parents; - } - } - - #undef MV_ADD_PARENT - #undef MV_START_PARENTS - #undef MV_END_PARENTS -} - -const std::vector>& -DearPyGui::GetAllowableChildren(mvAppItemType type) -{ - - // TODO: possibly index into array instead of switch - - #define MV_ADD_CHILD(x){#x, (int)x} - #define MV_START_CHILDREN {static std::vector> children = { - #define MV_END_CHILDREN };return children;} - - switch (type) - { - - case mvAppItemType::mvItemHandlerRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvActivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvActiveHandler), - MV_ADD_CHILD(mvAppItemType::mvClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDoubleClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedAfterEditHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvEditedHandler), - MV_ADD_CHILD(mvAppItemType::mvFocusHandler), - MV_ADD_CHILD(mvAppItemType::mvHoverHandler), - MV_ADD_CHILD(mvAppItemType::mvResizeHandler), - MV_ADD_CHILD(mvAppItemType::mvToggledOpenHandler), - MV_ADD_CHILD(mvAppItemType::mvVisibleHandler), - MV_ADD_CHILD(mvAppItemType::mvScrollHandler), - MV_END_CHILDREN - - case mvAppItemType::mvValueRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvBoolValue), - MV_ADD_CHILD(mvAppItemType::mvIntValue), - MV_ADD_CHILD(mvAppItemType::mvInt4Value), - MV_ADD_CHILD(mvAppItemType::mvFloatValue), - MV_ADD_CHILD(mvAppItemType::mvFloat4Value), - MV_ADD_CHILD(mvAppItemType::mvStringValue), - MV_ADD_CHILD(mvAppItemType::mvDoubleValue), - MV_ADD_CHILD(mvAppItemType::mvDouble4Value), - MV_ADD_CHILD(mvAppItemType::mvColorValue), - MV_ADD_CHILD(mvAppItemType::mvFloatVectValue), - MV_ADD_CHILD(mvAppItemType::mvSeriesValue) - MV_END_CHILDREN - - case mvAppItemType::mvThemeComponent: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvThemeColor), - MV_ADD_CHILD(mvAppItemType::mvThemeStyle) - MV_END_CHILDREN - - case mvAppItemType::mvTheme: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvThemeComponent) - MV_END_CHILDREN - - case mvAppItemType::mvTextureRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvStaticTexture), - MV_ADD_CHILD(mvAppItemType::mvDynamicTexture), - MV_ADD_CHILD(mvAppItemType::mvRawTexture) - MV_END_CHILDREN - - case mvAppItemType::mvTable: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvTooltip), - MV_ADD_CHILD(mvAppItemType::mvTableRow), - MV_ADD_CHILD(mvAppItemType::mvTableColumn) - MV_END_CHILDREN - - case mvAppItemType::mvSubPlots: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvPlot), - MV_ADD_CHILD(mvAppItemType::mvPlotLegend) - MV_END_CHILDREN - - case mvAppItemType::mvPlot: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvPlotLegend), - MV_ADD_CHILD(mvAppItemType::mvPlotAxis), - MV_ADD_CHILD(mvAppItemType::mvDragPoint), - MV_ADD_CHILD(mvAppItemType::mvDragRect), - MV_ADD_CHILD(mvAppItemType::mvDragLine), - MV_ADD_CHILD(mvAppItemType::mvAnnotation), - MV_ADD_CHILD(mvAppItemType::mvDrawLine), - MV_ADD_CHILD(mvAppItemType::mvDrawArrow), - MV_ADD_CHILD(mvAppItemType::mvDrawTriangle), - MV_ADD_CHILD(mvAppItemType::mvDrawCircle), - MV_ADD_CHILD(mvAppItemType::mvDrawEllipse), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierCubic), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierQuadratic), - MV_ADD_CHILD(mvAppItemType::mvDrawQuad), - MV_ADD_CHILD(mvAppItemType::mvDrawRect), - MV_ADD_CHILD(mvAppItemType::mvDrawText), - MV_ADD_CHILD(mvAppItemType::mvDrawPolygon), - MV_ADD_CHILD(mvAppItemType::mvDrawPolyline), - MV_ADD_CHILD(mvAppItemType::mvDrawImage), - MV_ADD_CHILD(mvAppItemType::mvDrawLayer), - MV_ADD_CHILD(mvAppItemType::mvActivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvActiveHandler), - MV_ADD_CHILD(mvAppItemType::mvClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDoubleClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedAfterEditHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvEditedHandler), - MV_ADD_CHILD(mvAppItemType::mvFocusHandler), - MV_ADD_CHILD(mvAppItemType::mvHoverHandler), - MV_ADD_CHILD(mvAppItemType::mvResizeHandler), - MV_ADD_CHILD(mvAppItemType::mvToggledOpenHandler), - MV_ADD_CHILD(mvAppItemType::mvVisibleHandler), - MV_ADD_CHILD(mvAppItemType::mvDragPayload), - MV_ADD_CHILD(mvAppItemType::mvDrawNode), - MV_END_CHILDREN - - case mvAppItemType::mvNodeEditor: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvMenuBar), - MV_ADD_CHILD(mvAppItemType::mvNode), - MV_ADD_CHILD(mvAppItemType::mvNodeLink), - MV_ADD_CHILD(mvAppItemType::mvActivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvActiveHandler), - MV_ADD_CHILD(mvAppItemType::mvClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDoubleClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedAfterEditHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvEditedHandler), - MV_ADD_CHILD(mvAppItemType::mvFocusHandler), - MV_ADD_CHILD(mvAppItemType::mvHoverHandler), - MV_ADD_CHILD(mvAppItemType::mvResizeHandler), - MV_ADD_CHILD(mvAppItemType::mvToggledOpenHandler), - MV_ADD_CHILD(mvAppItemType::mvVisibleHandler) - MV_END_CHILDREN - - case mvAppItemType::mvNode: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvNodeAttribute), - MV_ADD_CHILD(mvAppItemType::mvActiveHandler), - MV_ADD_CHILD(mvAppItemType::mvClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDoubleClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvHoverHandler), - MV_ADD_CHILD(mvAppItemType::mvVisibleHandler), - MV_ADD_CHILD(mvAppItemType::mvDragPayload), - MV_END_CHILDREN - - case mvAppItemType::mvHandlerRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvKeyDownHandler), - MV_ADD_CHILD(mvAppItemType::mvKeyPressHandler), - MV_ADD_CHILD(mvAppItemType::mvKeyReleaseHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseMoveHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseWheelHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseClickHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseDoubleClickHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseDownHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseReleaseHandler), - MV_ADD_CHILD(mvAppItemType::mvMouseDragHandler) - MV_END_CHILDREN - - case mvAppItemType::mvFontRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvFont) - MV_END_CHILDREN - - case mvAppItemType::mvFont: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvCharRemap), - MV_ADD_CHILD(mvAppItemType::mvTemplateRegistry), - MV_END_CHILDREN - - case mvAppItemType::mvViewportDrawlist: - case mvAppItemType::mvDrawlist: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvDrawLayer), - MV_ADD_CHILD(mvAppItemType::mvDrawLine), - MV_ADD_CHILD(mvAppItemType::mvDrawArrow), - MV_ADD_CHILD(mvAppItemType::mvDrawTriangle), - MV_ADD_CHILD(mvAppItemType::mvDrawCircle), - MV_ADD_CHILD(mvAppItemType::mvDrawEllipse), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierCubic), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierQuadratic), - MV_ADD_CHILD(mvAppItemType::mvDrawQuad), - MV_ADD_CHILD(mvAppItemType::mvDrawRect), - MV_ADD_CHILD(mvAppItemType::mvDrawText), - MV_ADD_CHILD(mvAppItemType::mvDrawPolygon), - MV_ADD_CHILD(mvAppItemType::mvDrawPolyline), - MV_ADD_CHILD(mvAppItemType::mvDrawImageQuad), - MV_ADD_CHILD(mvAppItemType::mvDrawImage), - MV_ADD_CHILD(mvAppItemType::mvDrawNode), - MV_END_CHILDREN - - case mvAppItemType::mvDrawNode: - case mvAppItemType::mvDrawLayer: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvDrawLine), - MV_ADD_CHILD(mvAppItemType::mvDrawArrow), - MV_ADD_CHILD(mvAppItemType::mvDrawTriangle), - MV_ADD_CHILD(mvAppItemType::mvDrawCircle), - MV_ADD_CHILD(mvAppItemType::mvDrawEllipse), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierCubic), - MV_ADD_CHILD(mvAppItemType::mvDrawBezierQuadratic), - MV_ADD_CHILD(mvAppItemType::mvDrawQuad), - MV_ADD_CHILD(mvAppItemType::mvDrawRect), - MV_ADD_CHILD(mvAppItemType::mvDrawText), - MV_ADD_CHILD(mvAppItemType::mvDrawPolygon), - MV_ADD_CHILD(mvAppItemType::mvDrawPolyline), - MV_ADD_CHILD(mvAppItemType::mvDrawImage), - MV_ADD_CHILD(mvAppItemType::mvDrawImageQuad), - MV_ADD_CHILD(mvAppItemType::mvDrawNode), - MV_END_CHILDREN - - case mvAppItemType::mvTabBar: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvTab), - MV_ADD_CHILD(mvAppItemType::mvTabButton), - MV_ADD_CHILD(mvAppItemType::mvActivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvActiveHandler), - MV_ADD_CHILD(mvAppItemType::mvClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDoubleClickedHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedAfterEditHandler), - MV_ADD_CHILD(mvAppItemType::mvDeactivatedHandler), - MV_ADD_CHILD(mvAppItemType::mvEditedHandler), - MV_ADD_CHILD(mvAppItemType::mvFocusHandler), - MV_ADD_CHILD(mvAppItemType::mvHoverHandler), - MV_ADD_CHILD(mvAppItemType::mvResizeHandler), - MV_ADD_CHILD(mvAppItemType::mvToggledOpenHandler), - MV_ADD_CHILD(mvAppItemType::mvVisibleHandler) - MV_END_CHILDREN - - case mvAppItemType::mvColorMapRegistry: - MV_START_CHILDREN - MV_ADD_CHILD(mvAppItemType::mvColorMap) - MV_END_CHILDREN - - default: - { - static std::vector> parents = { {"All", 0} }; - return parents; - } - } - - #undef MV_ADD_CHILD - #undef MV_START_CHILDREN - #undef MV_END_CHILDREN -} - -std::shared_ptr& -DearPyGui::GetClassThemeComponent(mvAppItemType type) -{ - #define X(el) case mvAppItemType::el: { static std::shared_ptr s_class_theme = nullptr; return s_class_theme; } - switch (type) - { - MV_ITEM_TYPES - default: - { - static std::shared_ptr s_class_theme = nullptr; - return s_class_theme; - } - } - #undef X -} - -std::shared_ptr& -DearPyGui::GetDisabledClassThemeComponent(mvAppItemType type) -{ - #define X(el) case mvAppItemType::el: { static std::shared_ptr s_class_theme = nullptr; return s_class_theme; } - switch (type) - { - MV_ITEM_TYPES - default: - { - static std::shared_ptr s_class_theme = nullptr; - return s_class_theme; - } - } - #undef X -} - -mvPythonParser -DearPyGui::GetEntityParser(mvAppItemType type) -{ - std::vector args; - mvPythonParserSetup setup; - setup.returnType = mvPyDataType::UUID; - setup.category = { "Widgets" }; - - switch (type) - { - case mvAppItemType::mvButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "small", mvArgType::KEYWORD_ARG, "False", "Shrinks the size of the button to the text of the label it contains. Useful for embedding in text." }); - args.push_back({ mvPyDataType::Bool, "arrow", mvArgType::KEYWORD_ARG, "False", "Displays an arrow in place of the text string. This requires the direction keyword." }); - args.push_back({ mvPyDataType::Integer, "direction", mvArgType::KEYWORD_ARG, "0", "Sets the cardinal direction for the arrow by using constants mvDir_Left, mvDir_Up, mvDir_Down, mvDir_Right, mvDir_None. Arrow keyword must be set to True." }); - args.push_back({ mvPyDataType::Bool, "repeat", mvArgType::KEYWORD_ARG, "False", "Hold to continuosly repeat the click." }); - - setup.about = "Adds a button."; - break; - } - - case mvAppItemType::mvCheckbox: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "default_value", mvArgType::KEYWORD_ARG, "False", "Sets the default value of the checkmark" }); - - setup.about = "Adds a checkbox."; - break; - } - - case mvAppItemType::mvCombo: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::StringList, "items", mvArgType::POSITIONAL_ARG, "()", "A tuple of items to be shown in the drop down window. Can consist of any combination of types but will convert all items to strings to be shown." }); - args.push_back({ mvPyDataType::String, "default_value", mvArgType::KEYWORD_ARG, "''", "Sets a selected item from the drop down by specifying the string value." }); - args.push_back({ mvPyDataType::Bool, "popup_align_left", mvArgType::KEYWORD_ARG, "False", "Align the contents on the popup toward the left." }); - args.push_back({ mvPyDataType::Bool, "no_arrow_button", mvArgType::KEYWORD_ARG, "False", "Display the preview box without the square arrow button indicating dropdown activity." }); - args.push_back({ mvPyDataType::Bool, "no_preview", mvArgType::KEYWORD_ARG, "False", "Display only the square arrow button and not the selected value." }); - args.push_back({ mvPyDataType::Bool, "fit_width", mvArgType::KEYWORD_ARG, "False", "Fit the available width." }); - args.push_back({ mvPyDataType::Long, "height_mode", mvArgType::KEYWORD_ARG, "1", "Controlls the number of items shown in the dropdown by the constants mvComboHeight_Small, mvComboHeight_Regular, mvComboHeight_Large, mvComboHeight_Largest" }); - - setup.about = "Adds a combo dropdown that allows a user to select a single option from a drop down window. All items will be shown as selectables on the dropdown."; - break; - } - - case mvAppItemType::mvInputText: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::String, "default_value", mvArgType::KEYWORD_ARG, "''" }); - args.push_back({ mvPyDataType::String, "hint", mvArgType::KEYWORD_ARG, "''", "Displayed only when value is an empty string. Will reappear if input value is set to empty string. Will not show if default value is anything other than default empty string." }); - args.push_back({ mvPyDataType::Bool, "multiline", mvArgType::KEYWORD_ARG, "False", "Allows for multiline text input." }); - args.push_back({ mvPyDataType::Bool, "no_spaces", mvArgType::KEYWORD_ARG, "False", "Filter out spaces and tabs." }); - args.push_back({ mvPyDataType::Bool, "uppercase", mvArgType::KEYWORD_ARG, "False", "Automatically make all inputs uppercase." }); - args.push_back({ mvPyDataType::Bool, "tab_input", mvArgType::KEYWORD_ARG, "False", "Allows tabs to be input into the string value instead of changing item focus." }); - args.push_back({ mvPyDataType::Bool, "decimal", mvArgType::KEYWORD_ARG, "False", "Only allow characters 0123456789.+-*/" }); - args.push_back({ mvPyDataType::Bool, "hexadecimal", mvArgType::KEYWORD_ARG, "False", "Only allow characters 0123456789ABCDEFabcdef" }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "password", mvArgType::KEYWORD_ARG, "False", "Display all input characters as '*'." }); - args.push_back({ mvPyDataType::Bool, "scientific", mvArgType::KEYWORD_ARG, "False", "Only allow characters 0123456789.+-*/eE (Scientific notation input)" }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "auto_select_all", mvArgType::KEYWORD_ARG, "False", "Select entire text when first taking mouse focus" }); - args.push_back({ mvPyDataType::Bool, "ctrl_enter_for_new_line", mvArgType::KEYWORD_ARG, "False", "In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter)." }); - args.push_back({ mvPyDataType::Bool, "no_horizontal_scroll", mvArgType::KEYWORD_ARG, "False", "Disable following the cursor horizontally" }); - args.push_back({ mvPyDataType::Bool, "always_overwrite", mvArgType::KEYWORD_ARG, "False", "Overwrite mode" }); - args.push_back({ mvPyDataType::Bool, "no_undo_redo", mvArgType::KEYWORD_ARG, "False", "Disable undo/redo." }); - args.push_back({ mvPyDataType::Bool, "escape_clears_all", mvArgType::KEYWORD_ARG, "False", "Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert)" }); - args.push_back({ mvPyDataType::Bool, "elide_left", mvArgType::KEYWORD_ARG, "False", - "When text doesn't fit an inactive input field, clip it on the left side " - "and ensure the right side stays visible. Useful for path/filenames. " - "Single-line inputs only." }); - - setup.about = "Adds input for text."; - break; - } - case mvAppItemType::mvRadioButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::StringList, "items", mvArgType::POSITIONAL_ARG, "()", "A tuple of items to be shown as radio options. Can consist of any combination of types. All types will be shown as strings." }); - args.push_back({ mvPyDataType::String, "default_value", mvArgType::KEYWORD_ARG, "''", "Default selected radio option. Set by using the string value of the item." }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "Displays the radio options horizontally." }); - - setup.about = "Adds a set of radio buttons. If items keyword is empty, nothing will be shown."; - break; - } - - case mvAppItemType::mvTabBar: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "reorderable", mvArgType::KEYWORD_ARG, "False", "Allows for the user to change the order of the tabs." }); - args.push_back({ mvPyDataType::Bool, "tab_list_popup_button", mvArgType::KEYWORD_ARG, "False", "Show a button to select active tab from a dropdown list." }); - args.push_back({ mvPyDataType::Bool, "no_close_with_middle_click", mvArgType::KEYWORD_ARG, "False", "Disable closing tabs (that have closable=True) by clicking with middle mouse button." }); - args.push_back({ mvPyDataType::Bool, "no_scrolling_buttons", mvArgType::KEYWORD_ARG, "False", "Disable left/right scrolling buttons when tab buttons don't fit the container width." }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltips when hovering a tab with a long name." }); - args.push_back({ mvPyDataType::Bool, "draw_selected_overline", mvArgType::KEYWORD_ARG, "False", "Draw selected overline markers over selected tab." }); - - setup.about = "Adds a tab bar."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTab: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Bool, "closable", mvArgType::KEYWORD_ARG, "False", "Creates a button on the tab that can hide the tab." }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip for the given tab." }); - args.push_back({ mvPyDataType::Integer, "order_mode", mvArgType::KEYWORD_ARG, "0", "set using a constant: mvTabOrder_Reorderable: allows reordering, mvTabOrder_Fixed: fixed ordering, mvTabOrder_Leading: adds tab to front, mvTabOrder_Trailing: adds tab to back" }); - args.push_back({ mvPyDataType::Bool, "unsaved_document", mvArgType::KEYWORD_ARG, "False", "Display a dot next to the title." }); - args.push_back({ mvPyDataType::Bool, "no_close_with_middle_click", mvArgType::KEYWORD_ARG, "False", "Disable closing this tab (if closable==True) by clicking with middle mouse button." }); - args.push_back({ mvPyDataType::Bool, "no_reorder", mvArgType::KEYWORD_ARG, "False", "Disable reordering this tab or having another tab cross over this tab." }); - - setup.about = "Adds a tab to a tab bar."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvImage: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::UUID, "texture_tag", mvArgType::REQUIRED_ARG, "", "The texture_tag should come from a texture that was added to a texture registry." }); - args.push_back({ mvPyDataType::FloatList, "tint_color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)", "Applies a color tint to the entire texture." }); - args.push_back({ mvPyDataType::FloatList, "border_color", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)", "Displays a border of the specified color around the texture." }); - args.push_back({ mvPyDataType::FloatList, "uv_min", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "Normalized texture coordinates min point." }); - args.push_back({ mvPyDataType::FloatList, "uv_max", mvArgType::KEYWORD_ARG, "(1.0, 1.0)", "Normalized texture coordinates max point." }); - - setup.about = "Adds an image from a specified texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) for texture coordinates will generally display the entire texture."; - setup.category = { "Widgets", "Textures" }; - break; - } - case mvAppItemType::mvMenuBar: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds a menu bar to a window."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvViewportMenuBar: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds a menubar to the viewport."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvMenu: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_ENABLED) - ); - - setup.about = "Adds a menu to an existing menu bar."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvMenuItem: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_ENABLED) - ); - args.push_back({ mvPyDataType::Callable, "drag_callback", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - args.push_back({ mvPyDataType::Bool, "default_value", mvArgType::KEYWORD_ARG, "False", "This value also controls the checkmark when shown." }); - args.push_back({ mvPyDataType::String, "shortcut", mvArgType::KEYWORD_ARG, "''", "Displays text on the menu item. Typically used to show a shortcut key command." }); - args.push_back({ mvPyDataType::Bool, "check", mvArgType::KEYWORD_ARG, "False", "Displays a checkmark on the menu item when it is selected and placed in a menu." }); - - setup.about = "Adds a menu item to an existing menu. Menu items act similar to selectables and has a bool value. When placed in a menu the checkmark will reflect its value."; - break; - } - case mvAppItemType::mvChildWindow: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "border", mvArgType::KEYWORD_ARG, "True", "Shows/Hides the border around the sides." }); - args.push_back({ mvPyDataType::Bool, "autosize_x", mvArgType::KEYWORD_ARG, "False", "Autosize the window to its parents size in x." }); - args.push_back({ mvPyDataType::Bool, "autosize_y", mvArgType::KEYWORD_ARG, "False", "Autosize the window to its parents size in y." }); - args.push_back({ mvPyDataType::Bool, "no_scrollbar", mvArgType::KEYWORD_ARG, "False", " Disable scrollbars (window can still scroll with mouse or programmatically)." }); - args.push_back({ mvPyDataType::Bool, "horizontal_scrollbar", mvArgType::KEYWORD_ARG, "False", "Allow horizontal scrollbar to appear (off by default)." }); - args.push_back({ mvPyDataType::Bool, "menubar", mvArgType::KEYWORD_ARG, "False", "Shows/Hides the menubar at the top." }); - args.push_back({ mvPyDataType::Bool, "no_scroll_with_mouse", mvArgType::KEYWORD_ARG, "False", "Disable user vertically scrolling with mouse wheel." }); - args.push_back({ mvPyDataType::Bool, "flattened_navigation", mvArgType::KEYWORD_ARG, "True", "Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)" }); - args.push_back({ mvPyDataType::Bool, "always_use_window_padding", mvArgType::KEYWORD_ARG, "False", "Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense)" }); - args.push_back({ mvPyDataType::Bool, "resizable_x", mvArgType::KEYWORD_ARG, "False", "Allow resize from right border (layout direction). Enable .ini saving." }); - args.push_back({ mvPyDataType::Bool, "resizable_y", mvArgType::KEYWORD_ARG, "False", "Allow resize from bottom border (layout direction). " }); - args.push_back({ mvPyDataType::Bool, "always_auto_resize", mvArgType::KEYWORD_ARG, "False", "Combined with auto_resize_x/auto_resize_y. Always measure size even when child is hidden and always disable clipping optimization! NOT RECOMMENDED." }); - args.push_back({ mvPyDataType::Bool, "frame_style", mvArgType::KEYWORD_ARG, "False", "Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding." }); - args.push_back({ mvPyDataType::Bool, "auto_resize_x", mvArgType::KEYWORD_ARG, "False", "Enable auto-resizing width based on child content. Read 'IMPORTANT: Size measurement' details above." }); - args.push_back({ mvPyDataType::Bool, "auto_resize_y", mvArgType::KEYWORD_ARG, "False", "Enable auto-resizing height based on child content. Read 'IMPORTANT: Size measurement' details above." }); - - setup.about = - "Adds an embedded child window. Will show scrollbars when items do not fit. About using auto_resize/resizable flags: " - "size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing and it won't update its auto-size while clipped. " - "While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional 'resizing after becoming visible again' glitch. " - "You may also use always_auto_resize to force an update even when child window is not in view. However doing so will degrade performance. " - "Remember that combining both auto_resize_x and auto_resize_y defeats purpose of a scrolling region and is NOT recommended."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvGroup: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "Forces child widgets to be added in a horizontal layout." }); - args.push_back({ mvPyDataType::Float, "horizontal_spacing", mvArgType::KEYWORD_ARG, "-1", "Spacing for the horizontal layout." }); - args.push_back({ mvPyDataType::Float, "xoffset", mvArgType::KEYWORD_ARG, "0.0", "Offset from containing window x item location within group." }); - - setup.about = "Creates a group that other widgets can belong to. The group allows item commands to be issued for all of its members.\nEnable property acts in a special way enabling/disabling everything inside the group. (Use mvStyleVar_DisabledAlpha to edit colors within the disabled group.)"; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvSliderFloat: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::Bool, "vertical", mvArgType::KEYWORD_ARG, "False", "Sets orientation of the slidebar and slider to vertical." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - - setup.about = "Adds slider for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvSliderDouble: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::Bool, "vertical", mvArgType::KEYWORD_ARG, "False", "Sets orientation of the slidebar and slider to vertical." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - - setup.about = "Adds slider for a single double value. Useful when slider float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvSliderInt: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "default_value", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Bool, "vertical", mvArgType::KEYWORD_ARG, "False", "Sets orientation of the slidebar and slider to vertical." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%d'", "Determines the format the int will be displayed as use python string formatting." }); - - setup.about = "Adds slider for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvFilterSet: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Helper to parse and apply text filters (e.g. aaaaa[, bbbbb][, ccccc])"; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvDragFloat: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag for a single float value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvDragDouble: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag for a single double value. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvDragInt: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "default_value", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%d'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag for a single int value. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvInputFloat: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Float, "step", mvArgType::KEYWORD_ARG, "0.1", "Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Float, "step_fast", mvArgType::KEYWORD_ARG, "1.0", "Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds input for an float. +/- buttons can be activated by setting the value of step."; - break; - } - case mvAppItemType::mvInputDouble: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Double, "step", mvArgType::KEYWORD_ARG, "0.1", "Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Double, "step_fast", mvArgType::KEYWORD_ARG, "1.0", "Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds input for an double. Useful when input float is not accurate enough. +/- buttons can be activated by setting the value of step."; - break; - } - case mvAppItemType::mvInputInt: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "default_value", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Value for lower limit of input. By default this limits the step buttons. Use min_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Value for upper limit of input. By default this limits the step buttons. Use max_clamped to limit manual input." }); - args.push_back({ mvPyDataType::Integer, "step", mvArgType::KEYWORD_ARG, "1", "Increment to change value by when the step buttons are pressed. Setting this and step_fast to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Integer, "step_fast", mvArgType::KEYWORD_ARG, "100", "Increment to change value by when ctrl + step buttons are pressed. Setting this and step to a value of 0 or less will turn off step buttons." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds input for an int. +/- buttons can be activated by setting the value of step."; - break; - } - case mvAppItemType::mvColorEdit: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)" }); - args.push_back({ mvPyDataType::Bool, "no_alpha", mvArgType::KEYWORD_ARG, "False", "Removes the displayed slider that can change alpha channel." }); - args.push_back({ mvPyDataType::Bool, "no_picker", mvArgType::KEYWORD_ARG, "False", "Disable picker popup when color square is clicked." }); - args.push_back({ mvPyDataType::Bool, "no_options", mvArgType::KEYWORD_ARG, "False", "Disable toggling options menu when right-clicking on inputs/small preview." }); - args.push_back({ mvPyDataType::Bool, "no_small_preview", mvArgType::KEYWORD_ARG, "False", "Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown." }); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square)" }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip when hovering the preview." }); - args.push_back({ mvPyDataType::Bool, "no_label", mvArgType::KEYWORD_ARG, "False", "Disable display of inline text label." }); - args.push_back({ mvPyDataType::Bool, "no_drag_drop", mvArgType::KEYWORD_ARG, "False", "Disable ability to drag and drop small preview (color square) to apply colors to other items." }); - args.push_back({ mvPyDataType::Bool, "alpha_bar", mvArgType::KEYWORD_ARG, "False", "Show vertical alpha bar/gradient in picker." }); - args.push_back({ mvPyDataType::Long, "alpha_preview", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_AlphaPreviewNone", "mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf" }); - args.push_back({ mvPyDataType::Long, "display_mode", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_rgb", "mvColorEdit_rgb, mvColorEdit_hsv, or mvColorEdit_hex" }); - args.push_back({ mvPyDataType::Long, "display_type", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_uint8", "mvColorEdit_uint8 or mvColorEdit_float" }); - args.push_back({ mvPyDataType::Long, "input_mode", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_input_rgb", "mvColorEdit_input_* values" }); - - setup.about = "Adds an RGBA color editor. Left clicking the small color preview will provide a color picker. Click and draging the small color preview will copy the color to be applied on any other color widget."; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvClipper: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Helper to manually clip large list of items. Increases performance by not searching or drawing widgets outside of the clipped region."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvColorPicker: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)" }); - args.push_back({ mvPyDataType::Bool, "no_alpha", mvArgType::KEYWORD_ARG, "False", "Removes the displayed slider that can change alpha channel." }); - args.push_back({ mvPyDataType::Bool, "no_side_preview", mvArgType::KEYWORD_ARG, "False", "Disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden." }); - args.push_back({ mvPyDataType::Bool, "no_small_preview", mvArgType::KEYWORD_ARG, "False", "Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown." }); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square)" }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip when hovering the preview." }); - args.push_back({ mvPyDataType::Bool, "no_label", mvArgType::KEYWORD_ARG, "False", "Disable display of inline text label." }); - args.push_back({ mvPyDataType::Bool, "alpha_bar", mvArgType::KEYWORD_ARG, "False", "Show vertical alpha bar/gradient in picker." }); - args.push_back({ mvPyDataType::Bool, "display_rgb", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex." }); - args.push_back({ mvPyDataType::Bool, "display_hsv", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex." }); - args.push_back({ mvPyDataType::Bool, "display_hex", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex." }); - args.push_back({ mvPyDataType::Long, "picker_mode", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorPicker_bar", "mvColorPicker_bar or mvColorPicker_wheel" }); - args.push_back({ mvPyDataType::Long, "alpha_preview", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_AlphaPreviewNone", "mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf" }); - args.push_back({ mvPyDataType::Long, "display_type", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_uint8", "mvColorEdit_uint8 or mvColorEdit_float" }); - args.push_back({ mvPyDataType::Long, "input_mode", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_input_rgb", "mvColorEdit_input_* values."}); - - setup.about = "Adds an RGB color picker. Right click the color picker for options. Click and drag the color preview to copy the color and drop on any other color widget to apply. Right Click allows the style of the color picker to be changed."; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvTooltip: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::UUID, "parent" }); - args.push_back({ mvPyDataType::Float, "delay", mvArgType::KEYWORD_ARG, "0.0", "Activation delay: time, in seconds, during which the mouse should stay still in order to display the tooltip. May be zero for instant activation." }); - args.push_back({ mvPyDataType::Bool, "hide_on_activity", mvArgType::KEYWORD_ARG, "False", "Hide the tooltip if the user has moved the mouse. If False, the tooltip will follow mouse pointer." }); - - setup.about = "Adds a tooltip window."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvCollapsingHeader: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "closable", mvArgType::KEYWORD_ARG, "False", "Adds the ability to hide this widget by pressing the (x) in the top right of widget." }); - args.push_back({ mvPyDataType::Bool, "default_open", mvArgType::KEYWORD_ARG, "False", "Sets the collapseable header open by default." }); - args.push_back({ mvPyDataType::Bool, "open_on_double_click", mvArgType::KEYWORD_ARG, "False", "Need double-click to open node." }); - args.push_back({ mvPyDataType::Bool, "open_on_arrow", mvArgType::KEYWORD_ARG, "False", "Only open when clicking on the arrow part." }); - args.push_back({ mvPyDataType::Bool, "leaf", mvArgType::KEYWORD_ARG, "False", "No collapsing, no arrow (use as a convenience for leaf nodes)." }); - args.push_back({ mvPyDataType::Bool, "bullet", mvArgType::KEYWORD_ARG, "False", "Display a bullet instead of arrow." }); - - setup.about = "Adds a collapsing header to add items to. Must be closed with the end command."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvSeparator: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_POS) - ); - - setup.about = "Adds a horizontal line separator. Use 'label' parameter to add text and mvStyleVar_SeparatorText* elements to style it."; - break; - } - case mvAppItemType::mvListbox: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::StringList, "items", mvArgType::POSITIONAL_ARG, "()", "A tuple of items to be shown in the listbox. Can consist of any combination of types. All items will be displayed as strings." }); - args.push_back({ mvPyDataType::String, "default_value", mvArgType::KEYWORD_ARG, "''", "String value of the item that will be selected by default." }); - args.push_back({ mvPyDataType::Integer, "num_items", mvArgType::KEYWORD_ARG, "3", "Expands the height of the listbox to show specified number of items." }); - - - setup.about = "Adds a listbox. If height is not large enough to show all items a scroll bar will appear."; - break; - } - case mvAppItemType::mvText: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::String, "default_value", mvArgType::POSITIONAL_ARG, "''" }); - args.push_back({ mvPyDataType::Integer, "wrap", mvArgType::KEYWORD_ARG, "-1", "Number of pixels from the start of the item until wrapping starts." }); - args.push_back({ mvPyDataType::Bool, "bullet", mvArgType::KEYWORD_ARG, "False", "Places a bullet to the left of the text." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(-255, 0, 0, 255)", "Color of the text (rgba)." }); - args.push_back({ mvPyDataType::Bool, "show_label", mvArgType::KEYWORD_ARG, "False", "Displays the label to the right of the text." }); - - setup.about = "Adds text. Text can have an optional label that will display to the right of the text."; - break; - } - case mvAppItemType::mvPlot: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - // plot flags - args.push_back({ mvPyDataType::Bool, "no_title", mvArgType::KEYWORD_ARG, "False", "the plot title will not be displayed"}); - args.push_back({ mvPyDataType::Bool, "no_menus", mvArgType::KEYWORD_ARG, "False", "the user will not be able to open context menus with right-click"}); - args.push_back({ mvPyDataType::Bool, "no_box_select", mvArgType::KEYWORD_ARG, "False", "the user will not be able to box-select with right-click drag"}); - args.push_back({ mvPyDataType::Bool, "no_mouse_pos", mvArgType::KEYWORD_ARG, "False", "the text of mouse position, in plot coordinates, will not be displayed inside of the plot"}); - args.push_back({ mvPyDataType::Bool, "no_highlight", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "False", "Removed because not supported from the backend anymore. To control the highlighting of series use the same argument in `add_plot_legend`"}); - args.push_back({ mvPyDataType::Bool, "no_child", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "False", "a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications)"}); - args.push_back({ mvPyDataType::Bool, "query", mvArgType::KEYWORD_ARG, "False", "the user will be able to draw query rects with CTRL + right-click drag"}); - args.push_back({ mvPyDataType::FloatList, "query_color", mvArgType::KEYWORD_ARG, "(0, 255, 0, 255)", "Color of the query rectangles." }); - args.push_back({ mvPyDataType::Integer, "min_query_rects", mvArgType::KEYWORD_ARG, "1", "The minimum number of query rects that can be in the plot. If there are less rects than this value, it won't be possible to delete them." }); - args.push_back({ mvPyDataType::Integer, "max_query_rects", mvArgType::KEYWORD_ARG, "1", "The maximum number of query rects that can be in the plot. If the number is reached any rect added will replace the latest one. (0 means unlimited)" }); - args.push_back({ mvPyDataType::Bool, "crosshairs", mvArgType::KEYWORD_ARG, "False", "the default mouse cursor will be replaced with a crosshair when hovered"}); - args.push_back({ mvPyDataType::Bool, "anti_aliased", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "True", "This feature was deprecated in ImPlot. To enable/disable anti_aliasing use `dpg.configure_app()` with the `anti_aliasing` parameters."}); - args.push_back({ mvPyDataType::Bool, "equal_aspects", mvArgType::KEYWORD_ARG, "False", "primary x and y axes will be constrained to have the same units/pixel (does not apply to auxiliary y-axes)"}); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "the user will not be able to interact with the plot"}); - args.push_back({ mvPyDataType::Bool, "no_frame", mvArgType::KEYWORD_ARG, "False", "the ImGui frame will not be rendered"}); - // args.push_back({ mvPyDataType::Bool, "canvas_only", mvArgType::KEYWORD_ARG, "False", "shortcut for: no_title + no_legend + no_menu + no_box_select + no_mouse_pos"}); - args.push_back({ mvPyDataType::Bool, "use_local_time", mvArgType::KEYWORD_ARG, "False", "axis labels will be formatted for your timezone when" }); - args.push_back({ mvPyDataType::Bool, "use_ISO8601", mvArgType::KEYWORD_ARG, "False", "dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.)" }); - args.push_back({ mvPyDataType::Bool, "use_24hour_clock", mvArgType::KEYWORD_ARG, "False", "times will be formatted using a 24 hour clock" }); - - // key modifiers - args.push_back({ mvPyDataType::Integer, "pan_button", mvArgType::KEYWORD_ARG, "internal_dpg.mvMouseButton_Left", "mouse button that enables panning when held" }); - args.push_back({ mvPyDataType::Integer, "pan_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_None", "optional modifier that must be held for panning" }); - args.push_back({ mvPyDataType::Integer, "context_menu_button", mvArgType::KEYWORD_ARG, "internal_dpg.mvMouseButton_Right", "opens context menus (if enabled) when clicked" }); - args.push_back({ mvPyDataType::Integer, "fit_button", mvArgType::KEYWORD_ARG, "internal_dpg.mvMouseButton_Left", "fits visible data when double clicked" }); - args.push_back({ mvPyDataType::Integer, "box_select_button", mvArgType::KEYWORD_ARG, "internal_dpg.mvMouseButton_Right", "begins box selection when pressed and confirms selection when released" }); - args.push_back({ mvPyDataType::Integer, "box_select_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_None", "begins box selection when pressed and confirms selection when released" }); - args.push_back({ mvPyDataType::Integer, "box_select_cancel_button", mvArgType::KEYWORD_ARG, "internal_dpg.mvMouseButton_Left", "cancels active box selection when pressed" }); - args.push_back({ mvPyDataType::Integer, "query_toggle_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_ModCtrl", "when held, active box selections turn into queries" }); - args.push_back({ mvPyDataType::Integer, "horizontal_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_ModAlt", "expands active box selection/query horizontally to plot edge when held" }); - args.push_back({ mvPyDataType::Integer, "vertical_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_ModShift", "expands active box selection/query vertically to plot edge when held" }); - args.push_back({ mvPyDataType::Integer, "override_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_ModCtrl", "when held, all input is ignored; used to enable axis/plots as DND sources" }); - args.push_back({ mvPyDataType::Integer, "zoom_mod", mvArgType::KEYWORD_ARG, "internal_dpg.mvKey_None", "optional modifier that must be held for scroll wheel zooming" }); - args.push_back({ mvPyDataType::Integer, "zoom_rate", mvArgType::KEYWORD_ARG, "0.1", "zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert" }); - args.push_back({ mvPyDataType::Integer, "query_button", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "0", "This refers to the old way of querying of ImPlot, now replaced with `DragRect()`" }); - args.push_back({ mvPyDataType::Integer, "query_mod", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG, "internal_dpg.mvKey_None", "This refers to the old way of querying of ImPlot, now replaced with `DragRect()`" }); - - setup.about = "Adds a plot which is used to hold series, and can be drawn to with draw commands. For all _mod parameters use mvKey_ModX enums, or mvKey_ModDisabled to disable the modifier."; - setup.category = { "Plotting", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvSimplePlot: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "()" }); - args.push_back({ mvPyDataType::String, "overlay", mvArgType::KEYWORD_ARG, "''", "overlays text (similar to a plot title)" }); - args.push_back({ mvPyDataType::Bool, "histogram", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "autosize", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Float, "min_scale", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::Float, "max_scale", mvArgType::KEYWORD_ARG, "0.0" }); - - setup.about = "Adds a simple plot for visualization of a 1 dimensional set of values."; - setup.category = { "Plotting", "Widgets" }; - break; - } - case mvAppItemType::mvDrawlist: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "width" }); - args.push_back({ mvPyDataType::Integer, "height" }); - - setup.about = "Adds a drawing canvas."; - setup.category = { "Drawlist", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvWindowAppItem: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "min_size", mvArgType::KEYWORD_ARG, "[100, 100]", "Minimum window size." }); - args.push_back({ mvPyDataType::IntList, "max_size", mvArgType::KEYWORD_ARG, "[30000, 30000]", "Maximum window size." }); - args.push_back({ mvPyDataType::Bool, "menubar", mvArgType::KEYWORD_ARG, "False", "Shows or hides the menubar." }); - args.push_back({ mvPyDataType::Bool, "collapsed", mvArgType::KEYWORD_ARG, "False", "Collapse the window." }); - args.push_back({ mvPyDataType::Bool, "autosize", mvArgType::KEYWORD_ARG, "False", "Autosized the window to fit it's items." }); - args.push_back({ mvPyDataType::Bool, "no_resize", mvArgType::KEYWORD_ARG, "False", "Allows for the window size to be changed or fixed." }); - args.push_back({ mvPyDataType::Bool, "unsaved_document", mvArgType::KEYWORD_ARG, "False", "Show a special marker if the document is not saved." }); - args.push_back({ mvPyDataType::Bool, "no_title_bar", mvArgType::KEYWORD_ARG, "False", "Title name for the title bar of the window." }); - args.push_back({ mvPyDataType::Bool, "no_move", mvArgType::KEYWORD_ARG, "False", "Allows for the window's position to be changed or fixed." }); - args.push_back({ mvPyDataType::Bool, "no_scrollbar", mvArgType::KEYWORD_ARG, "False", " Disable scrollbars. (window can still scroll with mouse or programmatically)" }); - args.push_back({ mvPyDataType::Bool, "no_collapse", mvArgType::KEYWORD_ARG, "False", "Disable user collapsing window by double-clicking on it." }); - args.push_back({ mvPyDataType::Bool, "horizontal_scrollbar", mvArgType::KEYWORD_ARG, "False", "Allow horizontal scrollbar to appear. (off by default)" }); - args.push_back({ mvPyDataType::Bool, "no_focus_on_appearing", mvArgType::KEYWORD_ARG, "False", "Disable taking focus when transitioning from hidden to visible state." }); - args.push_back({ mvPyDataType::Bool, "no_bring_to_front_on_focus", mvArgType::KEYWORD_ARG, "False", "Disable bringing window to front when taking focus. (e.g. clicking on it or programmatically giving it focus)" }); - args.push_back({ mvPyDataType::Bool, "no_close", mvArgType::KEYWORD_ARG, "False", "Disable user closing the window by removing the close button." }); - args.push_back({ mvPyDataType::Bool, "no_background", mvArgType::KEYWORD_ARG, "False", "Sets Background and border alpha to transparent." }); - args.push_back({ mvPyDataType::Bool, "modal", mvArgType::KEYWORD_ARG, "False", "Fills area behind window according to the theme and disables user ability to interact with anything except the window." }); - args.push_back({ mvPyDataType::Bool, "popup", mvArgType::KEYWORD_ARG, "False", "Fills area behind window according to the theme, removes title bar, collapse and close. Window can be closed by selecting area in the background behind the window." }); - args.push_back({ mvPyDataType::Bool, "no_saved_settings", mvArgType::KEYWORD_ARG, "False", "Never load/save settings in .ini file." }); - args.push_back({ mvPyDataType::Bool, "no_open_over_existing_popup", mvArgType::KEYWORD_ARG, "True", "Don't open if there's already a popup" }); - args.push_back({ mvPyDataType::Bool, "no_scroll_with_mouse", mvArgType::KEYWORD_ARG, "False", "Disable user vertically scrolling with mouse wheel." }); - args.push_back({ mvPyDataType::Bool, "no_docking", mvArgType::KEYWORD_ARG, "False", "Disable docking of this window" }); - - args.push_back({ mvPyDataType::Bool, "copy_contents_shortcut", mvArgType::KEYWORD_ARG, "False", "Experimental. If True, window contents can be copied to clipboard by pressing Ctrl+C. Might be useful for message boxes." }); - - args.push_back({ mvPyDataType::Callable, "on_close", mvArgType::KEYWORD_ARG, "None", "Callback ran when window is closed." }); - - setup.about = "Creates a new window for following items to be added to."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvSelectable: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "default_value", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Bool, "span_columns", mvArgType::KEYWORD_ARG, "False", "Forces the selectable to span the width of all columns if placed in a table." }); - args.push_back({ mvPyDataType::Bool, "disable_popup_close", mvArgType::KEYWORD_ARG, "False", "Disable closing a modal or popup window." }); - args.push_back({ mvPyDataType::Bool, "select_on_nav", mvArgType::KEYWORD_ARG, "False", "Auto-select when moved into with keyboard navigation, unless Ctrl is held." }); - - setup.about = "Adds a selectable. Similar to a button but can indicate its selected state."; - break; - } - case mvAppItemType::mvTreeNode: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "default_open", mvArgType::KEYWORD_ARG, "False", "Sets the tree node open by default." }); - args.push_back({ mvPyDataType::Bool, "open_on_double_click", mvArgType::KEYWORD_ARG, "False", "Need double-click to open node." }); - args.push_back({ mvPyDataType::Bool, "open_on_arrow", mvArgType::KEYWORD_ARG, "False", "Only open when clicking on the arrow part." }); - args.push_back({ mvPyDataType::Bool, "leaf", mvArgType::KEYWORD_ARG, "False", "No collapsing, no arrow (use as a convenience for leaf nodes)." }); - args.push_back({ mvPyDataType::Bool, "bullet", mvArgType::KEYWORD_ARG, "False", "Display a bullet instead of arrow." }); - args.push_back({ mvPyDataType::Bool, "selectable", mvArgType::KEYWORD_ARG, "False", "Makes the tree selectable." }); - args.push_back({ mvPyDataType::Bool, "span_text_width", mvArgType::KEYWORD_ARG, "False", "Makes hitbox and highlight only cover the label." }); - args.push_back({ mvPyDataType::Bool, "span_full_width", mvArgType::KEYWORD_ARG, "False", "Extend hit box to the left-most and right-most edges (cover the indent area)." }); - args.push_back({ mvPyDataType::Bool, "catch_nav_left", mvArgType::KEYWORD_ARG, "False", - "Keyboard navigation: left arrow within this node's children, if unhandled, " - "moves focus to this node. When setting it to True on a node, better set it " - "on all children nodes in the subtree as well, otherwise it might give unexpected " - "navigation jumps."}); - // TODO: Test these 2 arguments - // args.push_back({ mvPyDataType::Bool, "span_available_width", mvArgType::KEYWORD_ARG, "False", "Extend hit box to the right-most edge, even if not framed." }); - // args.push_back({ mvPyDataType::Bool, "span_all_columns", mvArgType::KEYWORD_ARG, "False", "Frame will span all columns of its container table (text will still fit in current column)." }); - args.push_back({ mvPyDataType::Integer, "lines", mvArgType::KEYWORD_ARG, "internal_dpg.mvTreeLines_None", - "Experimental. Draw lines connecting tree_node hierarchy. One of dpg.mvTreeLines " - "constants. To work correctly, must be configured the same way in every tree node." }); - - setup.about = "Adds a tree node to add items to."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvProgressBar: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::String, "overlay", mvArgType::KEYWORD_ARG, "''", "Overlayed text onto the bar that typically used to display the value of the progress." }); - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0", "Normalized value to fill the bar from 0.0 to 1.0. Put a negative value to show an indeterminate progress bar." }); - - setup.about = "Adds a progress bar."; - break; - } - case mvAppItemType::mvSpacer: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_POS) - ); - - setup.about = "Adds a spacer item that can be used to help with layouts or can be used as a placeholder item."; - break; - } - case mvAppItemType::mvImageButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::UUID, "texture_tag", mvArgType::REQUIRED_ARG, "", "The texture_tag should come from a texture that was added to a texture registry." }); - args.push_back({ mvPyDataType::Integer, "frame_padding", mvArgType::DEPRECATED_KEYWORD_ARG, "-1", "Empty space around the outside of the texture. Button will show around the texture.", "This is not supported anymore by ImGui but still used here as deprecated." }); - args.push_back({ mvPyDataType::FloatList, "tint_color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)", "Applies a color tint to the entire texture." }); - args.push_back({ mvPyDataType::FloatList, "background_color", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)", "Displays a border of the specified color around the texture." }); - args.push_back({ mvPyDataType::FloatList, "uv_min", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "Normalized texture coordinates min point." }); - args.push_back({ mvPyDataType::FloatList, "uv_max", mvArgType::KEYWORD_ARG, "(1.0, 1.0)", "Normalized texture coordinates max point." }); - - setup.about = "Adds an button with a texture. uv_min and uv_max represent the normalized texture coordinates of the original image that will be shown. Using range (0.0,0.0)->(1.0,1.0) texture coordinates will generally display the entire texture"; - setup.category = { "Widgets", "Textures" }; - break; - } - case mvAppItemType::mvTimePicker: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Dict, "default_value", mvArgType::KEYWORD_ARG, "{'hour': 14, 'min': 32, 'sec': 23}" }); - args.push_back({ mvPyDataType::Bool, "hour24", mvArgType::KEYWORD_ARG, "False", "Show 24 hour clock instead of 12 hour." }); - - setup.about = "Adds a time picker."; - break; - } - case mvAppItemType::mvDatePicker: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Dict, "default_value", mvArgType::KEYWORD_ARG, "{'month_day': 14, 'year':20, 'month':5}" }); - args.push_back({ mvPyDataType::Integer, "level", mvArgType::KEYWORD_ARG, "0", "Use avaliable constants. mvDatePickerLevel_Day, mvDatePickerLevel_Month, mvDatePickerLevel_Year" }); - - setup.about = "Adds a date picker."; - break; - } - case mvAppItemType::mvColorButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)" }); - args.push_back({ mvPyDataType::Bool, "no_alpha", mvArgType::KEYWORD_ARG, "False", "Removes the displayed slider that can change alpha channel." }); - args.push_back({ mvPyDataType::Bool, "no_border", mvArgType::KEYWORD_ARG, "False", "Disable border around the image." }); - args.push_back({ mvPyDataType::Bool, "no_drag_drop", mvArgType::KEYWORD_ARG, "False", "Disable ability to drag and drop small preview (color square) to apply colors to other items." }); - args.push_back({ mvPyDataType::Long, "alpha_preview", mvArgType::KEYWORD_ARG, "internal_dpg.mvColorEdit_AlphaPreviewNone", "mvColorEdit_AlphaPreviewNone, mvColorEdit_AlphaPreview, or mvColorEdit_AlphaPreviewHalf" }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip when hovering the button." }); - - setup.about = "Adds a color button."; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvFileDialog: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::String, "default_path", mvArgType::KEYWORD_ARG, "''", "Path that the file dialog will default to when opened." }); - args.push_back({ mvPyDataType::String, "default_filename", mvArgType::KEYWORD_ARG, "'.'", "Default name that will show in the file name input." }); - args.push_back({ mvPyDataType::Integer, "file_count", mvArgType::KEYWORD_ARG, "0", "Number of visible files in the dialog." }); - args.push_back({ mvPyDataType::Bool, "modal", mvArgType::KEYWORD_ARG, "False", "Forces user interaction with the file selector." }); - args.push_back({ mvPyDataType::Bool, "directory_selector", mvArgType::KEYWORD_ARG, "False", "Shows only directory/paths as options. Allows selection of directory/paths only." }); - args.push_back({ mvPyDataType::IntList, "min_size", mvArgType::KEYWORD_ARG, "[100, 100]", "Minimum window size." }); - args.push_back({ mvPyDataType::IntList, "max_size", mvArgType::KEYWORD_ARG, "[30000, 30000]", "Maximum window size." }); - args.push_back({ mvPyDataType::Callable, "cancel_callback", mvArgType::KEYWORD_ARG, "None", "Callback called when cancel button is clicked." }); - - setup.about = "Displays a file or directory selector depending on keywords. Displays a file dialog by default. Callback will be ran when the file or directory picker is closed. The app_data arguemnt will be populated with information related to the file and directory as a dictionary."; - setup.category = { "Containers", "Widgets", "File Dialog" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTabButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Bool, "no_reorder", mvArgType::KEYWORD_ARG, "False", "Disable reordering this tab or having another tab cross over this tab. Fixes the position of this tab in relation to the order of neighboring tabs at start. " }); - args.push_back({ mvPyDataType::Bool, "leading", mvArgType::KEYWORD_ARG, "False", "Enforce the tab position to the left of the tab bar (after the tab list popup button)." }); - args.push_back({ mvPyDataType::Bool, "trailing", mvArgType::KEYWORD_ARG, "False", "Enforce the tab position to the right of the tab bar (before the scrolling buttons)." }); - args.push_back({ mvPyDataType::Bool, "no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip for the given tab." }); - args.push_back({ mvPyDataType::Bool, "unsaved_document", mvArgType::KEYWORD_ARG, "False", "Display a dot next to the title." }); - - setup.about = "Adds a tab button to a tab bar."; - break; - } - case mvAppItemType::mvDrawNode: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "New in 1.1. Creates a drawing node to associate a transformation matrix. Child node matricies will concatenate."; - setup.category = { "Drawlist", "Widgets", "Matrix Operations" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvNodeEditor: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Callable, "delink_callback", mvArgType::KEYWORD_ARG, "None", "Callback ran when a link is detached." }); - args.push_back({ mvPyDataType::Bool, "menubar", mvArgType::KEYWORD_ARG, "False", "Shows or hides the menubar." }); - args.push_back({ mvPyDataType::Bool, "minimap", mvArgType::KEYWORD_ARG, "False", "Shows or hides the Minimap. New in 1.6." }); - args.push_back({ mvPyDataType::Integer, "minimap_location", mvArgType::KEYWORD_ARG, "2", "mvNodeMiniMap_Location_* constants. New in 1.6." }); - - setup.about = "Adds a node editor."; - setup.category = { "Node Editor", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvNode: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_POS | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Bool, "draggable", mvArgType::KEYWORD_ARG, "True", "Allow node to be draggable." }); - - setup.about = "Adds a node to a node editor."; - setup.category = { "Node Editor", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvNodeAttribute: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Long, "attribute_type", mvArgType::KEYWORD_ARG, "0", "mvNode_Attr_Input, mvNode_Attr_Output, or mvNode_Attr_Static." }); - args.push_back({ mvPyDataType::Integer, "shape", mvArgType::KEYWORD_ARG, "1", "Pin shape." }); - args.push_back({ mvPyDataType::String, "category", mvArgType::KEYWORD_ARG, "'general'", "Category" }); - - setup.about = "Adds a node attribute to a node."; - setup.category = { "Node Editor", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTable: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Bool, "header_row", mvArgType::KEYWORD_ARG, "True", "show headers at the top of the columns" }); - args.push_back({ mvPyDataType::Bool, "clipper", mvArgType::KEYWORD_ARG, "False", "Use clipper (rows must be same height)." }); - args.push_back({ mvPyDataType::Integer, "inner_width", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Integer, "policy", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Integer, "freeze_rows", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Integer, "freeze_columns", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::Bool, "sort_multi", mvArgType::KEYWORD_ARG, "False", "Hold shift when clicking headers to sort on multiple column." }); - args.push_back({ mvPyDataType::Bool, "sort_tristate", mvArgType::KEYWORD_ARG, "False", "Allow no sorting, disable default sorting." }); - args.push_back({ mvPyDataType::Bool, "resizable", mvArgType::KEYWORD_ARG, "False", "Enable resizing columns" }); - args.push_back({ mvPyDataType::Bool, "reorderable", mvArgType::KEYWORD_ARG, "False", "Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)" }); - args.push_back({ mvPyDataType::Bool, "hideable", mvArgType::KEYWORD_ARG, "False", "Enable hiding/disabling columns in context menu." }); - args.push_back({ mvPyDataType::Bool, "sortable", mvArgType::KEYWORD_ARG, "False", "Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate." }); - args.push_back({ mvPyDataType::Bool, "context_menu_in_body", mvArgType::KEYWORD_ARG, "False", "Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow()." }); - args.push_back({ mvPyDataType::Bool, "row_background", mvArgType::KEYWORD_ARG, "False", "Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually)" }); - args.push_back({ mvPyDataType::Bool, "borders_innerH", mvArgType::KEYWORD_ARG, "False", "Draw horizontal borders between rows." }); - args.push_back({ mvPyDataType::Bool, "borders_outerH", mvArgType::KEYWORD_ARG, "False", "Draw horizontal borders at the top and bottom." }); - args.push_back({ mvPyDataType::Bool, "borders_innerV", mvArgType::KEYWORD_ARG, "False", "Draw vertical borders between columns." }); - args.push_back({ mvPyDataType::Bool, "borders_outerV", mvArgType::KEYWORD_ARG, "False", "Draw vertical borders on the left and right sides." }); - args.push_back({ mvPyDataType::Bool, "no_host_extendX", mvArgType::KEYWORD_ARG, "False", "Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used." }); - args.push_back({ mvPyDataType::Bool, "no_host_extendY", mvArgType::KEYWORD_ARG, "False", "Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible." }); - args.push_back({ mvPyDataType::Bool, "no_keep_columns_visible", mvArgType::KEYWORD_ARG, "False", "Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable." }); - args.push_back({ mvPyDataType::Bool, "precise_widths", mvArgType::KEYWORD_ARG, "False", "Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth." }); - args.push_back({ mvPyDataType::Bool, "no_clip", mvArgType::KEYWORD_ARG, "False", "Disable clipping rectangle for every individual columns." }); - args.push_back({ mvPyDataType::Bool, "pad_outerX", mvArgType::KEYWORD_ARG, "False", "Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers." }); - args.push_back({ mvPyDataType::Bool, "no_pad_outerX", mvArgType::KEYWORD_ARG, "False", "Default if BordersOuterV is off. Disable outer-most padding." }); - args.push_back({ mvPyDataType::Bool, "no_pad_innerX", mvArgType::KEYWORD_ARG, "False", "Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)." }); - args.push_back({ mvPyDataType::Bool, "scrollX", mvArgType::KEYWORD_ARG, "False", "Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX." }); - args.push_back({ mvPyDataType::Bool, "scrollY", mvArgType::KEYWORD_ARG, "False", "Enable vertical scrolling." }); - args.push_back({ mvPyDataType::Bool, "no_saved_settings", mvArgType::KEYWORD_ARG, "False", "Never load/save settings in .ini file." }); - - setup.about = "Adds a table."; - setup.category = { "Tables", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTableColumn: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Float, "init_width_or_weight", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::Bool, "default_hide", mvArgType::KEYWORD_ARG, "False", "Default as a hidden/disabled column." }); - args.push_back({ mvPyDataType::Bool, "default_sort", mvArgType::KEYWORD_ARG, "False", "Default as a sorting column." }); - args.push_back({ mvPyDataType::Bool, "width_stretch", mvArgType::KEYWORD_ARG, "False", "Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp)." }); - args.push_back({ mvPyDataType::Bool, "width_fixed", mvArgType::KEYWORD_ARG, "False", "Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable)." }); - args.push_back({ mvPyDataType::Bool, "no_resize", mvArgType::KEYWORD_ARG, "False", "Disable manual resizing." }); - args.push_back({ mvPyDataType::Bool, "no_reorder", mvArgType::KEYWORD_ARG, "False", "Disable manual reordering this column, this will also prevent other columns from crossing over this column." }); - args.push_back({ mvPyDataType::Bool, "no_hide", mvArgType::KEYWORD_ARG, "False", "Disable ability to hide/disable this column." }); - args.push_back({ mvPyDataType::Bool, "no_clip", mvArgType::KEYWORD_ARG, "False", "Disable clipping for this column (all NoClip columns will render in a same draw command)." }); - args.push_back({ mvPyDataType::Bool, "no_sort", mvArgType::KEYWORD_ARG, "False", "Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table)." }); - args.push_back({ mvPyDataType::Bool, "no_sort_ascending", mvArgType::KEYWORD_ARG, "False", "Disable ability to sort in the ascending direction." }); - args.push_back({ mvPyDataType::Bool, "no_sort_descending", mvArgType::KEYWORD_ARG, "False", "Disable ability to sort in the descending direction." }); - args.push_back({ mvPyDataType::Bool, "no_header_width", mvArgType::KEYWORD_ARG, "False", "Disable header text width contribution to automatic column width." }); - args.push_back({ mvPyDataType::Bool, "prefer_sort_ascending", mvArgType::KEYWORD_ARG, "True", "Make the initial sort direction Ascending when first sorting on this column (default)." }); - args.push_back({ mvPyDataType::Bool, "prefer_sort_descending", mvArgType::KEYWORD_ARG, "False", "Make the initial sort direction Descending when first sorting on this column." }); - args.push_back({ mvPyDataType::Bool, "indent_enable", mvArgType::KEYWORD_ARG, "False", "Use current Indent value when entering cell (default for column 0)." }); - args.push_back({ mvPyDataType::Bool, "indent_disable", mvArgType::KEYWORD_ARG, "False", "Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored." }); - args.push_back({ mvPyDataType::Bool, "angled_header", mvArgType::KEYWORD_ARG, "False", "Set this parameter to True to display the header text for this column in an angled (diagonal) orientation. This will add an additional row to accommodate the angled text." }); - args.push_back({ mvPyDataType::Bool, "no_header_label", mvArgType::KEYWORD_ARG, "False", "Disable horizontal label for this column. Name will still appear in context menu or in angled headers." }); - - setup.about = "Adds a table column."; - setup.category = { "Tables", "Widgets" }; - break; - } - case mvAppItemType::mvTableRow: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SHOW) - ); - setup.about = "Adds a table row."; - setup.category = { "Tables", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvSyncedTables: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SHOW) - ); - - setup.about = - "Links all tables that are immediate children of this container so that they share " - "their state (mostly column sizes). Other children are rendered as is. This is " - "an experimental feature, use with caution."; - setup.category = { "Tables", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvDrawLine: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1", mvArgType::REQUIRED_ARG, "...", "Start of line." }); - args.push_back({ mvPyDataType::FloatList, "p2", mvArgType::REQUIRED_ARG, "...", "End of line." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - - setup.about = "Adds a line."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawArrow: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1", mvArgType::REQUIRED_ARG, "...", "Arrow tip." }); - args.push_back({ mvPyDataType::FloatList, "p2", mvArgType::REQUIRED_ARG, "...", "Arrow tail." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4" }); - - setup.about = "Adds an arrow."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawTriangle: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1" }); - args.push_back({ mvPyDataType::FloatList, "p2" }); - args.push_back({ mvPyDataType::FloatList, "p3" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - - setup.about = "Adds a triangle."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawImageQuad: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::UUID, "texture_tag" }); - args.push_back({ mvPyDataType::FloatList, "p1" }); - args.push_back({ mvPyDataType::FloatList, "p2" }); - args.push_back({ mvPyDataType::FloatList, "p3" }); - args.push_back({ mvPyDataType::FloatList, "p4" }); - args.push_back({ mvPyDataType::FloatList, "uv1", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::FloatList, "uv2", mvArgType::KEYWORD_ARG, "(1.0, 0.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::FloatList, "uv3", mvArgType::KEYWORD_ARG, "(1.0, 1.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::FloatList, "uv4", mvArgType::KEYWORD_ARG, "(0.0, 1.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - - setup.about = "Adds an image (for a drawing)."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawCircle: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "center" }); - args.push_back({ mvPyDataType::Float, "radius" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Integer, "segments", mvArgType::KEYWORD_ARG, "0", "Number of segments to approximate circle." }); - - setup.about = "Adds a circle"; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawEllipse: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "pmin", mvArgType::REQUIRED_ARG, "...", "Min point of bounding rectangle." }); - args.push_back({ mvPyDataType::FloatList, "pmax", mvArgType::REQUIRED_ARG, "...", "Max point of bounding rectangle." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Integer, "segments", mvArgType::KEYWORD_ARG, "32", "Number of segments to approximate bezier curve." }); - - setup.about = "Adds an ellipse."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawBezierCubic: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1", mvArgType::REQUIRED_ARG, "...", "First point in curve." }); - args.push_back({ mvPyDataType::FloatList, "p2", mvArgType::REQUIRED_ARG, "...", "Second point in curve." }); - args.push_back({ mvPyDataType::FloatList, "p3", mvArgType::REQUIRED_ARG, "...", "Third point in curve." }); - args.push_back({ mvPyDataType::FloatList, "p4", mvArgType::REQUIRED_ARG, "...", "Fourth point in curve." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Integer, "segments", mvArgType::KEYWORD_ARG, "0", "Number of segments to approximate bezier curve." }); - - setup.about = "Adds a cubic bezier curve."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawBezierQuadratic: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1", mvArgType::REQUIRED_ARG, "...", "First point in curve." }); - args.push_back({ mvPyDataType::FloatList, "p2", mvArgType::REQUIRED_ARG, "...", "Second point in curve." }); - args.push_back({ mvPyDataType::FloatList, "p3", mvArgType::REQUIRED_ARG, "...", "Third point in curve." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Integer, "segments", mvArgType::KEYWORD_ARG, "0", "Number of segments to approximate bezier curve." }); - - setup.about = "Adds a quadratic bezier curve."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawQuad: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "p1" }); - args.push_back({ mvPyDataType::FloatList, "p2" }); - args.push_back({ mvPyDataType::FloatList, "p3" }); - args.push_back({ mvPyDataType::FloatList, "p4" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - - setup.about = "Adds a quad."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawRect: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "pmin", mvArgType::REQUIRED_ARG, "...", "Min point of bounding rectangle." }); - args.push_back({ mvPyDataType::FloatList, "pmax", mvArgType::REQUIRED_ARG, "...", "Max point of bounding rectangle." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "color_upper_left", mvArgType::DEPRECATED_KEYWORD_ARG, "(255, 255, 255, 255)", "Use corner_colors instead", "Use corner_colors instead." }); - args.push_back({ mvPyDataType::IntList, "color_upper_right", mvArgType::DEPRECATED_KEYWORD_ARG, "(255, 255, 255, 255)", "Use corner_colors instead", "Use corner_colors instead." }); - args.push_back({ mvPyDataType::IntList, "color_bottom_right", mvArgType::DEPRECATED_KEYWORD_ARG, "(255, 255, 255, 255)", "Use corner_colors instead", "Use corner_colors instead." }); - args.push_back({ mvPyDataType::IntList, "color_bottom_left", mvArgType::DEPRECATED_KEYWORD_ARG, "(255, 255, 255, 255)", "Use corner_colors instead", "Use corner_colors instead." }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Bool, "multicolor", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::Float, "rounding", mvArgType::KEYWORD_ARG, "0.0", "Number of pixels of the radius that will round the corners of the rectangle. Note: doesn't work with multicolor" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::ListListInt, "corner_colors", mvArgType::KEYWORD_ARG, "None", "Corner colors in a list, starting with upper-left and going clockwise: (upper-left, upper-right, bottom-right, bottom-left). 'multicolor' must be set to 'True'." }); - - setup.about = "Adds a rectangle."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawText: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::FloatList, "pos", mvArgType::REQUIRED_ARG, "...", "Top left point of bounding text rectangle." }); - args.push_back({ mvPyDataType::String, "text", mvArgType::REQUIRED_ARG, "...", "Text to draw." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "size", mvArgType::KEYWORD_ARG, "10.0" }); - - setup.about = "Adds text (drawlist)."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawPolygon: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::ListFloatList, "points" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - - setup.about = "Adds a polygon."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawPolyline: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::ListFloatList, "points" }); - args.push_back({ mvPyDataType::Bool, "closed", mvArgType::KEYWORD_ARG, "False", "Will close the polyline by returning to the first point." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - - setup.about = "Adds a polyline."; - setup.category = { "Drawlist", "Widgets" }; - break; - } - case mvAppItemType::mvDrawImage: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::UUID, "texture_tag" }); - args.push_back({ mvPyDataType::FloatList, "pmin", mvArgType::REQUIRED_ARG, "...", "Point of to start drawing texture." }); - args.push_back({ mvPyDataType::FloatList, "pmax", mvArgType::REQUIRED_ARG, "...", "Point to complete drawing texture." }); - args.push_back({ mvPyDataType::FloatList, "uv_min", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::FloatList, "uv_max", mvArgType::KEYWORD_ARG, "(1.0, 1.0)", "Normalized coordinates on texture that will be drawn." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - - setup.about = "Adds an image (for a drawing)."; - setup.category = { "Drawlist", "Widgets", "Textures" }; - break; - } - case mvAppItemType::mvDragFloatMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of floats to be displayed." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag input for a set of float values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - setup.category = { "Widgets" }; - break; - } - case mvAppItemType::mvDragDoubleMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of doubles to be displayed." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag input for a set of double values up to 4. Useful when drag float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - setup.category = { "Widgets" }; - break; - } - case mvAppItemType::mvDragIntMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of ints to be displayed." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%d'", "Determines the format the int will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Sets the sensitivity the float will be modified while dragging." }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Applies a limit only to draging entry only." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods or Enter key allowing to input text directly into the widget." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - - setup.about = "Adds drag input for a set of int values up to 4. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the drag. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvSliderFloatMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of floats to be displayed." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the int will be displayed as use python string formatting." }); - - setup.about = "Adds multi slider for up to 4 float values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvSliderDoubleMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of doubles to be displayed." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the int will be displayed as use python string formatting." }); - - setup.about = "Adds multi slider for up to 4 double values. Usueful for when multi slide float is not accurate enough. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvSliderIntMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)" }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of ints to be displayed." }); - args.push_back({ mvPyDataType::Bool, "no_input", mvArgType::KEYWORD_ARG, "False", "Disable direct entry methods double-click or ctrl+click or Enter key allowing to input text directly into the item." }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "False", "Applies the min and max limits to direct entry methods also such as double click and CTRL+Click." }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Applies a limit only to sliding entry only." }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%d'", "Determines the format the int will be displayed as use python string formatting." }); - - setup.about = "Adds multi slider for up to 4 int values. Directly entry can be done with double click or CTRL+Click. Min and Max alone are a soft limit for the slider. Use clamped keyword to also apply limits to the direct entry modes."; - break; - } - case mvAppItemType::mvInputIntMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)" }); - args.push_back({ mvPyDataType::Integer, "min_value", mvArgType::KEYWORD_ARG, "0", "Value for lower limit of input for each cell. Use min_clamped to turn on." }); - args.push_back({ mvPyDataType::Integer, "max_value", mvArgType::KEYWORD_ARG, "100", "Value for upper limit of input for each cell. Use max_clamped to turn on." }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of components displayed for input." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds multi int input for up to 4 integer values."; - break; - } - case mvAppItemType::mvInputFloatMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Value for lower limit of input for each cell. Use min_clamped to turn on." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Value for upper limit of input for each cell. Use max_clamped to turn on." }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of components displayed for input." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds multi float input for up to 4 float values."; - break; - } - case mvAppItemType::mvInputDoubleMulti: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%.3f'", "Determines the format the float will be displayed as use python string formatting." }); - args.push_back({ mvPyDataType::Double, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Value for lower limit of input for each cell. Use min_clamped to turn on." }); - args.push_back({ mvPyDataType::Double, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Value for upper limit of input for each cell. Use max_clamped to turn on." }); - args.push_back({ mvPyDataType::Integer, "size", mvArgType::KEYWORD_ARG, "4", "Number of components displayed for input." }); - args.push_back({ mvPyDataType::Bool, "min_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of min_value." }); - args.push_back({ mvPyDataType::Bool, "max_clamped", mvArgType::KEYWORD_ARG, "False", "Activates and deactivates the enforcment of max_value." }); - args.push_back({ mvPyDataType::Bool, "on_enter", mvArgType::KEYWORD_ARG, "False", "Only runs callback on enter key press." }); - args.push_back({ mvPyDataType::Bool, "readonly", mvArgType::KEYWORD_ARG, "False", "Activates read only mode where no text can be input but text can still be highlighted." }); - args.push_back({ mvPyDataType::Bool, "accept_empty_input", mvArgType::KEYWORD_ARG, "False", "Treat empty input as a zero value." }); - args.push_back({ mvPyDataType::Bool, "display_empty_value", mvArgType::KEYWORD_ARG, "False", "If True, display an empty input if the value is zero. Generally used together with accept_empty_input." }); - - setup.about = "Adds multi double input for up to 4 double values. Useful when input float mulit is not accurate enough."; - break; - } - case mvAppItemType::mvDragPoint: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0)" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Bool, "show_label", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::FloatList, "offset", mvArgType::KEYWORD_ARG, "(16.0, 8.0)", "Offset of the label, in pixels, relative to the drag point itself" }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "True", "Keep the label within the visible area of the plot even if the drag point itself goes outside of the visible area" }); - args.push_back({ mvPyDataType::Bool, "delayed", mvArgType::KEYWORD_ARG, "False", "tool rendering will be delayed one frame; useful when applying position-constraints" }); - args.push_back({ mvPyDataType::Bool, "no_cursor", mvArgType::KEYWORD_ARG, "False", "drag tools won't change cursor icons when hovered or held" }); - args.push_back({ mvPyDataType::Bool, "no_fit", mvArgType::KEYWORD_ARG, "False", "the drag tool won't be considered for plot fits" }); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "lock the tool from user inputs" }); - - setup.about = "Adds a drag point to a plot."; - setup.category = { "Plotting", "Widgets" }; - break; - } - - case mvAppItemType::mvDragRect: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)", "The coordinates are specified in a sequence of: (xmin, ymin, xmax, ymax)" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Bool, "delayed", mvArgType::KEYWORD_ARG, "False", "tool rendering will be delayed one frame; useful when applying position-constraints" }); - args.push_back({ mvPyDataType::Bool, "no_cursor", mvArgType::KEYWORD_ARG, "False", "drag tools won't change cursor icons when hovered or held" }); - args.push_back({ mvPyDataType::Bool, "no_fit", mvArgType::KEYWORD_ARG, "False", "the drag tool won't be considered for plot fits" }); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "lock the tool from user inputs" }); - - setup.about = "Adds a drag rectangle to a plot."; - setup.category = { "Plotting", "Widgets" }; - break; - } - - case mvAppItemType::mvDragLine: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Bool, "show_label", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Bool, "vertical", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Bool, "delayed", mvArgType::KEYWORD_ARG, "False", "tool rendering will be delayed one frame; useful when applying position-constraints" }); - args.push_back({ mvPyDataType::Bool, "no_cursor", mvArgType::KEYWORD_ARG, "False", "drag tools won't change cursor icons when hovered or held" }); - args.push_back({ mvPyDataType::Bool, "no_fit", mvArgType::KEYWORD_ARG, "False", "the drag tool won't be considered for plot fits" }); - args.push_back({ mvPyDataType::Bool, "no_inputs", mvArgType::KEYWORD_ARG, "False", "lock the tool from user inputs" }); - - setup.about = "Adds a drag line to a plot."; - setup.category = { "Plotting", "Widgets" }; - break; - } - case mvAppItemType::mvAnnotation: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0)" }); - args.push_back({ mvPyDataType::FloatList, "offset", mvArgType::KEYWORD_ARG, "(0.0, 0.0)" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Bool, "clamped", mvArgType::KEYWORD_ARG, "True" }); - - setup.about = "Adds an annotation to a plot."; - setup.category = { "Plotting", "Widgets" }; - break; - } - case mvAppItemType::mvAxisTag: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Bool, "auto_rounding", mvArgType::KEYWORD_ARG, "False", "When enabled, the value displayed on the tag will be automatically rounded to the precision of other values displayed at axis' ticks. Only makes sense when label is not set, i.e. when the tag displays its location on the axis." }); - - setup.about = "Adds custom labels to axes."; - setup.category = { "Plotting", "Widgets" }; - break; - } - case mvAppItemType::mvLineSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Bool, "segments", mvArgType::KEYWORD_ARG, "False", "a line segment will be rendered from every two consecutive points" }); - args.push_back({ mvPyDataType::Bool, "loop", mvArgType::KEYWORD_ARG, "False", "the last and first point will be connected to form a closed loop" }); - args.push_back({ mvPyDataType::Bool, "skip_nan", mvArgType::KEYWORD_ARG, "False", "NaNs values will be skipped instead of rendered as missing data" }); - args.push_back({ mvPyDataType::Bool, "no_clip", mvArgType::KEYWORD_ARG, "False", "markers (if displayed) on the edge of a plot will not be clipped" }); - args.push_back({ mvPyDataType::Bool, "shaded", mvArgType::KEYWORD_ARG, "False", "a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases" }); - - setup.about = "Adds a line series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvScatterSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Bool, "no_clip", mvArgType::KEYWORD_ARG, "False", "markers on the edge of a plot will not be clipped" }); - - setup.about = "Adds a scatter series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvStemSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "stems will be rendered horizontally on the current y-axis" }); - - setup.about = "Adds a stem series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvStairSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Bool, "pre_step", mvArgType::KEYWORD_ARG, "False", "the y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i]" }); - args.push_back({ mvPyDataType::Bool, "shaded", mvArgType::KEYWORD_ARG, "False", "a filled region between the line and horizontal origin will be rendered; use add_shade_series for more advanced cases" }); - - setup.about = "Adds a stair series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvBarSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Float, "weight", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "bars will be rendered horizontally on the current y-axis" }); - - setup.about = "Adds a bar series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvBarGroupSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "values" }); - args.push_back({ mvPyDataType::StringList, "label_ids", mvArgType::REQUIRED_ARG, "...", "Label of each bar in a group" }); - args.push_back({ mvPyDataType::Integer, "group_size", mvArgType::REQUIRED_ARG, "...", "Number of bars in a group"}); - args.push_back({ mvPyDataType::Float, "group_width", mvArgType::KEYWORD_ARG, "0.67", "Size of bar groups" }); - args.push_back({ mvPyDataType::Integer, "shift", mvArgType::KEYWORD_ARG, "0", "The position on the x axis where to start plotting bar groups" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "bar groups will be rendered horizontally on the current y-axis" }); - args.push_back({ mvPyDataType::Bool, "stacked", mvArgType::KEYWORD_ARG, "False", "items in a group will be stacked on top of each other" }); - - setup.about = "Adds a bar groups series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvErrorSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::DoubleList, "negative" }); - args.push_back({ mvPyDataType::DoubleList, "positive" }); - args.push_back({ mvPyDataType::Bool, "contribute_to_bounds", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False" }); - - setup.about = "Adds an error series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvInfLineSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False" }); - - setup.about = "Adds an infinite line series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvHeatSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::Integer, "rows" }); - args.push_back({ mvPyDataType::Integer, "cols" }); - args.push_back({ mvPyDataType::Double, "scale_min", mvArgType::KEYWORD_ARG, "0.0", "Sets the color scale min. Typically paired with the color scale widget scale_min." }); - args.push_back({ mvPyDataType::Double, "scale_max", mvArgType::KEYWORD_ARG, "1.0", "Sets the color scale max. Typically paired with the color scale widget scale_max." }); - args.push_back({ mvPyDataType::DoubleList, "bounds_min", mvArgType::KEYWORD_ARG, "(0.0, 0.0)" }); - args.push_back({ mvPyDataType::DoubleList, "bounds_max", mvArgType::KEYWORD_ARG, "(1.0, 1.0)" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.1f'" }); - args.push_back({ mvPyDataType::Bool, "contribute_to_bounds", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Bool, "col_major", mvArgType::KEYWORD_ARG, "False", "data will be read in column major order" }); - - setup.about = "Adds a heat series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvImageSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::UUID, "texture_tag" }); - args.push_back({ mvPyDataType::DoubleList, "bounds_min" }); - args.push_back({ mvPyDataType::DoubleList, "bounds_max" }); - args.push_back({ mvPyDataType::FloatList, "uv_min", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "normalized texture coordinates" }); - args.push_back({ mvPyDataType::FloatList, "uv_max", mvArgType::KEYWORD_ARG, "(1.0, 1.0)", "normalized texture coordinates" }); - args.push_back({ mvPyDataType::IntList, "tint_color", mvArgType::KEYWORD_ARG, "(255, 255, 255, 255)" }); - - setup.about = "Adds an image series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets", "Textures" }; - break; - } - case mvAppItemType::mvPieSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Double, "x" }); - args.push_back({ mvPyDataType::Double, "y" }); - args.push_back({ mvPyDataType::Double, "radius" }); - args.push_back({ mvPyDataType::DoubleList, "values" }); - args.push_back({ mvPyDataType::StringList, "labels" }); - args.push_back({ mvPyDataType::String, "format", mvArgType::KEYWORD_ARG, "'%0.2f'" }); - args.push_back({ mvPyDataType::Double, "angle", mvArgType::KEYWORD_ARG, "90.0" }); - args.push_back({ mvPyDataType::Bool, "normalize", mvArgType::KEYWORD_ARG, "False", "force normalization of pie chart values (i.e. always make a full circle if sum < 0)" }); - args.push_back({ mvPyDataType::Bool, "ignore_hidden", mvArgType::KEYWORD_ARG, "False", "ignore hidden slices when drawing the pie chart (as if they were not there)" }); - - setup.about = "Adds an pie series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvShadeSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y1" }); - args.push_back({ mvPyDataType::DoubleList, "y2", mvArgType::KEYWORD_ARG, "[]" }); - - setup.about = "Adds a shade series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvLabelSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Double, "x" }); - args.push_back({ mvPyDataType::Double, "y" }); - args.push_back({ mvPyDataType::Integer, "x_offset", mvArgType::DEPRECATED_KEYWORD_ARG, "0", "Old way to set x offset of the label. Use `offset` argument instead.", "See the new offset argument." }); - args.push_back({ mvPyDataType::Integer, "y_offset", mvArgType::DEPRECATED_KEYWORD_ARG, "0", "Old way to set y offset of the label. Use `offset` argument instead.", "See the new offset argument." }); - args.push_back({ mvPyDataType::FloatList, "offset", mvArgType::KEYWORD_ARG, "(0.0, 0.0)", "Offset of the label, in pixels, relative to the coordinates." }); - args.push_back({ mvPyDataType::Bool, "vertical", mvArgType::KEYWORD_ARG, "False" }); - - setup.about = "Adds a label series to a plot. x and y can only have one elements each."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvDigitalSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - - setup.about = "Adds a digital series to a plot. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvHistogramSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::Integer, "bins", mvArgType::KEYWORD_ARG, "-1" }); - args.push_back({ mvPyDataType::Float, "bar_scale", mvArgType::KEYWORD_ARG, "1.0" }); - args.push_back({ mvPyDataType::Double, "min_range", mvArgType::KEYWORD_ARG, "0.0", "set the min range value, the values under this min will be ignored" }); - args.push_back({ mvPyDataType::Double, "max_range", mvArgType::KEYWORD_ARG, "0.0", "set the max range value, the values over this max will be ignored. If both min and max are 0.0, then the values will be the min and max values of the series" }); - args.push_back({ mvPyDataType::Bool, "cumulative", mvArgType::KEYWORD_ARG, "False", "each bin will contain its count plus the counts of all previous bins" }); - args.push_back({ mvPyDataType::Bool, "cumlative", mvArgType::DEPRECATED_RENAME_KEYWORD_ARG, "False", "Deprecated because of typo", "cumulative" }); - args.push_back({ mvPyDataType::Bool, "density", mvArgType::KEYWORD_ARG, "False", "counts will be normalized, i.e. the PDF will be visualized, or the CDF will be visualized if Cumulative is also set" }); - args.push_back({ mvPyDataType::Bool, "outliers", mvArgType::KEYWORD_ARG, "True", "exclude values outside the specifed histogram range from the count toward normalizing and cumulative counts" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "histogram bars will be rendered horizontally" }); - args.push_back({ mvPyDataType::Bool, "contribute_to_bounds", mvArgType::KEYWORD_ARG, "True" }); - - setup.about = "Adds a histogram series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mv2dHistogramSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Integer, "xbins", mvArgType::KEYWORD_ARG, "-1" }); - args.push_back({ mvPyDataType::Integer, "ybins", mvArgType::KEYWORD_ARG, "-1" }); - args.push_back({ mvPyDataType::Double, "xmin_range", mvArgType::KEYWORD_ARG, "0.0", "set the min x range value, the values under this min will be ignored"}); - args.push_back({ mvPyDataType::Double, "xmax_range", mvArgType::KEYWORD_ARG, "0.0", "set the max x range value, the values over this max will be ignored"}); - args.push_back({ mvPyDataType::Double, "ymin_range", mvArgType::KEYWORD_ARG, "0.0", "set the min y range value, the values under this min will be ignored"}); - args.push_back({ mvPyDataType::Double, "ymax_range", mvArgType::KEYWORD_ARG, "0.0", "set the max y range value, the values over this max will be ignored. If all xmin, xmax, ymin and ymax are 0.0, then the values will be the min and max values of the series" }); - args.push_back({ mvPyDataType::Bool, "density", mvArgType::KEYWORD_ARG, "False", "counts will be normalized, i.e. the PDF will be visualized" }); - args.push_back({ mvPyDataType::Bool, "outliers", mvArgType::KEYWORD_ARG, "False", "exclude values outside the specified histogram range from the count used for normalizing" }); - args.push_back({ mvPyDataType::Bool, "col_major", mvArgType::KEYWORD_ARG, "False", "data will be read in column major order" }); - - setup.about = "Adds a 2d histogram series."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvCandleSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "dates" }); - args.push_back({ mvPyDataType::DoubleList, "opens" }); - args.push_back({ mvPyDataType::DoubleList, "closes" }); - args.push_back({ mvPyDataType::DoubleList, "lows" }); - args.push_back({ mvPyDataType::DoubleList, "highs" }); - args.push_back({ mvPyDataType::IntList, "bull_color", mvArgType::KEYWORD_ARG, "(0, 255, 113, 255)" }); - args.push_back({ mvPyDataType::IntList, "bear_color", mvArgType::KEYWORD_ARG, "(218, 13, 79, 255)" }); - args.push_back({ mvPyDataType::Float, "weight", mvArgType::KEYWORD_ARG, "0.25" }); - args.push_back({ mvPyDataType::Bool, "tooltip", mvArgType::KEYWORD_ARG, "True" }); - args.push_back({ mvPyDataType::Integer, "time_unit", mvArgType::KEYWORD_ARG, "5", "mvTimeUnit_* constants. Default mvTimeUnit_Day."}); - - setup.about = "Adds a candle series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvCustomSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::Integer, "channel_count" }); - args.push_back({ mvPyDataType::DoubleList, "y1", mvArgType::KEYWORD_ARG, "[]" }); - args.push_back({ mvPyDataType::DoubleList, "y2", mvArgType::KEYWORD_ARG, "[]" }); - args.push_back({ mvPyDataType::DoubleList, "y3", mvArgType::KEYWORD_ARG, "[]" }); - args.push_back({ mvPyDataType::Bool, "tooltip", mvArgType::KEYWORD_ARG, "True", "Show tooltip when plot is hovered." }); - args.push_back({ mvPyDataType::Bool, "no_fit", mvArgType::KEYWORD_ARG, "False", "the item won't be considered for plot fits" }); - - setup.about = "Adds a custom series to a plot. New in 1.6."; - setup.category = { "Plotting", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvAreaSeries: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::DoubleList, "x" }); - args.push_back({ mvPyDataType::DoubleList, "y" }); - args.push_back({ mvPyDataType::IntList, "fill", mvArgType::KEYWORD_ARG, "(0, 0, 0, -255)" }); - args.push_back({ mvPyDataType::Bool, "contribute_to_bounds", mvArgType::KEYWORD_ARG, "True" }); - - setup.about = "Adds an area series to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - break; - } - case mvAppItemType::mvColorMapScale: - { - - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Callable, "drag_callback", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - args.push_back({ mvPyDataType::UUID, "colormap", mvArgType::KEYWORD_ARG, "0", "mvPlotColormap_* constants or mvColorMap uuid from a color map registry" }); - args.push_back({ mvPyDataType::Float, "min_scale", mvArgType::KEYWORD_ARG, "0.0", "Sets the min number of the color scale. Typically is the same as the min scale from the heat series." }); - args.push_back({ mvPyDataType::Float, "max_scale", mvArgType::KEYWORD_ARG, "1.0", "Sets the max number of the color scale. Typically is the same as the max scale from the heat series." }); - args.push_back({mvPyDataType:: String, "format", mvArgType::KEYWORD_ARG, "'%g'", "Formatting used for the labels."}); - args.push_back({mvPyDataType:: Bool, "reverse_dir", mvArgType::KEYWORD_ARG, "False", "invert the colormap bar and axis scale (this only affects rendering; if you only want to reverse the scale mapping, make scale_min > scale_max)"}); - args.push_back({mvPyDataType:: Bool, "mirror", mvArgType::KEYWORD_ARG, "False", "render the colormap label and tick labels on the opposite side"}); - - setup.about = "Adds a legend that pairs values with colors. This is typically used with a heat series. "; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvSlider3D: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::Float, "max_x", mvArgType::KEYWORD_ARG, "100.0", "Applies upper limit to slider." }); - args.push_back({ mvPyDataType::Float, "max_y", mvArgType::KEYWORD_ARG, "100.0", "Applies upper limit to slider." }); - args.push_back({ mvPyDataType::Float, "max_z", mvArgType::KEYWORD_ARG, "100.0", "Applies upper limit to slider." }); - args.push_back({ mvPyDataType::Float, "min_x", mvArgType::KEYWORD_ARG, "0.0", "Applies lower limit to slider." }); - args.push_back({ mvPyDataType::Float, "min_y", mvArgType::KEYWORD_ARG, "0.0", "Applies lower limit to slider." }); - args.push_back({ mvPyDataType::Float, "min_z", mvArgType::KEYWORD_ARG, "0.0", "Applies lower limit to slider." }); - args.push_back({ mvPyDataType::Float, "scale", mvArgType::KEYWORD_ARG, "1.0", "Size of the widget." }); - - setup.about = "Adds a 3D box slider."; - break; - } - case mvAppItemType::mvKnobFloat: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SOURCE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::Float, "min_value", mvArgType::KEYWORD_ARG, "0.0", "Applies lower limit to value." }); - args.push_back({ mvPyDataType::Float, "max_value", mvArgType::KEYWORD_ARG, "100.0", "Applies upper limit to value." }); - - setup.about = "Adds a knob that rotates based on change in x mouse position."; - break; - } - case mvAppItemType::mvLoadingIndicator: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "style", mvArgType::KEYWORD_ARG, "0", "mvLoadInd_DottedCircle is rotating dots style, mvLoadInd_Ring is rotating bar style." }); - args.push_back({ mvPyDataType::Integer, "circle_count", mvArgType::KEYWORD_ARG, "8", "DottedCircle style: number of dots to show." }); - args.push_back({ mvPyDataType::Float, "speed", mvArgType::KEYWORD_ARG, "1.0", "Speed with which the animation will rotate." }); - args.push_back({ mvPyDataType::Float, "radius", mvArgType::KEYWORD_ARG, "3.0", "Scale factor for the loading indicator radius. The size of the indicator is determined by font size and this scale factor." }); - args.push_back({ mvPyDataType::Float, "thickness", mvArgType::KEYWORD_ARG, "1.0", "Ring style: scale factor of line thickness; thickness=1 corresponds to line width being 1/8 of the ring diameter." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "None", "Main color of the indicator. If omitted, the color for mvThemeCol_Button will be used." }); - args.push_back({ mvPyDataType::IntList, "secondary_color", mvArgType::KEYWORD_ARG, "None", "DottedCircle style: color of 'inactive' dots. If omitted, the color for mvThemeCol_ButtonHovered will be used." }); - - setup.about = "Adds a rotating animated loading symbol."; - break; - } - case mvAppItemType::mvNodeLink: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::UUID, "attr_1" }); - args.push_back({ mvPyDataType::UUID, "attr_2" }); - - setup.about = "Adds a node link between 2 node attributes."; - setup.category = { "Node Editor", "Widgets" }; - break; - } - case mvAppItemType::mvTextureRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Bool, "show", mvArgType::KEYWORD_ARG, "False", "Attempt to render widget." }); - - setup.about = "Adds a dynamic texture."; - setup.category = { "Textures", "Registries", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvStaticTexture: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Integer, "width" }); - args.push_back({ mvPyDataType::Integer, "height" }); - args.push_back({ mvPyDataType::FloatList, "default_value" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_2", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a static texture."; - setup.category = { "Textures", "Widgets" }; - break; - } - case mvAppItemType::mvDynamicTexture: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Integer, "width" }); - args.push_back({ mvPyDataType::Integer, "height" }); - args.push_back({ mvPyDataType::FloatList, "default_value" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_2", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a dynamic texture."; - setup.category = { "Textures", "Widgets" }; - break; - } - case mvAppItemType::mvStage: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - setup.about = "Adds a stage."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvDrawLayer: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Bool, "perspective_divide", mvArgType::KEYWORD_ARG, "False", "New in 1.1. apply perspective divide" }); - args.push_back({ mvPyDataType::Bool, "depth_clipping", mvArgType::KEYWORD_ARG, "False", "New in 1.1. apply depth clipping" }); - args.push_back({ mvPyDataType::Integer, "cull_mode", mvArgType::KEYWORD_ARG, "0", "New in 1.1. culling mode, mvCullMode_* constants. Only works with triangles currently." }); - - setup.about = "New in 1.1. Creates a layer useful for grouping drawlist items."; - setup.category = { "Drawlist", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvViewportDrawlist: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Bool, "front", mvArgType::KEYWORD_ARG, "True", "Draws to the front of the view port instead of the back." }); - - setup.about = "A container that is used to present draw items or layers directly to the viewport. By default this will draw to the back of the viewport. Layers and draw items should be added to this widget as children."; - setup.category = { "Drawlist", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvFileExtension: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE) - ); - - args.push_back({ mvPyDataType::String, "extension", mvArgType::REQUIRED_ARG, "*", "Extension that will show as an when the parent is a file dialog." }); - args.push_back({ mvPyDataType::String, "custom_text", mvArgType::KEYWORD_ARG, "''", "Replaces the displayed text in the drop down for this extension." }); - args.push_back({ mvPyDataType::IntList, "color", mvArgType::KEYWORD_ARG, "(-255, 0, 0, 255)", "Color for the text that will be shown with specified extensions." }); - - setup.about = "Creates a file extension filter option in the file dialog."; - setup.category = { "File Dialog" }; - break; - } - case mvAppItemType::mvPlotLegend: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "location", mvArgType::KEYWORD_ARG, "5", "location, mvPlot_Location_*" }); - args.push_back({ mvPyDataType::Bool, "horizontal", mvArgType::KEYWORD_ARG, "False", "legend entries will be displayed horizontally" }); - args.push_back({ mvPyDataType::Bool, "sort", mvArgType::KEYWORD_ARG, "False", "legend entries will be displayed in alphabetical order"}); - args.push_back({ mvPyDataType::Bool, "outside", mvArgType::KEYWORD_ARG, "False", "legend will be rendered outside of the plot area"}); - args.push_back({ mvPyDataType::Bool, "no_highlight_item", mvArgType::KEYWORD_ARG, "False", "plot items will not be highlighted when their legend entry is hovered" }); - args.push_back({ mvPyDataType::Bool, "no_highlight_axis", mvArgType::KEYWORD_ARG, "False", "axes will not be highlighted when legend entries are hovered (only relevant if x/y-axis count > 1)" }); - args.push_back({ mvPyDataType::Bool, "no_menus", mvArgType::KEYWORD_ARG, "False", "the user will not be able to open context menus with right-click" }); - args.push_back({ mvPyDataType::Bool, "no_buttons", mvArgType::KEYWORD_ARG, "False", "legend icons will not function as hide/show buttons" }); - - setup.about = "Adds a plot legend to a plot."; - setup.category = { "Plotting", "Widgets" }; - break; - } - case mvAppItemType::mvPlotAxis: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "axis" }); - args.push_back({ mvPyDataType::Bool, "no_label", mvArgType::KEYWORD_ARG, "False", "the axis label will not be displayed" }); - args.push_back({ mvPyDataType::Bool, "no_gridlines", mvArgType::KEYWORD_ARG, "False", "no grid lines will be displayed" }); - args.push_back({ mvPyDataType::Bool, "no_tick_marks", mvArgType::KEYWORD_ARG, "False", "no tick marks will be displayed" }); - args.push_back({ mvPyDataType::Bool, "no_tick_labels", mvArgType::KEYWORD_ARG, "False", "no text labels will be displayed" }); - args.push_back({ mvPyDataType::Bool, "no_initial_fit", mvArgType::KEYWORD_ARG, "False", "axis will not be initially fit to data extents on the first rendered frame" }); - args.push_back({ mvPyDataType::Bool, "no_menus", mvArgType::KEYWORD_ARG, "False", "the user will not be able to open context menus with right-click" }); - args.push_back({ mvPyDataType::Bool, "no_side_switch", mvArgType::KEYWORD_ARG, "False", "the user will not be able to switch the axis side by dragging it" }); - args.push_back({ mvPyDataType::Bool, "no_highlight", mvArgType::KEYWORD_ARG, "False", "the axis will not have its background highlighted when hovered or held" }); - args.push_back({ mvPyDataType::Bool, "opposite", mvArgType::KEYWORD_ARG, "False", "axis ticks and labels will be rendered on the conventionally opposite side (i.e, right or top)" }); - args.push_back({ mvPyDataType::Bool, "foreground_grid", mvArgType::KEYWORD_ARG, "False", "grid lines will be displayed in the foreground (i.e. on top of data) instead of the background" }); - args.push_back({ mvPyDataType::String, "tick_format", mvArgType::KEYWORD_ARG, "''", "Sets a custom tick label formatter" }); - args.push_back({ mvPyDataType::Integer, "scale", mvArgType::KEYWORD_ARG, "internal_dpg.mvPlotScale_Linear", "Sets the axis' scale. Can have only mvPlotScale_ values"}); - args.push_back({ mvPyDataType::Bool, "log_scale", mvArgType::DEPRECATED_KEYWORD_ARG, "False", "Old way to set log scale in the axis. Use 'scale' argument instead.", "See the new scale argument." }); - args.push_back({ mvPyDataType::Bool, "time", mvArgType::DEPRECATED_KEYWORD_ARG, "False", "Old way to set time scale in the axis. Use 'scale' argument instead.", "See the new scale argument." }); - args.push_back({ mvPyDataType::Bool, "invert", mvArgType::KEYWORD_ARG, "False", "the axis values will be inverted (i.e. growing from right to left)" }); - args.push_back({ mvPyDataType::Bool, "auto_fit", mvArgType::KEYWORD_ARG, "False", "axis will be auto-fitting to data extents" }); - args.push_back({ mvPyDataType::Bool, "range_fit", mvArgType::KEYWORD_ARG, "False", "axis will only fit points if the point is in the visible range of the **orthogonal** axis" }); - args.push_back({ mvPyDataType::Bool, "pan_stretch", mvArgType::KEYWORD_ARG, "False", "panning in a locked or constrained state will cause the axis to stretch if possible" }); - args.push_back({ mvPyDataType::Bool, "lock_min", mvArgType::KEYWORD_ARG, "False", "the axis minimum value will be locked when panning/zooming"}); - args.push_back({ mvPyDataType::Bool, "lock_max", mvArgType::KEYWORD_ARG, "False", "the axis maximum value will be locked when panning/zooming" }); - - - setup.about = "Adds an axis to a plot."; - setup.category = { "Plotting", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvHandlerRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds a handler registry."; - setup.category = { "Events", "Widgets", "Registries" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvKeyDownHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "key", mvArgType::POSITIONAL_ARG, "internal_dpg.mvKey_None", "Submits callback for all keys" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a key down handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvKeyPressHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "key", mvArgType::POSITIONAL_ARG, "internal_dpg.mvKey_None", "Submits callback for all keys" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a key press handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvKeyReleaseHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "key", mvArgType::POSITIONAL_ARG, "internal_dpg.mvKey_None", "Submits callback for all keys" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a key release handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseMoveHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_CALLBACK) - ); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse move handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseWheelHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_CALLBACK) - ); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse wheel handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseClickHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse click handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseDoubleClickHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse double click handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseDownHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse down handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseReleaseHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse release handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvMouseDragHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - args.push_back({ mvPyDataType::Float, "threshold", mvArgType::POSITIONAL_ARG, "10.0", "The threshold the mouse must be dragged before the callback is ran" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_1", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a mouse drag handler."; - setup.category = { "Events", "Widgets" }; - break; - } - case mvAppItemType::mvHoverHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - args.push_back({ mvPyDataType::Integer, "event_type", mvArgType::KEYWORD_ARG, "None", "What kind of events to track: mouse-in (mvEventType_Enter), mouse-over (mvEventType_On), mouse-out (mvEventType_Leave). Can be a combination of these flags. Defaults to mouse-over." }); - - setup.about = "Adds a hover handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvActiveHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a active handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvFocusHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - args.push_back({ mvPyDataType::Integer, "event_type", mvArgType::KEYWORD_ARG, "None", "What kind of events to track: just got focus (mvEventType_Enter), currently having focus (mvEventType_On), lost focus (mvEventType_Leave). Can be a combination of these flags. Defaults to mvEventType_On." }); - - setup.about = "Adds a focus handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvVisibleHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a visible handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvEditedHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds an edited handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvActivatedHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a activated handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvDeactivatedHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a deactivated handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvDeactivatedAfterEditHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a deactivated after edit handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvToggledOpenHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - args.push_back({ mvPyDataType::Bool, "two_way", mvArgType::KEYWORD_ARG, "False", "Trigger on both 'opened' and 'closed' events, i.e. when the 'opened' state is toggled between the two values. If False, some containers will trigger it only on the 'opened' event." }); - - setup.about = "Adds a togged open handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvClickedHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - - setup.about = "Adds a clicked handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvDoubleClickedHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - args.push_back({ mvPyDataType::Integer, "button", mvArgType::POSITIONAL_ARG, "-1", "Submits callback for all mouse buttons" }); - - setup.about = "Adds a double click handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvDragPayload: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::Object, "drag_data", mvArgType::KEYWORD_ARG, "None", "Drag data" }); - args.push_back({ mvPyDataType::Object, "drop_data", mvArgType::KEYWORD_ARG, "None", "Drop data" }); - args.push_back({ mvPyDataType::String, "payload_type", mvArgType::KEYWORD_ARG, "'$$DPG_PAYLOAD'" }); - - setup.about = "User data payload for drag and drop operations."; - setup.category = { "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvResizeHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a resize handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvScrollHandler: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_CALLBACK) - ); - - setup.about = "Adds a scroll handler."; - setup.category = { "Widgets", "Events" }; - break; - } - case mvAppItemType::mvFont: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::String, "file" }); - args.push_back({ mvPyDataType::Integer, "size" }); - args.push_back({ mvPyDataType::Bool, "pixel_snapH", mvArgType::KEYWORD_ARG, "False", "Align every glyph to pixel boundary in horizontal direction. Useful if you are rendering text piece-by-piece (e.g. for coloring)." }); - args.push_back({ mvPyDataType::Bool, "pixel_snapV", mvArgType::KEYWORD_ARG, "False", "Align scaled GlyphOffset.y to pixel boundaries in ImGui." }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_0", "Parent to add this item to. (runtime adding)" }); - args.push_back({ mvPyDataType::Bool, "default_font", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - - setup.about = "Adds font to a font registry."; - setup.category = { "Fonts", "Containers" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvFontRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds a font registry."; - setup.category = { "Fonts", "Containers", "Registries" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTheme: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Bool, "default_theme", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - - setup.about = "Adds a theme."; - setup.category = { "Themes", "Containers" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvThemeColor: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT) - ); - - args.push_back({ mvPyDataType::Long, "target", mvArgType::POSITIONAL_ARG, "0" }); - args.push_back({ mvPyDataType::IntList, "value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)" }); - args.push_back({ mvPyDataType::Integer, "category", mvArgType::KEYWORD_ARG, "0", "Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes." }); - - setup.about = "Adds a theme color."; - setup.category = { "Themes" }; - break; - } - case mvAppItemType::mvThemeStyle: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT) - ); - - args.push_back({ mvPyDataType::Long, "target", mvArgType::POSITIONAL_ARG, "0" }); - args.push_back({ mvPyDataType::Float, "x", mvArgType::POSITIONAL_ARG, "1.0" }); - args.push_back({ mvPyDataType::Float, "y", mvArgType::POSITIONAL_ARG, "-1.0" }); - args.push_back({ mvPyDataType::Integer, "category", mvArgType::KEYWORD_ARG, "0", "Options include mvThemeCat_Core, mvThemeCat_Plots, mvThemeCat_Nodes." }); - - setup.about = "Adds a theme style."; - setup.category = { "Themes" }; - break; - } - case mvAppItemType::mvThemeComponent: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE - )); - - args.push_back({ mvPyDataType::Integer, "item_type", mvArgType::POSITIONAL_ARG, "0" }); - args.push_back({ mvPyDataType::Bool, "enabled_state", mvArgType::KEYWORD_ARG, "True" }); - - setup.about = "Adds a theme component."; - setup.category = { "Themes", "Containers" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvCharRemap: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT) - ); - - args.push_back({ mvPyDataType::Integer, "source" }); - args.push_back({ mvPyDataType::Integer, "target" }); - - setup.category = { "Fonts", "Widgets" }; - setup.about = "Remaps a character."; - break; - } - case mvAppItemType::mvValueRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - setup.about = "Adds a value registry."; - setup.category = { "Widgets", "Values", "Containers" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvIntValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::Integer, "default_value", mvArgType::KEYWORD_ARG, "0" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a int value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvFloatValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a float value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvFloat4Value: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a float4 value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvInt4Value: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::KEYWORD_ARG, "(0, 0, 0, 0)" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a int4 value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvBoolValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::Bool, "default_value", mvArgType::KEYWORD_ARG, "False" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a bool value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvStringValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::String, "default_value", mvArgType::KEYWORD_ARG, "''" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a string value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvDoubleValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::Double, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a double value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvDouble4Value: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a double value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvColorValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "(0.0, 0.0, 0.0, 0.0)" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a color value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvFloatVectValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::FloatList, "default_value", mvArgType::KEYWORD_ARG, "()" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a float vect value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvSeriesValue: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SOURCE) - ); - - args.push_back({ mvPyDataType::DoubleList, "default_value", mvArgType::KEYWORD_ARG, "()" }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_3", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a plot series value."; - setup.category = { "Widgets", "Values" }; - break; - } - case mvAppItemType::mvRawTexture: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Integer, "width" }); - args.push_back({ mvPyDataType::Integer, "height" }); - args.push_back({ mvPyDataType::FloatList, "default_value" }); - args.push_back({ mvPyDataType::Integer, "format", mvArgType::KEYWORD_ARG, "internal_dpg.mvFormat_Float_rgba", "Data format." }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_2", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a raw texture."; - setup.category = { "Textures", "Widgets" }; - break; - } - case mvAppItemType::mvSubPlots: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SEARCH_DELAY | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Integer, "rows" }); - args.push_back({ mvPyDataType::Integer, "columns" }); - args.push_back({ mvPyDataType::FloatList, "row_ratios", mvArgType::KEYWORD_ARG, "[]" }); - args.push_back({ mvPyDataType::FloatList, "column_ratios", mvArgType::KEYWORD_ARG, "[]" }); - - // plot flags - args.push_back({ mvPyDataType::Bool, "no_title", mvArgType::KEYWORD_ARG, "False", "the subplot title will not be displayed" }); - args.push_back({ mvPyDataType::Bool, "no_menus", mvArgType::KEYWORD_ARG, "False", "the user will not be able to open context menus with right-click" }); - args.push_back({ mvPyDataType::Bool, "no_resize", mvArgType::KEYWORD_ARG, "False", "resize splitters between subplot cells will be not be provided" }); - args.push_back({ mvPyDataType::Bool, "no_align", mvArgType::KEYWORD_ARG, "False", "subplot edges will not be aligned vertically or horizontally" }); - args.push_back({ mvPyDataType::Bool, "share_series", mvArgType::KEYWORD_ARG, "False", "when set to True, series from all sub-plots will be shared to some extent, using a single common color set and showing them in a single legend in the subplots item. Otherwise each plot will be independent from others and will have its own legend" }); - args.push_back({ mvPyDataType::Bool, "link_rows", mvArgType::KEYWORD_ARG, "False", "link the y-axis limits of all plots in each row (does not apply auxiliary y-axes)" }); - args.push_back({ mvPyDataType::Bool, "link_columns", mvArgType::KEYWORD_ARG, "False", "link the x-axis limits of all plots in each column" }); - args.push_back({ mvPyDataType::Bool, "link_all_x", mvArgType::KEYWORD_ARG, "False", "link the x-axis limits in every plot in the subplot" }); - args.push_back({ mvPyDataType::Bool, "link_all_y", mvArgType::KEYWORD_ARG, "False", "link the y-axis limits in every plot in the subplot (does not apply to auxiliary y-axes)" }); - args.push_back({ mvPyDataType::Bool, "column_major", mvArgType::KEYWORD_ARG, "False", "subplots are added in column major order instead of the default row major order" }); - - setup.about = "Adds a collection of plots."; - setup.category = { "Plotting", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvColorMap: - { - - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW) - ); - - args.push_back({ mvPyDataType::ListListInt, "colors", mvArgType::REQUIRED_ARG, "", "colors that will be mapped to the normalized value 0.0->1.0" }); - args.push_back({ mvPyDataType::Bool, "qualitative", mvArgType::REQUIRED_ARG, "", "Qualitative will create hard transitions for color boundries across the value range when enabled." }); - args.push_back({ mvPyDataType::UUID, "parent", mvArgType::KEYWORD_ARG, "internal_dpg.mvReservedUUID_4", "Parent to add this item to. (runtime adding)" }); - - setup.about = "Adds a legend that pairs colors with normalized value 0.0->1.0. Each color will be This is typically used with a heat series. (ex. [[0, 0, 0, 255], [255, 255, 255, 255]] will be mapped to a soft transition from 0.0-1.0)"; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvColorMapRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - args.push_back({ mvPyDataType::Bool, "show", mvArgType::KEYWORD_ARG, "False", "Attempt to render widget." }); - - setup.about = "Adds a colormap registry."; - setup.category = { "Containers", "Widgets", "Colors" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvColorMapButton: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_ENABLED | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_DRAG_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::IntList, "default_value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)" }); - - setup.about = "Adds a button that a color map can be bound to."; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvColorMapSlider: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_WIDTH | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_INDENT | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_CALLBACK | - MV_PARSER_ARG_SHOW | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_DROP_CALLBACK | - MV_PARSER_ARG_PAYLOAD_TYPE | - MV_PARSER_ARG_TRACKED | - MV_PARSER_ARG_POS) - ); - - args.push_back({ mvPyDataType::Callable, "drag_callback", mvArgType::DEPRECATED_REMOVE_KEYWORD_ARG }); - args.push_back({ mvPyDataType::Float, "default_value", mvArgType::KEYWORD_ARG, "0.0" }); - - setup.about = "Adds a color slider that a color map can be bound to."; - setup.category = { "Widgets", "Colors" }; - break; - } - case mvAppItemType::mvTemplateRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID) - ); - - setup.about = "Adds a template registry."; - setup.category = { "Containers", "Widgets", "Registries" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvTableCell: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_PARENT | - MV_PARSER_ARG_BEFORE | - MV_PARSER_ARG_HEIGHT | - MV_PARSER_ARG_FILTER | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds a table."; - setup.category = { "Tables", "Containers", "Widgets" }; - setup.createContextManager = true; - break; - } - case mvAppItemType::mvItemHandlerRegistry: - { - AddCommonArgs(args, (CommonParserArgs)( - MV_PARSER_ARG_ID | - MV_PARSER_ARG_SHOW) - ); - - setup.about = "Adds an item handler registry."; - setup.category = { "Widgets", "Events", "Registries", "Containers" }; - setup.createContextManager = true; - break; - } - - case mvAppItemType::All: - case mvAppItemType::None: - case mvAppItemType::ItemTypeCount: - default: break; - } - - return FinalizeParser(setup, args); -} - -void -DearPyGui::OnChildAdded(mvAppItem* item, std::shared_ptr child) -{ - switch (item->type) - { - - case mvAppItemType::mvWindowAppItem: - { - mvWindowAppItem* actualItem = (mvWindowAppItem*)item; - if (child->type == mvAppItemType::mvMenuBar) - actualItem->configData.windowflags |= ImGuiWindowFlags_MenuBar; - return; - } - - case mvAppItemType::mvFontRegistry: - { - mvFontRegistry* actualItem = (mvFontRegistry*)item; - actualItem->onChildAdd(child); - return; - } - - case mvAppItemType::mvPlot: - { - mvPlot* actualItem = (mvPlot*)item; - if (child->type == mvAppItemType::mvPlotLegend) - actualItem->configData._flags &= ~ImPlotFlags_NoLegend; - return; - } - - case mvAppItemType::mvSubPlots: - { - mvSubPlots* actualItem = (mvSubPlots*)item; - actualItem->onChildAdd(child); - return; - } - - case mvAppItemType::mvTable: - { - mvTable* actualItem = (mvTable*)item; - actualItem->onChildAdd(child); - return; - } - - default: return; - } -} - -void -DearPyGui::OnChildRemoved(mvAppItem* item, std::shared_ptr child) -{ - switch (item->type) - { - - case mvAppItemType::mvWindowAppItem: - { - mvWindowAppItem* actualItem = (mvWindowAppItem*)item; - if (child->type == mvAppItemType::mvMenuBar) - actualItem->configData.windowflags &= ~ImGuiWindowFlags_MenuBar; - return; - } - - case mvAppItemType::mvNodeEditor: - { - mvNodeEditor* actualItem = (mvNodeEditor*)item; - actualItem->onChildRemoved(child); - return; - } - - case mvAppItemType::mvPlot: - { - mvPlot* actualItem = (mvPlot*)item; - if (child->type == mvAppItemType::mvPlotLegend) - actualItem->configData._flags |= ImPlotFlags_NoLegend; - return; - } - - case mvAppItemType::mvSubPlots: - { - mvSubPlots* actualItem = (mvSubPlots*)item; - actualItem->onChildRemoved(child); - return; - } - - case mvAppItemType::mvTable: - { - mvTable* actualItem = (mvTable*)item; - actualItem->onChildRemoved(child); - return; - } - - default: - return; - } -} - -void -DearPyGui::RestoreImGuiCursor(const ImVec2& prev_pos) -{ - ImGui::SetCursorPos(prev_pos); - // Since ImGui 1.92.0, it is necessary to add an item, say a Dummy, if we do - // a SetCursorPos at the end of a group or a window (see issue #5548 in Dear ImGui). - // To prevent the Dummy from actually moving the cursor, we also zero out item spacing. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); - ImGui::Dummy(ImVec2(0, 0)); - ImGui::PopStyleVar(); -} diff --git a/src/mvAppItem.h b/src/mvAppItem.h deleted file mode 100644 index 62f21c332..000000000 --- a/src/mvAppItem.h +++ /dev/null @@ -1,526 +0,0 @@ -#pragma once - -//----------------------------------------------------------------------------- -// mvAppItem -// -// - mvAppItem is the abstract base class for all DearPygui widgets. -// -//----------------------------------------------------------------------------- - -#include -#include -#include -#include "mvAppItemState.h" -#include "mvCallbackRegistry.h" -#include "mvPyUtils.h" -#include "mvAppItemTypes.inc" - -// forward declarations -class mvThemeManager; -class mvAppItem; -class mvItemHandlerRegistry; -class mvTheme; -class mvThemeComponent; - -//----------------------------------------------------------------------------- -// mvAppItemType -//----------------------------------------------------------------------------- -enum class mvAppItemType -{ - None = -1, All, - #define X(el) el, - MV_ITEM_TYPES - #undef X - ItemTypeCount -}; - -enum class StorageValueTypes -{ - None = 0, - Int, Int4, - Float, Float4, FloatVect, - Double, Double4, DoubleVect, - Series, Bool, String, UUID, - Time, Color, Texture -}; - -enum ItemDescriptionFlags -{ - MV_ITEM_DESC_DEFAULT = 0, - MV_ITEM_DESC_ROOT = 1 << 1, - MV_ITEM_DESC_CONTAINER = 1 << 2, - MV_ITEM_DESC_HANDLER = 1 << 3, // todo: rename descriptively - MV_ITEM_DESC_DRAW_CMP = 1 << 4 // has draw component -}; - -enum class mvLibType -{ - MV_IMGUI = 0, - MV_IMPLOT = 1, - MV_IMNODES = 2 -}; - -struct ScopedID -{ - ScopedID(void* id) { ImGui::PushID(id); } - ScopedID(mvUUID id) { ImGui::PushID((int)id); } - ~ScopedID() { ImGui::PopID(); } -}; - -namespace DearPyGui -{ - std::shared_ptr CreateEntity (mvAppItemType type, mvUUID id); - int GetEntityDesciptionFlags (mvAppItemType type); - int GetEntityTargetSlot (mvAppItemType type); - StorageValueTypes GetEntityValueType (mvAppItemType type); - const char* GetEntityTypeString (mvAppItemType type); - int GetApplicableState (mvAppItemType type); - const std::vector>& GetAllowableParents (mvAppItemType type); - const std::vector>& GetAllowableChildren (mvAppItemType type); - std::shared_ptr& GetClassThemeComponent (mvAppItemType type); - std::shared_ptr& GetDisabledClassThemeComponent (mvAppItemType type); - mvPythonParser GetEntityParser (mvAppItemType type); - void OnChildAdded (mvAppItem* item, std::shared_ptr child); - void OnChildRemoved (mvAppItem* item, std::shared_ptr child); - // This is purely a helper function that restores cursor position so that subsequent - // items follow the normal item flow. Use it in place of ImGui::SetCursorPos(). - void RestoreImGuiCursor (const ImVec2& prev_pos); -} - -struct mvAppItemInfo -{ - std::string internalLabel; // label passed into imgui - mvAppItem* parentPtr = nullptr; - int location = -1; - bool showDebug = false; - - // next frame triggers - bool focusNextFrame = false; - bool triggerAlternativeAction = false; - bool shownLastFrame = false; - bool hiddenLastFrame = false; - bool enabledLastFrame = false; - bool disabledLastFrame = false; - - // previous frame cache - ImVec2 previousCursorPos = { 0.0f, 0.0f }; - - // dirty flags - bool dirty_size = true; - bool dirtyPos = false; -}; - -enum mvSetScrollFlags -{ - mvSetScrollFlags_None = 0, - mvSetScrollFlags_Now = 1 << 0, - mvSetScrollFlags_Delayed = 1 << 1, - mvSetScrollFlags_Both = mvSetScrollFlags_Now | mvSetScrollFlags_Delayed -}; - -struct mvAppItemConfig -{ - mvUUID source = 0; - mvUUID parent = 0; - std::string specifiedLabel; - std::string filter; - std::string alias; - std::string payloadType = "$$DPG_PAYLOAD"; - int width = 0; - int height = 0; - float indent = -1.0f; - float trackOffset = 0.5f; // 0.0f:top, 0.5f:center, 1.0f:bottom - bool show = true; - bool enabled = true; - bool useInternalLabel = true; // when false, will use specificed label - bool tracked = false; - mvPyObject callback = nullptr; - mvPyObject dragCallback = nullptr; - mvPyObject dropCallback = nullptr; - // We store user_data as a pointer because that's how we'll need it when submitting - // the callback. This is to pass user_data into mvAddCallback that comes from a - // different source than the callback owner (required for the drag callback). - std::shared_ptr user_data = std::make_shared(nullptr); - float scrollX = 0.0f; - float scrollY = 0.0f; - mvSetScrollFlags scrollXFlags = mvSetScrollFlags_None; - mvSetScrollFlags scrollYFlags = mvSetScrollFlags_None; -}; - -struct mvAppItemDrawInfo -{ - mvMat4 transform = mvIdentityMat4(); - mvMat4 appliedTransform = mvIdentityMat4(); // only used by nodes - long cullMode = 0; // mvCullMode_None - bool perspectiveDivide = false; - bool depthClipping = false; - float clipViewport[6] = { 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f }; // top leftx, top lefty, width, height, min depth, maxdepth -}; - -//----------------------------------------------------------------------------- -// mvAppItem -//----------------------------------------------------------------------------- -class mvAppItem : public std::enable_shared_from_this -{ - -public: - - mvAppItemType type = mvAppItemType::None; - mvUUID uuid = 0; - mvAppItemState state; - mvAppItemInfo info{}; - mvAppItemConfig config{}; - std::shared_ptr handlerRegistry = nullptr; - std::shared_ptr font = nullptr; - std::shared_ptr theme = nullptr; - std::shared_ptr drawInfo = nullptr; - - // slots - // * 0 : mvFileExtension, mvNodeLink, mvAnnotation, mvAxisTag - // mvDragLine, mvDragPoint, mvDragRect, mvLegend, mvTableColumn - // * 1 : Most widgets - // * 2 : Draw Commands - // * 3 : mvDragPayload - std::vector> childslots[4] = { {}, {}, {}, {} }; - -public: - - mvAppItem(mvUUID uuid); - mvAppItem(const mvAppItem& other) = delete; // copy constructor - mvAppItem(mvAppItem&& other) = delete; // move constructor - - virtual ~mvAppItem(); - - // actual immediate mode drawing instructions - virtual void draw(ImDrawList* drawlist, f32 x, f32 y) = 0; - - //----------------------------------------------------------------------------- - // usually used for iterating through items and performing an action - // other than drawing. - //----------------------------------------------------------------------------- - virtual void customAction(void* data = nullptr) {}; - - //----------------------------------------------------------------------------- - // These methods handle setting the widget's value using PyObject*'s or - // returning the actual value. These are mostly overridden by the - // mvTypeBase classes - //----------------------------------------------------------------------------- - virtual void* getValue() { return nullptr; } - virtual PyObject* getPyValue() { return GetPyNone(); } - virtual void setPyValue(PyObject* value) { } - - // used to check arguments, get/set configurations - void handleKeywordArgs(PyObject* dict, const std::string& parser); // python dictionary acts as an out parameter - - // used by derived items to register their arguments - virtual void handleSpecificRequiredArgs (PyObject* args) {} - virtual void handleSpecificPositionalArgs(PyObject* args) {} - virtual void handleSpecificKeywordArgs (PyObject* dict) {} // called by handleKeywordArgs - virtual void getSpecificConfiguration (PyObject* dict) {} - - //----------------------------------------------------------------------------- - // callbacks - //----------------------------------------------------------------------------- - // Submits the specified callback, if any, with user_data from the item config - // and app_data created by app_data_func (typically a lambda). - // Note: `callback` must be a member of `this` (or of a nested object, like `config`). - // It does *not* check if the item is enabled or disabled, because some "custom" - // callbacks historically run even on disabled items. - template - void submitCallbackEx(PyObject* callback, AppDataFunc app_data_func) - { - // The current `mvAppItem` becomes the owner of this callback, and as soon - // as it gets deleted, the callback entry will be thrown away. - mvAddCallback(weak_from_this(), callback, config.user_data, uuid, config.alias, app_data_func); - } - - // Submits the mvAppItem's "default" callback, if any, with user_data from - // the item config and app_data created by app_data_func (typically a lambda). - // The callback is only submitted if the item is enabled; on a disabled item, - // the call is effectively ignored. - template - void submitCallbackEx(AppDataFunc app_data_func) - { - if (!config.enabled) - return; - submitCallbackEx(config.callback, app_data_func); - } - - template - void submitCallback(AppDataType app_data); // submits the callback, if any, passing it app_data, and also user_data from the item config - - void submitCallback(); // submits the callback with app_data=None - - //----------------------------------------------------------------------------- - // config setters - //----------------------------------------------------------------------------- - virtual void setDataSource(mvUUID value); - - //----------------------------------------------------------------------------- - // scrolling support - //----------------------------------------------------------------------------- - void handleImmediateScroll(); - void handleDelayedScroll(); -}; - -inline bool mvClipPoint(float clipViewport[6], mvVec4& point) -{ - - if (point.x < clipViewport[0]) return true; - if (point.x > clipViewport[0] + clipViewport[2]) return true; - - if (point.y > clipViewport[1]) return true; - if (point.y < clipViewport[1] - clipViewport[3]) return true; - - if (point.z < clipViewport[4]) return true; - if (point.z > clipViewport[5]) return true; - - return false; -} - -inline constexpr const char* -GetEntityCommand(mvAppItemType type) -{ - switch (type) - { - - case mvAppItemType::mvButton: return "add_button"; - case mvAppItemType::mvCheckbox: return "add_checkbox"; - case mvAppItemType::mvInputText: return "add_input_text"; - case mvAppItemType::mvRadioButton: return "add_radio_button"; - case mvAppItemType::mvTabBar: return "add_tab_bar"; - case mvAppItemType::mvTab: return "add_tab"; - case mvAppItemType::mvImage: return "add_image"; - case mvAppItemType::mvMenuBar: return "add_menu_bar"; - case mvAppItemType::mvViewportMenuBar: return "add_viewport_menu_bar"; - case mvAppItemType::mvMenu: return "add_menu"; - case mvAppItemType::mvMenuItem: return "add_menu_item"; - case mvAppItemType::mvChildWindow: return "add_child_window"; - case mvAppItemType::mvGroup: return "add_group"; - case mvAppItemType::mvSliderFloat: return "add_slider_float"; - case mvAppItemType::mvSliderDouble: return "add_slider_double"; - case mvAppItemType::mvSliderInt: return "add_slider_int"; - case mvAppItemType::mvFilterSet: return "add_filter_set"; - case mvAppItemType::mvDragFloat: return "add_drag_float"; - case mvAppItemType::mvDragDouble: return "add_drag_double"; - case mvAppItemType::mvDragInt: return "add_drag_int"; - case mvAppItemType::mvInputFloat: return "add_input_float"; - case mvAppItemType::mvInputDouble: return "add_input_double"; - case mvAppItemType::mvInputInt: return "add_input_int"; - case mvAppItemType::mvColorEdit: return "add_color_edit"; - case mvAppItemType::mvClipper: return "add_clipper"; - case mvAppItemType::mvColorPicker: return "add_color_picker"; - case mvAppItemType::mvTooltip: return "add_tooltip"; - case mvAppItemType::mvCollapsingHeader: return "add_collapsing_header"; - case mvAppItemType::mvSeparator: return "add_separator"; - case mvAppItemType::mvListbox: return "add_listbox"; - case mvAppItemType::mvText: return "add_text"; - case mvAppItemType::mvCombo: return "add_combo"; - case mvAppItemType::mvPlot: return "add_plot"; - case mvAppItemType::mvSimplePlot: return "add_simple_plot"; - case mvAppItemType::mvDrawlist: return "add_drawlist"; - case mvAppItemType::mvWindowAppItem: return "add_window"; - case mvAppItemType::mvSelectable: return "add_selectable"; - case mvAppItemType::mvTreeNode: return "add_tree_node"; - case mvAppItemType::mvProgressBar: return "add_progress_bar"; - case mvAppItemType::mvSpacer: return "add_spacer"; - case mvAppItemType::mvImageButton: return "add_image_button"; - case mvAppItemType::mvTimePicker: return "add_time_picker"; - case mvAppItemType::mvDatePicker: return "add_date_picker"; - case mvAppItemType::mvColorButton: return "add_color_button"; - case mvAppItemType::mvFileDialog: return "add_file_dialog"; - case mvAppItemType::mvTabButton: return "add_tab_button"; - case mvAppItemType::mvDrawNode: return "add_draw_node"; - case mvAppItemType::mvNodeEditor: return "add_node_editor"; - case mvAppItemType::mvNode: return "add_node"; - case mvAppItemType::mvNodeAttribute: return "add_node_attribute"; - case mvAppItemType::mvTable: return "add_table"; - case mvAppItemType::mvTableColumn: return "add_table_column"; - case mvAppItemType::mvTableRow: return "add_table_row"; - case mvAppItemType::mvSyncedTables: return "add_synced_tables"; - case mvAppItemType::mvDrawLine: return "draw_line"; - case mvAppItemType::mvDrawArrow: return "draw_arrow"; - case mvAppItemType::mvDrawTriangle: return "draw_triangle"; - case mvAppItemType::mvDrawImageQuad: return "draw_image_quad"; - case mvAppItemType::mvDrawCircle: return "draw_circle"; - case mvAppItemType::mvDrawEllipse: return "draw_ellipse"; - case mvAppItemType::mvDrawBezierCubic: return "draw_bezier_cubic"; - case mvAppItemType::mvDrawBezierQuadratic: return "draw_bezier_quadratic"; - case mvAppItemType::mvDrawQuad: return "draw_quad"; - case mvAppItemType::mvDrawRect: return "draw_rectangle"; - case mvAppItemType::mvDrawText: return "draw_text"; - case mvAppItemType::mvDrawPolygon: return "draw_polygon"; - case mvAppItemType::mvDrawPolyline: return "draw_polyline"; - case mvAppItemType::mvDrawImage: return "draw_image"; - case mvAppItemType::mvDragFloatMulti: return "add_drag_floatx"; - case mvAppItemType::mvDragDoubleMulti: return "add_drag_doublex"; - case mvAppItemType::mvDragIntMulti: return "add_drag_intx"; - case mvAppItemType::mvSliderFloatMulti: return "add_slider_floatx"; - case mvAppItemType::mvSliderDoubleMulti: return "add_slider_doublex"; - case mvAppItemType::mvSliderIntMulti: return "add_slider_intx"; - case mvAppItemType::mvInputIntMulti: return "add_input_intx"; - case mvAppItemType::mvInputFloatMulti: return "add_input_floatx"; - case mvAppItemType::mvInputDoubleMulti: return "add_input_doublex"; - case mvAppItemType::mvDragPoint: return "add_drag_point"; - case mvAppItemType::mvDragRect: return "add_drag_rect"; - case mvAppItemType::mvDragLine: return "add_drag_line"; - case mvAppItemType::mvAnnotation: return "add_plot_annotation"; - case mvAppItemType::mvAxisTag: return "add_axis_tag"; - case mvAppItemType::mvLineSeries: return "add_line_series"; - case mvAppItemType::mvScatterSeries: return "add_scatter_series"; - case mvAppItemType::mvStemSeries: return "add_stem_series"; - case mvAppItemType::mvStairSeries: return "add_stair_series"; - case mvAppItemType::mvBarSeries: return "add_bar_series"; - case mvAppItemType::mvBarGroupSeries: return "add_bar_group_series"; - case mvAppItemType::mvErrorSeries: return "add_error_series"; - case mvAppItemType::mvCustomSeries: return "add_custom_series"; - case mvAppItemType::mvInfLineSeries: return "add_inf_line_series"; - case mvAppItemType::mvHeatSeries: return "add_heat_series"; - case mvAppItemType::mvImageSeries: return "add_image_series"; - case mvAppItemType::mvPieSeries: return "add_pie_series"; - case mvAppItemType::mvShadeSeries: return "add_shade_series"; - case mvAppItemType::mvLabelSeries: return "add_text_point"; - case mvAppItemType::mvHistogramSeries: return "add_histogram_series"; - case mvAppItemType::mv2dHistogramSeries: return "add_2d_histogram_series"; - case mvAppItemType::mvDigitalSeries: return "add_digital_series"; - case mvAppItemType::mvCandleSeries: return "add_candle_series"; - case mvAppItemType::mvAreaSeries: return "add_area_series"; - case mvAppItemType::mvColorMapScale: return "add_colormap_scale"; - case mvAppItemType::mvSlider3D: return "add_3d_slider"; - case mvAppItemType::mvKnobFloat: return "add_knob_float"; - case mvAppItemType::mvLoadingIndicator: return "add_loading_indicator"; - case mvAppItemType::mvNodeLink: return "add_node_link"; - case mvAppItemType::mvTextureRegistry: return "add_texture_registry"; - case mvAppItemType::mvStaticTexture: return "add_static_texture"; - case mvAppItemType::mvDynamicTexture: return "add_dynamic_texture"; - case mvAppItemType::mvStage: return "add_stage"; - case mvAppItemType::mvDrawLayer: return "add_draw_layer"; - case mvAppItemType::mvViewportDrawlist: return "add_viewport_drawlist"; - case mvAppItemType::mvFileExtension: return "add_file_extension"; - case mvAppItemType::mvPlotLegend: return "add_plot_legend"; - case mvAppItemType::mvPlotAxis: return "add_plot_axis"; - case mvAppItemType::mvHandlerRegistry: return "add_handler_registry"; - case mvAppItemType::mvKeyDownHandler: return "add_key_down_handler"; - case mvAppItemType::mvKeyPressHandler: return "add_key_press_handler"; - case mvAppItemType::mvKeyReleaseHandler: return "add_key_release_handler"; - case mvAppItemType::mvMouseMoveHandler: return "add_mouse_move_handler"; - case mvAppItemType::mvMouseWheelHandler: return "add_mouse_wheel_handler"; - case mvAppItemType::mvMouseClickHandler: return "add_mouse_click_handler"; - case mvAppItemType::mvMouseDoubleClickHandler: return "add_mouse_double_click_handler"; - case mvAppItemType::mvMouseDownHandler: return "add_mouse_down_handler"; - case mvAppItemType::mvMouseReleaseHandler: return "add_mouse_release_handler"; - case mvAppItemType::mvMouseDragHandler: return "add_mouse_drag_handler"; - case mvAppItemType::mvHoverHandler: return "add_item_hover_handler"; - case mvAppItemType::mvActiveHandler: return "add_item_active_handler"; - case mvAppItemType::mvFocusHandler: return "add_item_focus_handler"; - case mvAppItemType::mvVisibleHandler: return "add_item_visible_handler"; - case mvAppItemType::mvEditedHandler: return "add_item_edited_handler"; - case mvAppItemType::mvActivatedHandler: return "add_item_activated_handler"; - case mvAppItemType::mvDeactivatedHandler: return "add_item_deactivated_handler"; - case mvAppItemType::mvDeactivatedAfterEditHandler: return "add_item_deactivated_after_edit_handler"; - case mvAppItemType::mvToggledOpenHandler: return "add_item_toggled_open_handler"; - case mvAppItemType::mvClickedHandler: return "add_item_clicked_handler"; - case mvAppItemType::mvDoubleClickedHandler: return "add_item_double_clicked_handler"; - case mvAppItemType::mvDragPayload: return "add_drag_payload"; - case mvAppItemType::mvResizeHandler: return "add_item_resize_handler"; - case mvAppItemType::mvScrollHandler: return "add_item_scroll_handler"; - case mvAppItemType::mvFont: return "add_font"; - case mvAppItemType::mvFontRegistry: return "add_font_registry"; - case mvAppItemType::mvTheme: return "add_theme"; - case mvAppItemType::mvThemeColor: return "add_theme_color"; - case mvAppItemType::mvThemeStyle: return "add_theme_style"; - case mvAppItemType::mvThemeComponent: return "add_theme_component"; - case mvAppItemType::mvCharRemap: return "add_char_remap"; - case mvAppItemType::mvValueRegistry: return "add_value_registry"; - case mvAppItemType::mvIntValue: return "add_int_value"; - case mvAppItemType::mvFloatValue: return "add_float_value"; - case mvAppItemType::mvFloat4Value: return "add_float4_value"; - case mvAppItemType::mvInt4Value: return "add_int4_value"; - case mvAppItemType::mvBoolValue: return "add_bool_value"; - case mvAppItemType::mvStringValue: return "add_string_value"; - case mvAppItemType::mvDoubleValue: return "add_double_value"; - case mvAppItemType::mvDouble4Value: return "add_double4_value"; - case mvAppItemType::mvColorValue: return "add_color_value"; - case mvAppItemType::mvFloatVectValue: return "add_float_vect_value"; - case mvAppItemType::mvSeriesValue: return "add_series_value"; - case mvAppItemType::mvRawTexture: return "add_raw_texture"; - case mvAppItemType::mvSubPlots: return "add_subplots"; - case mvAppItemType::mvColorMap: return "add_colormap"; - case mvAppItemType::mvColorMapRegistry: return "add_colormap_registry"; - case mvAppItemType::mvColorMapButton: return "add_colormap_button"; - case mvAppItemType::mvColorMapSlider: return "add_colormap_slider"; - case mvAppItemType::mvTemplateRegistry: return "add_template_registry"; - case mvAppItemType::mvTableCell: return "add_table_cell"; - case mvAppItemType::mvItemHandlerRegistry: return "add_item_handler_registry"; - default: - { - IM_ASSERT(false && "No command"); - return "no command"; - } - } -} - -#define MV_BASE_COL_bgColor mvColor(37, 37, 38, 255) -#define MV_BASE_COL_lightBgColor mvColor(82, 82, 85, 255) -#define MV_BASE_COL_veryLightBgColor mvColor(90, 90, 95, 255) -#define MV_BASE_COL_panelColor mvColor(51, 51, 55, 255) -#define MV_BASE_COL_panelHoverColor mvColor(29, 151, 236, 103) -#define MV_BASE_COL_panelActiveColor mvColor(0, 119, 200, 153) -#define MV_BASE_COL_textColor mvColor(255, 255, 255, 255) -#define MV_BASE_COL_textDisabledColor mvColor(151, 151, 151, 255) -#define MV_BASE_COL_borderColor mvColor(78, 78, 78, 255) -#define mvImGuiCol_Text MV_BASE_COL_textColor -#define mvImGuiCol_TextSelectedBg MV_BASE_COL_panelActiveColor -#define mvImGuiCol_WindowBg MV_BASE_COL_bgColor -#define mvImGuiCol_ChildBg MV_BASE_COL_bgColor -#define mvImGuiCol_PopupBg MV_BASE_COL_bgColor -#define mvImGuiCol_Border MV_BASE_COL_borderColor -#define mvImGuiCol_BorderShadow MV_BASE_COL_borderColor -#define mvImGuiCol_FrameBg MV_BASE_COL_panelColor -#define mvImGuiCol_FrameBgHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_FrameBgActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_TitleBg MV_BASE_COL_bgColor -#define mvImGuiCol_TitleBgActive mvColor(15, 86, 135, 255) -#define mvImGuiCol_TitleBgCollapsed MV_BASE_COL_bgColor -#define mvImGuiCol_MenuBarBg MV_BASE_COL_panelColor -#define mvImGuiCol_ScrollbarBg MV_BASE_COL_panelColor -#define mvImGuiCol_ScrollbarGrab MV_BASE_COL_lightBgColor -#define mvImGuiCol_ScrollbarGrabHovered MV_BASE_COL_veryLightBgColor -#define mvImGuiCol_ScrollbarGrabActive MV_BASE_COL_veryLightBgColor -#define mvImGuiCol_CheckMark MV_BASE_COL_panelActiveColor -#define mvImGuiCol_SliderGrab MV_BASE_COL_panelHoverColor -#define mvImGuiCol_SliderGrabActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_Button MV_BASE_COL_panelColor -#define mvImGuiCol_ButtonHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_ButtonActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_Header MV_BASE_COL_panelColor -#define mvImGuiCol_HeaderHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_HeaderActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_Separator MV_BASE_COL_borderColor -#define mvImGuiCol_SeparatorHovered MV_BASE_COL_borderColor -#define mvImGuiCol_SeparatorActive MV_BASE_COL_borderColor -#define mvImGuiCol_ResizeGrip MV_BASE_COL_bgColor -#define mvImGuiCol_ResizeGripHovered MV_BASE_COL_panelColor -#define mvImGuiCol_Tab MV_BASE_COL_panelColor -#define mvImGuiCol_TabHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_TabActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_TabUnfocused MV_BASE_COL_panelColor -#define mvImGuiCol_TabUnfocusedActive MV_BASE_COL_panelActiveColor -#define mvImGuiCol_TabUnfocusedActiveOverline mvColor(0, 119, 200, 0) -#define mvImGuiCol_DockingPreview MV_BASE_COL_panelActiveColor -#define mvImGuiCol_DockingEmptyBg mvColor(51, 51, 51, 255) -#define mvImGuiCol_PlotLines MV_BASE_COL_panelActiveColor -#define mvImGuiCol_PlotLinesHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_PlotHistogram MV_BASE_COL_panelActiveColor -#define mvImGuiCol_PlotHistogramHovered MV_BASE_COL_panelHoverColor -#define mvImGuiCol_DragDropTarget mvColor(255, 255, 0, 179) -#define mvImGuiCol_DragDropTargetBg mvColor(0, 0, 0, 0) -#define mvImGuiCol_NavHighlight MV_BASE_COL_bgColor -#define mvImGuiCol_NavWindowingHighlight mvColor(255, 255, 255, 179) -#define mvImGuiCol_NavWindowingDimBg mvColor(204, 204, 204, 51) -#define mvImGuiCol_ModalWindowDimBg mvColor(37, 37, 38, 150) -#define mvImGuiCol_TableHeaderBg mvColor(48, 48, 51, 255) -#define mvImGuiCol_TableBorderStrong mvColor(79, 79, 89, 255) -#define mvImGuiCol_TableBorderLight mvColor(59, 59, 64, 255) -#define mvImGuiCol_TableRowBg mvColor(0, 0, 0, 0) -#define mvImGuiCol_TableRowBgAlt mvColor(255, 255, 255, 15) \ No newline at end of file diff --git a/src/mvAppItemCommons.h b/src/mvAppItemCommons.h deleted file mode 100644 index 2ee6f49d2..000000000 --- a/src/mvAppItemCommons.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "mvBasicWidgets.h" -#include "mvThemes.h" -#include "mvNodes.h" -#include "mvTables.h" -#include "mvDrawings.h" -#include "mvGlobalHandlers.h" -#include "mvItemHandlers.h" -#include "mvValues.h" -#include "mvTextureItems.h" -#include "mvFontItems.h" -#include "mvColors.h" -#include "mvPlotting.h" -#include "mvContainers.h" -#include "mvTimePicker.h" -#include "mvDatePicker.h" -#include "mvSlider3D.h" -#include "mvLoadingIndicator.h" -#include "mvFileDialog.h" -#include "mvFileExtension.h" diff --git a/src/mvAppItemState.cpp b/src/mvAppItemState.cpp deleted file mode 100644 index ade4606d1..000000000 --- a/src/mvAppItemState.cpp +++ /dev/null @@ -1,230 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvAppItemState.h" - -#include "mvAppItem.h" -#include "mvContext.h" -#include -// For ImGuiWindow -#include - -void -ResetAppItemState(mvAppItemState& state) -{ - state.hovered = false; - state.prevHovered = false; - state.active = false; - state.focused = false; - state.prevFocused = false; - state.leftclicked = false; - state.rightclicked = false; - state.middleclicked = false; - state.doubleclicked.fill(false); - state.visible = false; - state.edited = false; - state.activated = false; - state.deactivated = false; - state.deactivatedAfterEdit = false; - state.toggledOpenPure = state.toggledOpen = false; - state.mvRectSizeResized = false; - state.scrolledX = state.scrolledY = false; - state.isScrollingX = state.isScrollingY = false; -} - -void -UpdateAppItemState(mvAppItemState& state) -{ - state.lastFrameUpdate = GContext->frame; - state.prevHovered = state.hovered; - state.hovered = ImGui::IsItemHovered(); - state.active = ImGui::IsItemActive(); - state.prevFocused = state.focused; - state.focused = ImGui::IsItemFocused(); - if (state.focused) - { - GContext->focusedItem = state.parent->uuid; - } - state.leftclicked = ImGui::IsItemClicked(); - state.rightclicked = ImGui::IsItemClicked(1); - state.middleclicked = ImGui::IsItemClicked(2); - for (int i = 0; i < state.doubleclicked.size(); i++) - { - state.doubleclicked[i] = IsItemDoubleClicked(i); - } - state.visible = ImGui::IsItemVisible(); - state.edited = ImGui::IsItemEdited(); - state.activated = ImGui::IsItemActivated(); - state.deactivated = ImGui::IsItemDeactivated(); - state.deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit(); - state.toggledOpenPure = state.toggledOpen = ImGui::IsItemToggledOpen(); - state.rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y }; - state.rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y }; - state.rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y }; - state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - - if (state.mvPrevRectSize.x != state.rectSize.x || state.mvPrevRectSize.y != state.rectSize.y) { state.mvRectSizeResized = true; } - else state.mvRectSizeResized = false; - state.mvPrevRectSize = state.rectSize; -} - -void -UpdateAppItemScrollInfo(mvAppItemState& state) -{ - float scrollX = ImGui::GetScrollX(); - float scrollY = ImGui::GetScrollY(); - state.scrolledX = (scrollX != state.scrollPos.x); - state.scrolledY = (scrollY != state.scrollPos.y); - state.scrollPos = { scrollX, scrollY }; - state.scrollMax = { ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY() }; -} - -void -FillAppItemState(PyObject* dict, mvAppItemState& state, i32 applicableState) -{ - if (dict == nullptr) - return; - - bool valid = state.lastFrameUpdate == GContext->frame; - - PyDict_SetItemString(dict, "ok", mvPyObject(ToPyBool(state.ok))); - PyDict_SetItemString(dict, "pos", mvPyObject(ToPyPairII((i32)state.pos.x, (i32)state.pos.y))); - - if(applicableState & MV_STATE_HOVER) PyDict_SetItemString(dict, "hovered", mvPyObject(ToPyBool(valid ? state.hovered : false))); - if(applicableState & MV_STATE_ACTIVE) PyDict_SetItemString(dict, "active", mvPyObject(ToPyBool(valid ? state.active : false))); - if(applicableState & MV_STATE_FOCUSED) PyDict_SetItemString(dict, "focused", mvPyObject(ToPyBool(valid ? state.focused : false))); - if(applicableState & MV_STATE_CLICKED) - { - PyDict_SetItemString(dict, "clicked", mvPyObject(ToPyBool(valid ? state.leftclicked || state.rightclicked || state.middleclicked : false))); - PyDict_SetItemString(dict, "left_clicked", mvPyObject(ToPyBool(valid ? state.leftclicked : false))); - PyDict_SetItemString(dict, "right_clicked", mvPyObject(ToPyBool(valid ? state.rightclicked : false))); - PyDict_SetItemString(dict, "middle_clicked", mvPyObject(ToPyBool(valid ? state.middleclicked : false))); - } - if(applicableState & MV_STATE_VISIBLE) PyDict_SetItemString(dict, "visible", mvPyObject(ToPyBool(valid ? state.visible : false))); - if(applicableState & MV_STATE_EDITED) PyDict_SetItemString(dict, "edited", mvPyObject(ToPyBool(valid ? state.edited : false))); - if(applicableState & MV_STATE_ACTIVATED) PyDict_SetItemString(dict, "activated", mvPyObject(ToPyBool(valid ? state.activated : false))); - if(applicableState & MV_STATE_DEACTIVATED) PyDict_SetItemString(dict, "deactivated", mvPyObject(ToPyBool(valid ? state.deactivated : false))); - if(applicableState & MV_STATE_DEACTIVATEDAE) PyDict_SetItemString(dict, "deactivated_after_edit", mvPyObject(ToPyBool(valid ? state.deactivatedAfterEdit : false))); - if(applicableState & MV_STATE_TOGGLED_OPEN) PyDict_SetItemString(dict, "toggled_open", mvPyObject(ToPyBool(valid ? state.toggledOpen : false))); - if(applicableState & MV_STATE_RECT_MIN) PyDict_SetItemString(dict, "rect_min", mvPyObject(ToPyPairII((i32)state.rectMin.x, (i32)state.rectMin.y))); - if(applicableState & MV_STATE_RECT_MAX) PyDict_SetItemString(dict, "rect_max", mvPyObject(ToPyPairII((i32)state.rectMax.x, (i32)state.rectMax.y))); - if (applicableState & MV_STATE_RECT_SIZE) - { - PyDict_SetItemString(dict, "rect_size", mvPyObject(ToPyPairII((i32)state.rectSize.x, (i32)state.rectSize.y))); - PyDict_SetItemString(dict, "resized", mvPyObject(ToPyBool(valid ? state.mvRectSizeResized : false))); - } - if(applicableState & MV_STATE_CONT_AVAIL) PyDict_SetItemString(dict, "content_region_avail", mvPyObject(ToPyPairII((i32)state.contextRegionAvail.x, (i32)state.contextRegionAvail.y))); - - if(applicableState & MV_STATE_SCROLL) - { - PyDict_SetItemString(dict, "scrolled", mvPyObject(ToPyTPair(valid && state.scrolledX, valid && state.scrolledY))); - PyDict_SetItemString(dict, "is_scrolling", mvPyObject(ToPyTPair(valid && state.isScrollingX, valid && state.isScrollingY))); - PyDict_SetItemString(dict, "scroll_pos", mvPyObject(ToPyPair(state.scrollPos.x, state.scrollPos.y))); - PyDict_SetItemString(dict, "scroll_max", mvPyObject(ToPyPair(state.scrollMax.x, state.scrollMax.y))); - } - -} - -b8 -IsItemHovered(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.hovered; -} - -b8 -IsItemActive(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.active; -} - -b8 -IsItemFocused(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.focused; -} - -b8 -IsItemLeftClicked(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.leftclicked; -} - -b8 -IsItemRightClicked(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.rightclicked; -} - -b8 -IsItemMiddleClicked(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.middleclicked; -} - -b8 -IsItemVisible(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.visible; -} - -b8 -IsItemEdited(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.edited; -} - -b8 -IsItemActivated(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.activated; -} - -b8 -IsItemDeactivated(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.deactivated; -} - -b8 -IsItemDeactivatedAfterEdit(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.deactivatedAfterEdit; -} - -b8 -IsItemToogledOpen(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.toggledOpen; -} - -b8 -IsItemRectSizeResized(mvAppItemState& state, i32 frameDelay) -{ - if (state.lastFrameUpdate + frameDelay != GContext->frame) - return false; - return state.mvRectSizeResized; -} \ No newline at end of file diff --git a/src/mvAppItemState.h b/src/mvAppItemState.h deleted file mode 100644 index 3fd9cb24f..000000000 --- a/src/mvAppItemState.h +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once - -#include "mvCore.h" -#include - -#ifndef PyObject_HEAD -struct _object; -typedef _object PyObject; -#endif - -//----------------------------------------------------------------------------- -// forward declarations -//----------------------------------------------------------------------------- -class mvAppItem; -struct mvAppItemState; - -enum mvStateItems -{ - MV_STATE_NONE = 0, - MV_STATE_HOVER = 1 << 1, - MV_STATE_ACTIVE = 1 << 2, - MV_STATE_FOCUSED = 1 << 3, - MV_STATE_CLICKED = 1 << 4, - MV_STATE_VISIBLE = 1 << 5, - MV_STATE_EDITED = 1 << 6, - MV_STATE_ACTIVATED = 1 << 7, - MV_STATE_DEACTIVATED = 1 << 8, - MV_STATE_DEACTIVATEDAE = 1 << 9, - MV_STATE_TOGGLED_OPEN = 1 << 10, - MV_STATE_RECT_MIN = 1 << 11, - MV_STATE_RECT_MAX = 1 << 12, - MV_STATE_RECT_SIZE = 1 << 13, - MV_STATE_CONT_AVAIL = 1 << 14, - MV_STATE_SCROLL = 1 << 15, - MV_STATE_ALL = MV_STATE_HOVER |MV_STATE_ACTIVE |MV_STATE_FOCUSED |MV_STATE_CLICKED |MV_STATE_VISIBLE |MV_STATE_EDITED |MV_STATE_ACTIVATED |MV_STATE_DEACTIVATED |MV_STATE_DEACTIVATEDAE | - MV_STATE_TOGGLED_OPEN | MV_STATE_RECT_MIN |MV_STATE_RECT_MAX |MV_STATE_RECT_SIZE |MV_STATE_CONT_AVAIL |MV_STATE_SCROLL -}; - -//----------------------------------------------------------------------------- -// public API -//----------------------------------------------------------------------------- - -void FillAppItemState (PyObject* dict, mvAppItemState& state, i32 applicableState); // fills python dict with applicable state values -void ResetAppItemState (mvAppItemState& state); // reset values to false -void UpdateAppItemState(mvAppItemState& state); // standard imgui update -// Retrieves scroll info; only applicable to containers. Does NOT update state.lastFrameUpdate -// and therefore MUST be called in the same branch where that variable is updated -// by the caller (or where UpdateAppItemState() gets called). -void UpdateAppItemScrollInfo(mvAppItemState& state); - -// return actual value if frame is active -b8 IsItemHovered (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemActive (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemFocused (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemLeftClicked (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemRightClicked (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemMiddleClicked (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemVisible (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemEdited (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemActivated (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemDeactivated (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemDeactivatedAfterEdit(mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemToogledOpen (mvAppItemState& state, i32 frameDelay = 0); -b8 IsItemRectSizeResized (mvAppItemState& state, i32 frameDelay = 0); - -inline b8 IsItemDoubleClicked(ImGuiMouseButton mouse_button) -{ - return ImGui::IsMouseDoubleClicked(mouse_button) && ImGui::IsItemHovered(ImGuiHoveredFlags_None); -} - -struct mvAppItemState -{ - b8 hovered = false; - b8 prevHovered = false; - b8 active = false; - b8 focused = false; - b8 prevFocused = false; - b8 leftclicked = false; - b8 rightclicked = false; - b8 middleclicked = false; - std::array doubleclicked = {}; - b8 visible = false; - b8 edited = false; - b8 activated = false; - b8 deactivated = false; - b8 deactivatedAfterEdit = false; - b8 toggledOpen = false; - // This one is not reset by mvCollapsingHeader and mvTreeNode; also, not all items - // initialize it (but mvCollapsingHeader and mvTreeNode do, and they in fact are - // the only ones that must do it). Used as an extra flag by the two-way toggled open handler. - b8 toggledOpenPure = false; - b8 mvRectSizeResized = false; - b8 scrolledX = false; - b8 scrolledY = false; - // isScrolling flags are not implemented yet - we need support on ImGui side. - // They are here just as a reserved placeholder for future implementation. - b8 isScrollingX = false; - b8 isScrollingY = false; - mvVec2 rectMin = { 0.0f, 0.0f }; - mvVec2 rectMax = { 0.0f, 0.0f }; - mvVec2 rectSize = { 0.0f, 0.0f }; - mvVec2 mvPrevRectSize = { 0.0f, 0.0f }; - mvVec2 pos = { 0.0f, 0.0f }; - mvVec2 contextRegionAvail = { 0.0f, 0.0f }; - mvVec2 scrollPos = { 0.0f, 0.0f }; - mvVec2 scrollMax = { 0.0f, 0.0f }; - b8 ok = true; - i32 lastFrameUpdate = 0; // last frame update occured - mvAppItem* parent = nullptr; // hacky, but quick fix for widget handlers -}; diff --git a/src/mvAppItemTypes.inc b/src/mvAppItemTypes.inc deleted file mode 100644 index 68a2f73ea..000000000 --- a/src/mvAppItemTypes.inc +++ /dev/null @@ -1,171 +0,0 @@ -#pragma once - -#define MV_ITEM_TYPES \ - X( mvInputText ) \ - X( mvButton ) \ - X( mvRadioButton ) \ - X( mvTabBar ) \ - X( mvTab ) \ - X( mvImage ) \ - X( mvMenuBar ) \ - X( mvViewportMenuBar ) \ - X( mvMenu ) \ - X( mvMenuItem ) \ - X( mvChildWindow ) \ - X( mvGroup ) \ - X( mvSliderFloat ) \ - X( mvSliderInt ) \ - X( mvFilterSet ) \ - X( mvDragFloat ) \ - X( mvDragInt ) \ - X( mvInputFloat ) \ - X( mvInputInt ) \ - X( mvColorEdit ) \ - X( mvClipper ) \ - X( mvColorPicker ) \ - X( mvTooltip ) \ - X( mvCollapsingHeader ) \ - X( mvSeparator ) \ - X( mvCheckbox ) \ - X( mvListbox ) \ - X( mvText ) \ - X( mvCombo ) \ - X( mvPlot ) \ - X( mvSimplePlot ) \ - X( mvDrawlist ) \ - X( mvWindowAppItem ) \ - X( mvSelectable ) \ - X( mvTreeNode ) \ - X( mvProgressBar ) \ - X( mvSpacer ) \ - X( mvImageButton ) \ - X( mvTimePicker ) \ - X( mvDatePicker ) \ - X( mvColorButton ) \ - X( mvFileDialog ) \ - X( mvTabButton ) \ - X( mvDrawNode ) \ - X( mvNodeEditor ) \ - X( mvNode ) \ - X( mvNodeAttribute ) \ - X( mvTable ) \ - X( mvTableColumn ) \ - X( mvTableRow ) \ - X( mvSyncedTables ) \ - X( mvDrawLine ) \ - X( mvDrawArrow ) \ - X( mvDrawTriangle ) \ - X( mvDrawImageQuad ) \ - X( mvDrawCircle ) \ - X( mvDrawEllipse ) \ - X( mvDrawBezierCubic ) \ - X( mvDrawBezierQuadratic ) \ - X( mvDrawQuad ) \ - X( mvDrawRect ) \ - X( mvDrawText ) \ - X( mvDrawPolygon ) \ - X( mvDrawPolyline ) \ - X( mvDrawImage ) \ - X( mvDragFloatMulti ) \ - X( mvDragIntMulti ) \ - X( mvSliderFloatMulti ) \ - X( mvSliderIntMulti ) \ - X( mvInputIntMulti ) \ - X( mvInputFloatMulti ) \ - X( mvDragPoint ) \ - X( mvDragLine ) \ - X( mvDragRect ) \ - X( mvAnnotation ) \ - X( mvAxisTag ) \ - X( mvLineSeries ) \ - X( mvScatterSeries ) \ - X( mvStemSeries ) \ - X( mvStairSeries ) \ - X( mvBarSeries ) \ - X( mvBarGroupSeries ) \ - X( mvErrorSeries ) \ - X( mvInfLineSeries ) \ - X( mvHeatSeries ) \ - X( mvImageSeries ) \ - X( mvPieSeries ) \ - X( mvShadeSeries ) \ - X( mvLabelSeries ) \ - X( mvHistogramSeries ) \ - X( mvDigitalSeries ) \ - X( mv2dHistogramSeries ) \ - X( mvCandleSeries ) \ - X( mvAreaSeries ) \ - X( mvColorMapScale ) \ - X( mvSlider3D ) \ - X( mvKnobFloat ) \ - X( mvLoadingIndicator ) \ - X( mvNodeLink ) \ - X( mvTextureRegistry ) \ - X( mvStaticTexture ) \ - X( mvDynamicTexture ) \ - X( mvStage ) \ - X( mvDrawLayer ) \ - X( mvViewportDrawlist ) \ - X( mvFileExtension ) \ - X( mvPlotLegend ) \ - X( mvPlotAxis ) \ - X( mvHandlerRegistry ) \ - X( mvKeyDownHandler ) \ - X( mvKeyPressHandler ) \ - X( mvKeyReleaseHandler ) \ - X( mvMouseMoveHandler ) \ - X( mvMouseWheelHandler ) \ - X( mvMouseClickHandler ) \ - X( mvMouseDoubleClickHandler ) \ - X( mvMouseDownHandler ) \ - X( mvMouseReleaseHandler ) \ - X( mvMouseDragHandler ) \ - X( mvHoverHandler ) \ - X( mvActiveHandler ) \ - X( mvFocusHandler ) \ - X( mvVisibleHandler ) \ - X( mvEditedHandler ) \ - X( mvActivatedHandler ) \ - X( mvDeactivatedHandler ) \ - X( mvDeactivatedAfterEditHandler ) \ - X( mvToggledOpenHandler ) \ - X( mvClickedHandler ) \ - X( mvDoubleClickedHandler ) \ - X( mvScrollHandler ) \ - X( mvDragPayload ) \ - X( mvResizeHandler ) \ - X( mvFont ) \ - X( mvFontRegistry ) \ - X( mvTheme ) \ - X( mvThemeColor ) \ - X( mvThemeStyle ) \ - X( mvThemeComponent ) \ - X( mvCharRemap ) \ - X( mvValueRegistry ) \ - X( mvIntValue ) \ - X( mvFloatValue ) \ - X( mvFloat4Value ) \ - X( mvInt4Value ) \ - X( mvBoolValue ) \ - X( mvStringValue ) \ - X( mvDoubleValue ) \ - X( mvDouble4Value ) \ - X( mvColorValue ) \ - X( mvFloatVectValue ) \ - X( mvSeriesValue ) \ - X( mvRawTexture ) \ - X( mvSubPlots ) \ - X( mvColorMap ) \ - X( mvColorMapRegistry ) \ - X( mvColorMapButton ) \ - X( mvColorMapSlider ) \ - X( mvTemplateRegistry ) \ - X( mvTableCell ) \ - X( mvItemHandlerRegistry ) \ - X( mvInputDouble ) \ - X( mvInputDoubleMulti ) \ - X( mvDragDouble ) \ - X( mvDragDoubleMulti ) \ - X( mvSliderDouble ) \ - X( mvSliderDoubleMulti ) \ - X( mvCustomSeries ) diff --git a/src/mvAppleSpecifics.h b/src/mvAppleSpecifics.h deleted file mode 100644 index b44a8bb2c..000000000 --- a/src/mvAppleSpecifics.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#define GLFW_INCLUDE_NONE -#define GLFW_EXPOSE_NATIVE_COCOA -#include -#include - -#import -#import - -struct mvViewportData -{ - GLFWwindow* handle = nullptr; - CAMetalLayer* layer = nullptr; -}; - -struct mvGraphics_Metal -{ - MTLRenderPassDescriptor* renderPassDescriptor; - id commandQueue; - id device; -}; \ No newline at end of file diff --git a/src/mvBasicWidgets.cpp b/src/mvBasicWidgets.cpp deleted file mode 100644 index 8b0e3ba9e..000000000 --- a/src/mvBasicWidgets.cpp +++ /dev/null @@ -1,6255 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvBasicWidgets.h" - -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvContainers.h" -#include "mvItemHandlers.h" -#include "mvTextureItems.h" - -#include -#include - -static bool KnobFloat(const char* label, float* p_value, float v_min, float v_max, float v_step = 50.f); - -//----------------------------------------------------------------------------- -// [SECTION] get_item_configuration(...) specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::fill_configuration_dict(const mvSimplePlotConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "overlay", mvPyObject(ToPyString(inConfig.overlay))); - PyDict_SetItemString(outDict, "minscale", mvPyObject(ToPyFloat(inConfig.scaleMin))); - PyDict_SetItemString(outDict, "maxscale", mvPyObject(ToPyFloat(inConfig.scaleMax))); - PyDict_SetItemString(outDict, "histogram", mvPyObject(ToPyBool(inConfig.histogram))); - PyDict_SetItemString(outDict, "autosize", mvPyObject(ToPyBool(inConfig.autosize))); -} - -void -DearPyGui::fill_configuration_dict(const mvButtonConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_small = ToPyBool(inConfig.small_button); - mvPyObject py_arrow = ToPyBool(inConfig.arrow); - mvPyObject py_direction = ToPyInt(inConfig.direction); - mvPyObject py_repeat = ToPyBool(inConfig.repeat); - - - PyDict_SetItemString(outDict, "small", py_small); - PyDict_SetItemString(outDict, "arrow", py_arrow); - PyDict_SetItemString(outDict, "direction", py_direction); - PyDict_SetItemString(outDict, "repeat", py_repeat); -} - -void -DearPyGui::fill_configuration_dict(const mvComboConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_value = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_value); - }; - checkbitset("popup_align_left", ImGuiComboFlags_PopupAlignLeft, inConfig.flags); - checkbitset("no_arrow_button", ImGuiComboFlags_NoArrowButton, inConfig.flags); - checkbitset("no_preview", ImGuiComboFlags_NoPreview, inConfig.flags); - checkbitset("fit_width", ImGuiComboFlags_WidthFitPreview, inConfig.flags); - - long mode = (long)mvComboHeightMode::mvComboHeight_Largest; - if (inConfig.flags & ImGuiComboFlags_HeightSmall) mode = (long)mvComboHeightMode::mvComboHeight_Small; - else if (inConfig.flags & ImGuiComboFlags_HeightRegular) mode = (long)mvComboHeightMode::mvComboHeight_Regular; - else if (inConfig.flags & ImGuiComboFlags_HeightLarge) mode = (long)mvComboHeightMode::mvComboHeight_Large; - - mvPyObject py_height_mode = ToPyLong(mode); - mvPyObject py_items = ToPyList(inConfig.items); - PyDict_SetItemString(outDict, "height_mode", py_height_mode); - PyDict_SetItemString(outDict, "items", py_items); -} - -void -DearPyGui::fill_configuration_dict(const mvDragFloatConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyFloat(inConfig.minv); - mvPyObject py_max_value = ToPyFloat(inConfig.maxv); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvDragDoubleConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyDouble(inConfig.minv); - mvPyObject py_max_value = ToPyDouble(inConfig.maxv); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvDragIntConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyInt(inConfig.minv); - mvPyObject py_max_value = ToPyInt(inConfig.maxv); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvDragIntMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyInt(inConfig.minv); - mvPyObject py_max_value = ToPyInt(inConfig.maxv); - mvPyObject py_size = ToPyInt(inConfig.size); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - PyDict_SetItemString(outDict, "size", py_size); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvDragFloatMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyFloat(inConfig.minv); - mvPyObject py_max_value = ToPyFloat(inConfig.maxv); - mvPyObject py_size = ToPyInt(inConfig.size); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - PyDict_SetItemString(outDict, "size", py_size); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvDragDoubleMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - mvPyObject py_format = ToPyString(inConfig.format); - mvPyObject py_speed = ToPyFloat(inConfig.speed); - mvPyObject py_min_value = ToPyDouble(inConfig.minv); - mvPyObject py_max_value = ToPyDouble(inConfig.maxv); - mvPyObject py_size = ToPyInt(inConfig.size); - - PyDict_SetItemString(outDict, "format", py_format); - PyDict_SetItemString(outDict, "speed", py_speed); - PyDict_SetItemString(outDict, "min_value", py_min_value); - PyDict_SetItemString(outDict, "max_value", py_max_value); - PyDict_SetItemString(outDict, "size", py_size); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - mvPyObject py_result = ToPyBool(flags & flag); - PyDict_SetItemString(outDict, keyword, py_result); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderIntConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "vertical", mvPyObject(ToPyBool(inConfig.vertical))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyInt(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyInt(inConfig.maxv))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderIntMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyInt(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyInt(inConfig.maxv))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderFloatConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "vertical", mvPyObject(ToPyBool(inConfig.vertical))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyFloat(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyFloat(inConfig.maxv))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderFloatMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyFloat(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyFloat(inConfig.maxv))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvListboxConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - PyDict_SetItemString(outDict, "items", mvPyObject(ToPyList(inConfig.names))); - PyDict_SetItemString(outDict, "num_items", mvPyObject(ToPyInt(inConfig.itemsHeight))); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderDoubleConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "vertical", mvPyObject(ToPyBool(inConfig.vertical))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyDouble(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyDouble(inConfig.maxv))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvSliderDoubleMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyDouble(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyDouble(inConfig.maxv))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("clamped", ImGuiSliderFlags_AlwaysClamp, inConfig.flags); - checkbitset("no_input", ImGuiSliderFlags_NoInput, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvRadioButtonConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "items", mvPyObject(ToPyList(inConfig.itemnames))); - PyDict_SetItemString(outDict, "horizontal", mvPyObject(ToPyBool(inConfig.horizontal))); -} - -void -DearPyGui::fill_configuration_dict(const mvInputTextConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "hint", mvPyObject(ToPyString(inConfig.hint))); - PyDict_SetItemString(outDict, "multiline", mvPyObject(ToPyBool(inConfig.multiline))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_spaces", ImGuiInputTextFlags_CharsNoBlank, inConfig.flags); - checkbitset("uppercase", ImGuiInputTextFlags_CharsUppercase, inConfig.flags); - checkbitset("decimal", ImGuiInputTextFlags_CharsDecimal, inConfig.flags); - checkbitset("hexadecimal", ImGuiInputTextFlags_CharsHexadecimal, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("password", ImGuiInputTextFlags_Password, inConfig.flags); - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("scientific", ImGuiInputTextFlags_CharsScientific, inConfig.flags); - checkbitset("tab_input", ImGuiInputTextFlags_AllowTabInput, inConfig.flags); - - checkbitset("auto_select_all", ImGuiInputTextFlags_AutoSelectAll, inConfig.flags); // Select entire text when first taking mouse focus - checkbitset("ctrl_enter_for_new_line", ImGuiInputTextFlags_CtrlEnterForNewLine, inConfig.flags); // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). - checkbitset("no_horizontal_scroll", ImGuiInputTextFlags_NoHorizontalScroll, inConfig.flags); // Disable following the cursor horizontally - checkbitset("always_overwrite", ImGuiInputTextFlags_AlwaysOverwrite, inConfig.flags); // Overwrite mode - checkbitset("no_undo_redo", ImGuiInputTextFlags_NoUndoRedo, inConfig.flags); // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). - checkbitset("escape_clears_all", ImGuiInputTextFlags_EscapeClearsAll, inConfig.flags); // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) - checkbitset("elide_left", ImGuiInputTextFlags_ElideLeft, inConfig.flags); - - // TODO: Implement all of these (they seem really useful) - // Search this: ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); - // ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) - // ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) - // ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. - // ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. - // ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) - // ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) - -} - -void -DearPyGui::fill_configuration_dict(const mvInputIntConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "step", mvPyObject(ToPyInt(inConfig.step))); - PyDict_SetItemString(outDict, "step_fast", mvPyObject(ToPyInt(inConfig.step_fast))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyInt(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyInt(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvInputFloatConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "step", mvPyObject(ToPyFloat(inConfig.step))); - PyDict_SetItemString(outDict, "step_fast", mvPyObject(ToPyFloat(inConfig.step_fast))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyFloat(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyFloat(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvInputDoubleConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "step", mvPyObject(ToPyDouble(inConfig.step))); - PyDict_SetItemString(outDict, "step_fast", mvPyObject(ToPyDouble(inConfig.step_fast))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyDouble(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyDouble(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvInputFloatMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyFloat(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyFloat(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvInputDoubleMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyDouble(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyDouble(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvInputIntMultiConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "min_value", mvPyObject(ToPyInt(inConfig.minv))); - PyDict_SetItemString(outDict, "max_value", mvPyObject(ToPyInt(inConfig.maxv))); - PyDict_SetItemString(outDict, "min_clamped", mvPyObject(ToPyBool(inConfig.min_clamped))); - PyDict_SetItemString(outDict, "max_clamped", mvPyObject(ToPyBool(inConfig.max_clamped))); - PyDict_SetItemString(outDict, "size", mvPyObject(ToPyInt(inConfig.size))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, inConfig.flags); - checkbitset("readonly", ImGuiInputTextFlags_ReadOnly, inConfig.flags); - checkbitset("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, inConfig.flags); - checkbitset("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvTextConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "color", mvPyObject(ToPyColor(inConfig.color))); - PyDict_SetItemString(outDict, "wrap", mvPyObject(ToPyInt(inConfig.wrap))); - PyDict_SetItemString(outDict, "bullet", mvPyObject(ToPyBool(inConfig.bullet))); - PyDict_SetItemString(outDict, "show_label", mvPyObject(ToPyBool(inConfig.show_label))); -} - -void -DearPyGui::fill_configuration_dict(const mvSelectableConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("span_columns", ImGuiSelectableFlags_SpanAllColumns, inConfig.flags); - checkbitset("disable_popup_close", ImGuiSelectableFlags_NoAutoClosePopups, inConfig.flags); - checkbitset("select_on_nav", ImGuiSelectableFlags_SelectOnNav, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvTabButtonConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_reorder", ImGuiTabBarFlags_Reorderable, inConfig.flags); - checkbitset("leading", ImGuiTabItemFlags_Leading, inConfig.flags); - checkbitset("trailing", ImGuiTabItemFlags_Trailing, inConfig.flags); - checkbitset("no_tooltip", ImGuiTabItemFlags_NoTooltip, inConfig.flags); - checkbitset("unsaved_document", ImGuiTabItemFlags_UnsavedDocument, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvMenuItemConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "shortcut", mvPyObject(ToPyString(inConfig.shortcut))); - PyDict_SetItemString(outDict, "check", mvPyObject(ToPyBool(inConfig.check))); -} - -void -DearPyGui::fill_configuration_dict(const mvProgressBarConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "overlay", mvPyObject(ToPyString(inConfig.overlay))); -} - -void -DearPyGui::fill_configuration_dict(const mvImageConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "uv_min", mvPyObject(ToPyPair(inConfig.uv_min.x, inConfig.uv_min.y))); - PyDict_SetItemString(outDict, "uv_max", mvPyObject(ToPyPair(inConfig.uv_max.x, inConfig.uv_max.y))); - PyDict_SetItemString(outDict, "tint_color", mvPyObject(ToPyColor(inConfig.tintColor))); - PyDict_SetItemString(outDict, "border_color", mvPyObject(ToPyColor(inConfig.borderColor))); - PyDict_SetItemString(outDict, "texture_tag", mvPyObject(ToPyUUID(inConfig.texture.get()))); -} - -void -DearPyGui::fill_configuration_dict(const mvImageButtonConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "uv_min", mvPyObject(ToPyPair(inConfig.uv_min.x, inConfig.uv_min.y))); - PyDict_SetItemString(outDict, "uv_max", mvPyObject(ToPyPair(inConfig.uv_max.x, inConfig.uv_max.y))); - PyDict_SetItemString(outDict, "tint_color", mvPyObject(ToPyColor(inConfig.tintColor))); - PyDict_SetItemString(outDict, "background_color", mvPyObject(ToPyColor(inConfig.backgroundColor))); - PyDict_SetItemString(outDict, "texture_tag", mvPyObject(ToPyUUID(inConfig.texture.get()))); - PyDict_SetItemString(outDict, "frame_padding", mvPyObject(ToPyInt(inConfig.framePadding))); -} - -void -DearPyGui::fill_configuration_dict(const mvKnobFloatConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "min_scale", mvPyObject(ToPyFloat(inConfig.minv))); - PyDict_SetItemString(outDict, "max_scale", mvPyObject(ToPyFloat(inConfig.maxv))); - -} - -void -DearPyGui::fill_configuration_dict(const mvTooltipConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "delay", mvPyObject(ToPyFloat(inConfig.activation_delay))); - PyDict_SetItemString(outDict, "hide_on_activity", mvPyObject(ToPyBool(inConfig.hide_on_move))); -} - -//----------------------------------------------------------------------------- -// [SECTION] configure_item(...) specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::set_configuration(PyObject* inDict, mvSimplePlotConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "overlay")) outConfig.overlay = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "minscale")) outConfig.scaleMin = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "maxscale")) outConfig.scaleMax = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "histogram")) outConfig.histogram = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "autosize")) outConfig.autosize = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvButtonConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "small")) outConfig.small_button = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "arrow")) outConfig.arrow = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "direction")) outConfig.direction = static_cast(ToInt(item)); - if (PyObject* item = PyDict_GetItemString(inDict, "repeat")) outConfig.repeat = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvComboConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "items")) outConfig.items = ToStringVect(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "height_mode")) - { - long height_mode = (long)ToUUID(item); - if (height_mode == (long)mvComboHeightMode::mvComboHeight_Small) outConfig.flags = ImGuiComboFlags_HeightSmall; - else if (height_mode == (long)mvComboHeightMode::mvComboHeight_Regular) outConfig.flags = ImGuiComboFlags_HeightRegular; - else if (height_mode == (long)mvComboHeightMode::mvComboHeight_Large) outConfig.flags = ImGuiComboFlags_HeightLarge; - else outConfig.flags = ImGuiComboFlags_HeightLargest; - } - - // helpers for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag;}; - - flagop("popup_align_left", ImGuiComboFlags_PopupAlignLeft, outConfig.flags); - flagop("no_arrow_button", ImGuiComboFlags_NoArrowButton, outConfig.flags); - flagop("no_preview", ImGuiComboFlags_NoPreview, outConfig.flags); - flagop("fit_width", ImGuiComboFlags_WidthFitPreview, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragFloatConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToFloat(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragDoubleConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToDouble(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragIntConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragIntMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragFloatMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragDoubleMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "speed")) outConfig.speed = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderIntConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "vertical")) outConfig.vertical = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderIntMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderFloatConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "vertical")) outConfig.vertical = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToFloat(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderFloatMultiConfig& outConfig, mvAppItemInfo& info) -{ - - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderDoubleConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "vertical")) outConfig.vertical = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToDouble(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSliderDoubleMultiConfig& outConfig, mvAppItemInfo& info) -{ - - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("clamped", ImGuiSliderFlags_AlwaysClamp, outConfig.flags); - flagop("no_input", ImGuiSliderFlags_NoInput, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvListboxConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "num_items")) outConfig.itemsHeight = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "items")) - { - outConfig.names = ToStringVect(item); - outConfig.charNames.clear(); - for (const std::string& name : outConfig.names) - outConfig.charNames.emplace_back(name.c_str()); - - outConfig.index = 0; - outConfig.disabledindex = 0; - - int index = 0; - for (const auto& name : outConfig.names) - { - if (name == *outConfig.value) - { - outConfig.index = index; - outConfig.disabledindex = index; - break; - } - index++; - } - - if (!outConfig.value->empty()) - { - if (!outConfig.names.empty()) - { - bool oldValueFound = false; - for (int i = 0; i < outConfig.names.size(); i++) - { - if (outConfig.names[i] == *outConfig.value) - { - oldValueFound = true; - break; - } - } - - if(!oldValueFound) - *outConfig.value = outConfig.names[0]; - } - } - } - - if(outConfig.value->empty()) - { - if(!outConfig.names.empty()) - *outConfig.value = outConfig.names[0]; - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvRadioButtonConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "items")) - { - outConfig.itemnames = ToStringVect(item); - - // update index - outConfig.index = 0; - outConfig.disabledindex = 0; - - int index = 0; - for (const auto& name : outConfig.itemnames) - { - if (name == *outConfig.value) - { - outConfig.index = index; - outConfig.disabledindex = index; - break; - } - index++; - } - - } - if (PyObject* item = PyDict_GetItemString(inDict, "horizontal")) outConfig.horizontal = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputTextConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "hint")) outConfig.hint = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "multiline")) outConfig.multiline = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("no_spaces", ImGuiInputTextFlags_CharsNoBlank, outConfig.flags); - flagop("uppercase", ImGuiInputTextFlags_CharsUppercase, outConfig.flags); - flagop("decimal", ImGuiInputTextFlags_CharsDecimal, outConfig.flags); - flagop("hexadecimal", ImGuiInputTextFlags_CharsHexadecimal, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("password", ImGuiInputTextFlags_Password, outConfig.flags); - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("scientific", ImGuiInputTextFlags_CharsScientific, outConfig.flags); - flagop("tab_input", ImGuiInputTextFlags_AllowTabInput, outConfig.flags); - - flagop("auto_select_all", ImGuiInputTextFlags_AutoSelectAll, outConfig.flags); - flagop("ctrl_enter_for_new_line", ImGuiInputTextFlags_CtrlEnterForNewLine, outConfig.flags); - flagop("no_horizontal_scroll", ImGuiInputTextFlags_NoHorizontalScroll, outConfig.flags); - flagop("always_overwrite", ImGuiInputTextFlags_AlwaysOverwrite, outConfig.flags); - flagop("no_undo_redo", ImGuiInputTextFlags_NoUndoRedo, outConfig.flags); - flagop("escape_clears_all", ImGuiInputTextFlags_EscapeClearsAll, outConfig.flags); - flagop("elide_left", ImGuiInputTextFlags_ElideLeft, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputIntConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "step")) outConfig.step = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "step_fast")) outConfig.step_fast = ToInt(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToInt(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToInt(item); - outConfig.max_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputFloatConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "step")) outConfig.step = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "step_fast")) outConfig.step_fast = ToFloat(item); - - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToFloat(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToFloat(item); - outConfig.max_clamped = true; - } - - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputDoubleConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "step")) outConfig.step = ToDouble(item); - if (PyObject* item = PyDict_GetItemString(inDict, "step_fast")) outConfig.step_fast = ToDouble(item); - - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToDouble(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToDouble(item); - outConfig.max_clamped = true; - } - - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputFloatMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToFloat(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToFloat(item); - outConfig.max_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputDoubleMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToDouble(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToDouble(item); - outConfig.max_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvInputIntMultiConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "size")) outConfig.size = ToInt(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) - { - outConfig.minv = ToInt(item); - outConfig.min_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) - { - outConfig.maxv = ToInt(item); - outConfig.max_clamped = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "min_clamped")) outConfig.min_clamped = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_clamped")) outConfig.max_clamped = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("on_enter", ImGuiInputTextFlags_EnterReturnsTrue, outConfig.flags); - flagop("readonly", ImGuiInputTextFlags_ReadOnly, outConfig.flags); - flagop("accept_empty_input", ImGuiInputTextFlags_ParseEmptyRefVal, outConfig.flags); - flagop("display_empty_value", ImGuiInputTextFlags_DisplayEmptyRefVal, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTextConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "color")) outConfig.color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(inDict, "wrap")) outConfig.wrap = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "bullet")) outConfig.bullet = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "show_label")) outConfig.show_label = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvSelectableConfig& outConfig, mvAppItemInfo& info) -{ - if (inDict == nullptr) - return; - - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("span_columns", ImGuiSelectableFlags_SpanAllColumns, outConfig.flags); - flagop("disable_popup_close", ImGuiSelectableFlags_NoAutoClosePopups, outConfig.flags); - flagop("select_on_nav", ImGuiSelectableFlags_SelectOnNav, outConfig.flags); - - if (info.enabledLastFrame) - { - info.enabledLastFrame = false; - outConfig.flags &= ~ImGuiSelectableFlags_Disabled; - } - - if (info.disabledLastFrame) - { - info.disabledLastFrame = false; - outConfig.flags |= ImGuiSelectableFlags_Disabled; - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTabButtonConfig& outConfig) -{ - if (inDict == nullptr) - return; - - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("no_reorder", ImGuiTabItemFlags_NoReorder, outConfig.flags); - flagop("leading", ImGuiTabItemFlags_Leading, outConfig.flags); - flagop("trailing", ImGuiTabItemFlags_Trailing, outConfig.flags); - flagop("no_tooltip", ImGuiTabItemFlags_NoTooltip, outConfig.flags); - flagop("unsaved_document", ImGuiTabItemFlags_UnsavedDocument, outConfig.flags); - - if (outConfig.flags & ImGuiTabItemFlags_Leading && outConfig.flags & ImGuiTabItemFlags_Trailing) - outConfig.flags &= ~ImGuiTabItemFlags_Leading; -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvMenuItemConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "shortcut")) outConfig.shortcut = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "check")) outConfig.check = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvProgressBarConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "overlay")) outConfig.overlay = ToString(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvImageConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "uv_min")) outConfig.uv_min = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(inDict, "uv_max")) outConfig.uv_max = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(inDict, "tint_color")) outConfig.tintColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(inDict, "border_color")) outConfig.borderColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(inDict, "texture_tag")) - { - mvUUID textureUUID = GetIDFromPyObject(item); - if (textureUUID == MV_ATLAS_UUID) - { - outConfig.texture = std::make_shared(textureUUID); - } - else - { - outConfig.texture = GetRefItem(*GContext->itemRegistry, textureUUID); - if (!outConfig.texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(mvAppItemType::mvImage), "Texture not found.", nullptr); - } - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvImageButtonConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "uv_min")) outConfig.uv_min = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(inDict, "uv_max")) outConfig.uv_max = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(inDict, "tint_color")) outConfig.tintColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(inDict, "background_color")) outConfig.backgroundColor = ToColor(item); - if (PyObject* item = PyDict_GetItemString(inDict, "frame_padding")) outConfig.framePadding = ToInt(item); - if (PyObject* item = PyDict_GetItemString(inDict, "texture_tag")) - { - mvUUID textureUUID = GetIDFromPyObject(item); - if (textureUUID == MV_ATLAS_UUID) - { - outConfig.texture = std::make_shared(textureUUID); - } - else - { - outConfig.texture = GetRefItem(*GContext->itemRegistry, textureUUID); - if (!outConfig.texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(mvAppItemType::mvImageButton), "Texture not found.", nullptr); - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvTooltipConfig& outConfig, mvAppItemConfig& config) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvTooltip)], inDict)) - return; - - config.parent = GetIDFromPyObject(PyTuple_GetItem(inDict, 0)); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTooltipConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "delay")) outConfig.activation_delay = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "hide_on_activity")) outConfig.hide_on_move = ToBool(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvKnobFloatConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "min_value")) outConfig.minv = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_value")) outConfig.maxv = ToFloat(item); -} - -//----------------------------------------------------------------------------- -// [SECTION] required args specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::set_required_configuration(PyObject* inDict, mvImageConfig& outConfig) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvImage)], inDict)) - return; - - mvUUID textureUUID = GetIDFromPyObject(PyTuple_GetItem(inDict, 0)); - if (textureUUID == MV_ATLAS_UUID) - { - outConfig.texture = std::make_shared(textureUUID); - } - else - { - outConfig.texture = GetRefItem(*GContext->itemRegistry, textureUUID); - if (!outConfig.texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(mvAppItemType::mvImage), "Texture not found.", nullptr); - } -} - -void -DearPyGui::set_required_configuration(PyObject* inDict, mvImageButtonConfig& outConfig) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvImageButton)], inDict)) - return; - - mvUUID textureUUID = GetIDFromPyObject(PyTuple_GetItem(inDict, 0)); - if (textureUUID == MV_ATLAS_UUID) - { - outConfig.texture = std::make_shared(textureUUID); - } - else - { - outConfig.texture = GetRefItem(*GContext->itemRegistry, textureUUID); - if (!outConfig.texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(mvAppItemType::mvImageButton), "Texture not found.", nullptr); - } -} - -//----------------------------------------------------------------------------- -// [SECTION] positional args specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvComboConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvCombo)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - switch (i) - { - case 0: - outConfig.items = ToStringVect(item); - break; - - default: - break; - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvListboxConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvListbox)], inDict)) - return; - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - switch (i) - { - case 0: - outConfig.names = ToStringVect(PyTuple_GetItem(inDict, 0)); - outConfig.charNames.clear(); - for (const std::string& item : outConfig.names) - outConfig.charNames.emplace_back(item.c_str()); - break; - default: - break; - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvRadioButtonConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvRadioButton)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - switch (i) - { - case 0: - outConfig.itemnames = ToStringVect(item); - break; - - default: - break; - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvTextConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvText)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - switch (i) - { - case 0: - *outConfig.value = ToString(item); - break; - - default: - break; - } - } -} - -//----------------------------------------------------------------------------- -// [SECTION] data sources -//----------------------------------------------------------------------------- - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSimplePlotConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvComboConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvCheckboxConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragFloatConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* scrItem = GetItem((*GContext->itemRegistry), dataSource); - if (!scrItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(scrItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(scrItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragDoubleConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* scrItem = GetItem((*GContext->itemRegistry), dataSource); - if (!scrItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(scrItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(scrItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragIntConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragIntMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragFloatMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvDragDoubleMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderFloatConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderFloatMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderDoubleConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderDoubleMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderIntConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderIntMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvListboxConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvRadioButtonConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputTextConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputIntConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputFloatConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputDoubleConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvKnobFloatConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast * > (srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputFloatMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputDoubleMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvInputIntMultiConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvTextConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvSelectableConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvMenuItemConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvProgressBarConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -//----------------------------------------------------------------------------- -// [SECTION] draw commands -//----------------------------------------------------------------------------- - -void -DearPyGui::draw_simple_plot(ImDrawList* drawlist, mvAppItem& item, const mvSimplePlotConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ImGui::PushID(&item); - - if (config.histogram) - ImGui::PlotHistogram(item.info.internalLabel.c_str(), config.value->data(), (int)config.value->size(), 0, config.overlay.c_str(), - config.scaleMin, config.scaleMax, ImVec2((float)item.config.width, (float)item.config.height)); - else - ImGui::PlotLines(item.info.internalLabel.c_str(), config.value->data(), (int)config.value->size(), 0, config.overlay.c_str(), - config.scaleMin, config.scaleMax, ImVec2((float)item.config.width, (float)item.config.height)); - - ImGui::PopID(); - } - - //----------------------------------------------------------------------------- - // update state - // * only update if applicable - //----------------------------------------------------------------------------- - item.state.lastFrameUpdate = GContext->frame; - item.state.prevHovered = item.state.hovered; - item.state.hovered = ImGui::IsItemHovered(); - item.state.leftclicked = ImGui::IsItemClicked(); - item.state.rightclicked = ImGui::IsItemClicked(1); - item.state.middleclicked = ImGui::IsItemClicked(2); - for (int i = 0; i < item.state.doubleclicked.size(); i++) - { - item.state.doubleclicked[i] = IsItemDoubleClicked(i); - } - item.state.visible = ImGui::IsItemVisible(); - item.state.rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y }; - item.state.rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y }; - item.state.rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_button(ImDrawList* drawlist, mvAppItem& item, const mvButtonConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, config.repeat); - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - // push imgui id to prevent name collisions - ScopedID id(item.uuid); - - bool activated = false; - - if (config.small_button) - activated = ImGui::SmallButton(item.info.internalLabel.c_str()); - - else if (config.arrow) - activated = ImGui::ArrowButton(item.info.internalLabel.c_str(), config.direction); - - else - activated = ImGui::Button(item.info.internalLabel.c_str(), ImVec2((float)item.config.width, (float)item.config.height)); - - if (activated) - { - item.submitCallback(); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - - ImGui::PopItemFlag(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_combo(ImDrawList* drawlist, mvAppItem& item, mvComboConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - static std::vector disabled_items{}; - - // The second parameter is the label previewed before opening the combo. - bool activated = ImGui::BeginCombo(item.info.internalLabel.c_str(), config.value->c_str(), config.flags); - UpdateAppItemState(item.state); - - if (activated) - { - - for (const auto& name : item.config.enabled ? config.items : disabled_items) - { - bool is_selected = (*config.value == name); - if (ImGui::Selectable((name).c_str(), is_selected)) - { - if (item.config.enabled) { *config.value = name; } - - item.submitCallback(*config.value); - } - - item.state.edited = ImGui::IsItemEdited(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit(); - - // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) - if (is_selected) - ImGui::SetItemDefaultFocus(); - } - - ImGui::EndCombo(); - } - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_checkbox(ImDrawList* drawlist, mvAppItem& item, mvCheckboxConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - // push imgui id to prevent name collisions - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - if (ImGui::Checkbox(item.info.internalLabel.c_str(), item.config.enabled ? config.value.get() : &config.disabled_value)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_float(ImDrawList* drawlist, mvAppItem& item, mvDragFloatConfig& config) -{ - ScopedID id(item.uuid); - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (ImGui::DragFloat(item.info.internalLabel.c_str(), - item.config.enabled ? config.value.get() : &config.disabled_value, - config.speed, config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_double(ImDrawList* drawlist, mvAppItem& item, mvDragDoubleConfig& config) -{ - ScopedID id(item.uuid); - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (ImGui::DragScalar(item.info.internalLabel.c_str(), ImGuiDataType_Double, - item.config.enabled ? config.value.get() : &config.disabled_value, - config.speed, &config.minv, &config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_int(ImDrawList* drawlist, mvAppItem& item, mvDragIntConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (ImGui::DragInt(item.info.internalLabel.c_str(), - item.config.enabled ? config.value.get() : &config.disabled_value, config.speed, - config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_intx(ImDrawList* drawlist, mvAppItem& item, mvDragIntMultiConfig& config) -{ - //----------------------------------------------------------------------------- -// pre draw -//----------------------------------------------------------------------------- - -// show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 2, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - switch (config.size) - { - case 2: - activated = ImGui::DragInt2(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - case 3: - activated = ImGui::DragInt3(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - case 4: - activated = ImGui::DragInt4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - default: - break; - } - - if (activated) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_floatx(ImDrawList* drawlist, mvAppItem& item, mvDragFloatMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 2, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - switch (config.size) - { - case 2: - activated = ImGui::DragFloat2(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - case 3: - activated = ImGui::DragFloat3(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - case 4: - activated = ImGui::DragFloat4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.speed, config.minv, config.maxv, config.format.c_str(), flags); - break; - default: - break; - } - - if (activated) - { - item.submitCallback(*config.value); - } - } - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_doublex(ImDrawList* drawlist, mvAppItem& item, mvDragDoubleMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 2, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if(config.size > 1 && config.size < 5) - activated = ImGui::DragScalarN(item.info.internalLabel.c_str(), ImGuiDataType_Double, item.config.enabled ? config.value->data() : &config.disabled_value[0], config.size, config.speed, &config.minv, &config.maxv, config.format.c_str(), flags); - - if (activated) - { - item.submitCallback(*config.value); - } - } - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_float(ImDrawList* drawlist, mvAppItem& item, mvSliderFloatConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (config.vertical) - { - if ((float)item.config.height < 1.0f) - item.config.height = 100; - if ((float)item.config.width < 1.0f) - item.config.width = 20; - - if (ImGui::VSliderFloat(item.info.internalLabel.c_str(), ImVec2((float)item.config.width, (float)item.config.height), item.config.enabled ? config.value.get() : &config.disabled_value, config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - else - { - if (ImGui::SliderFloat(item.info.internalLabel.c_str(), item.config.enabled ? config.value.get() : &config.disabled_value, config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_double(ImDrawList* drawlist, mvAppItem& item, mvSliderDoubleConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (config.vertical) - { - if ((float)item.config.height < 1.0f) - item.config.height = 100; - if ((float)item.config.width < 1.0f) - item.config.width = 20; - - if (ImGui::VSliderScalar(item.info.internalLabel.c_str(), ImVec2((float)item.config.width, (float)item.config.height), ImGuiDataType_Double, item.config.enabled ? config.value.get() : &config.disabled_value, &config.minv, &config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - else - { - if (ImGui::SliderScalar(item.info.internalLabel.c_str(), ImGuiDataType_Double, item.config.enabled ? config.value.get() : &config.disabled_value, &config.minv, &config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_floatx(ImDrawList* drawlist, mvAppItem& item, mvSliderFloatMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 4, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - switch (config.size) - { - case 2: - activated = ImGui::SliderFloat2(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - case 3: - activated = ImGui::SliderFloat3(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - case 4: - activated = ImGui::SliderFloat4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - default: - break; - } - - if (activated) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_doublex(ImDrawList* drawlist, mvAppItem& item, mvSliderDoubleMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 4, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (config.size > 1 && config.size < 5) - activated = ImGui::SliderScalarN(item.info.internalLabel.c_str(), ImGuiDataType_Double, item.config.enabled ? config.value->data() : &config.disabled_value[0], config.size, &config.minv, &config.maxv, config.format.c_str(), flags); - - if (activated) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_int(ImDrawList* drawlist, mvAppItem& item, mvSliderIntConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - if (config.vertical) - { - if ((float)item.config.height < 1.0f) - item.config.height = 100; - if ((float)item.config.width < 1.0f) - item.config.width = 20; - - if (ImGui::VSliderInt(item.info.internalLabel.c_str(), ImVec2((float)item.config.width, (float)item.config.height), item.config.enabled ? config.value.get() : &config.disabled_value, config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - else - { - if (ImGui::SliderInt(item.info.internalLabel.c_str(), item.config.enabled ? config.value.get() : &config.disabled_value, config.minv, config.maxv, config.format.c_str(), flags)) - { - item.submitCallback(*config.value); - } - - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_slider_intx(ImDrawList* drawlist, mvAppItem& item, mvSliderIntMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool activated = false; - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 4, config.disabled_value); - - auto flags = config.flags | (item.config.enabled? 0 : ImGuiSliderFlags_NoInput); - - switch (config.size) - { - case 2: - activated = ImGui::SliderInt2(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - case 3: - activated = ImGui::SliderInt3(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - case 4: - activated = ImGui::SliderInt4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.minv, config.maxv, config.format.c_str(), flags); - break; - default: - break; - } - - if (activated) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_listbox(ImDrawList *drawlist, mvAppItem &item, mvListboxConfig &config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - if(!item.config.enabled) - { - config.disabled_value = *config.value; - config.disabledindex = config.index; - } - - item.handleImmediateScroll(); - - // remap Header to FrameBgActive - ImGuiStyle* style = &ImGui::GetStyle(); - ImGui::PushStyleColor(ImGuiCol_Header, style->Colors[ImGuiCol_FrameBgActive]); - - // We cannot use `ImGui::ListBox()` directly because to apply scrolling, - // we need access to the child window and `ListBox()` does not expose it. - // That's why we have to reimplement it using BeginListBox/EndListBox - // (as ImGui recommends it anyway). Ideally, the code below needs to be - // kept in sync, more or less, with `ImGui::ListBox()`. - int items_count = (int)config.names.size(); - int* current_item = item.config.enabled ? &config.index : &config.disabledindex; - - int height_in_items = config.itemsHeight; - if (height_in_items < 0) - height_in_items = ImMin(items_count, 7); - float height_in_items_f = (float)height_in_items + 0.25f; - ImVec2 size(0.0f, ImTrunc(ImGui::GetTextLineHeightWithSpacing() * height_in_items_f + ImGui::GetStyle().FramePadding.y * 2.0f)); - - if (ImGui::BeginListBox(item.info.internalLabel.c_str(), size)) - { - bool value_changed = false; - ImGuiListClipper clipper; - clipper.Begin(items_count, ImGui::GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. - clipper.IncludeItemByIndex(*current_item); - while (clipper.Step()) - { - for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) - { - ImGui::PushID(i); - const bool item_selected = (i == *current_item); - if (ImGui::Selectable(config.charNames[i], item_selected)) - { - *current_item = i; - value_changed = true; - } - if (item_selected) - ImGui::SetItemDefaultFocus(); - ImGui::PopID(); - } - } - - item.handleDelayedScroll(); - item.config.scrollXFlags = item.config.scrollYFlags = mvSetScrollFlags_None; - UpdateAppItemScrollInfo(item.state); - - ImGui::EndListBox(); - - if (value_changed) - { - ImGuiContext& g = *GImGui; - ImGui::MarkItemEdited(g.LastItemData.ID); - - *config.value = config.names[config.index]; - // TODO: we need to review how listbox behaves in the disabled state. It does - // not look good that it uses `index` rather than `disabledindex` here. Neither - // does `config.value` in `submitCallback` below. - config.disabled_value = config.names[config.index]; - item.submitCallback(*config.value); - } - } - - ImGui::PopStyleColor(); - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_radio_button(ImDrawList* drawlist, mvAppItem& item, mvRadioButtonConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ImGui::BeginGroup(); - - ScopedID id(item.uuid); - - if (!item.config.enabled) - { - config.disabled_value = *config.value; - config.disabledindex = config.index; - } - - for (size_t i = 0; i < config.itemnames.size(); i++) - { - if (config.horizontal && i != 0) - ImGui::SameLine(); - - if (ImGui::RadioButton(config.itemnames[i].c_str(), item.config.enabled ? &config.index : &config.disabledindex, (int)i)) - { - *config.value = config.itemnames[config.index]; - config.disabled_value = config.itemnames[config.index]; - item.submitCallback(*config.value); - } - - item.state.edited = ImGui::IsItemEdited(); - } - - ImGui::EndGroup(); - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_input_text(ImDrawList* drawlist, mvAppItem& item, mvInputTextConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - bool activated = false; - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - if (config.multiline) - config.hint.clear(); - - if (config.hint.empty()) - { - if (config.multiline) - activated = ImGui::InputTextMultiline(item.info.internalLabel.c_str(), config.value.get(), ImVec2((float)item.config.width, (float)item.config.height), flags); - else - activated = ImGui::InputText(item.info.internalLabel.c_str(), config.value.get(), flags); - } - else - activated = ImGui::InputTextWithHint(item.info.internalLabel.c_str(), config.hint.c_str(), config.value.get(), flags); - - if (activated) - { - item.submitCallback(*config.value); - } - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_input_int(ImDrawList* drawlist, mvAppItem& item, mvInputIntConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - if (ImGui::InputInt(item.info.internalLabel.c_str(), config.value.get(), config.step, config.step_fast, flags)) - { - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - else if (*config.value > config.maxv) *config.value = config.maxv; - } - else if (config.min_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - } - else if (config.max_clamped) - { - if (*config.value > config.maxv) *config.value = config.maxv; - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - item.submitCallback(*config.value); - } - } - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_input_floatx(ImDrawList* drawlist, mvAppItem& item, mvInputFloatMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - bool res = false; - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - switch (config.size) - { - case 2: - res = ImGui::InputFloat2(item.info.internalLabel.c_str(), config.value->data(), config.format.c_str(), flags); - break; - case 3: - res = ImGui::InputFloat3(item.info.internalLabel.c_str(), config.value->data(), config.format.c_str(), flags); - break; - case 4: - res = ImGui::InputFloat4(item.info.internalLabel.c_str(), config.value->data(), config.format.c_str(), flags); - break; - default: - break; - } - - if (res) - { - auto inital_value = *config.value; - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - else if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - else if (config.min_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - } - } - else if (config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - item.submitCallback(*config.value); - } - } - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); - -} - -void -DearPyGui::draw_input_float(ImDrawList* drawlist, mvAppItem& item, mvInputFloatConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - if (ImGui::InputFloat(item.info.internalLabel.c_str(), config.value.get(), config.step, config.step_fast, config.format.c_str(), flags)) - { - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - else if (*config.value > config.maxv) *config.value = config.maxv; - } - else if (config.min_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - } - else if (config.max_clamped) - { - if (*config.value > config.maxv) *config.value = config.maxv; - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - item.submitCallback(*config.value); - } - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_knob_float(ImDrawList* drawlist, mvAppItem& item, mvKnobFloatConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - if (!item.config.enabled) config.disabled_value = *config.value; - - if (KnobFloat(item.config.specifiedLabel.c_str(), item.config.enabled ? config.value.get() : &config.disabled_value, config.minv, config.maxv, config.step)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_input_double(ImDrawList* drawlist, mvAppItem& item, mvInputDoubleConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //-----------------------------------------------------------------------------(void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL) - { - - ScopedID id(item.uuid); - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - if (ImGui::InputScalar(item.info.internalLabel.c_str(), ImGuiDataType_Double, (void*)config.value.get(), (void*)(config.step > 0 ? &config.step : NULL), (void*)(config.step_fast > 0 ? &config.step_fast : NULL), config.format.c_str(), flags)) - { - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - else if (*config.value > config.maxv) *config.value = config.maxv; - } - else if (config.min_clamped) - { - if (*config.value < config.minv) *config.value = config.minv; - } - else if (config.max_clamped) - { - if (*config.value > config.maxv) *config.value = config.maxv; - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - item.submitCallback(*config.value); - } - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_input_doublex(ImDrawList* drawlist, mvAppItem& item, mvInputDoubleMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - bool res = false; - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - if (config.size > 1 && config.size < 5) - res = ImGui::InputScalarN(item.info.internalLabel.c_str(), ImGuiDataType_Double, config.value->data(), config.size, NULL, NULL, config.format.c_str(), flags); - - if (res) - { - auto inital_value = *config.value; - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - else if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - else if (config.min_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - } - } - else if (config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - item.submitCallback(*config.value); - } - } - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); - -} - -void -DearPyGui::draw_input_intx(ImDrawList* drawlist, mvAppItem& item, mvInputIntMultiConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool res = false; - - auto flags = item.config.enabled? config.flags : (config.flags & ~ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_ReadOnly); - - switch (config.size) - { - case 2: - res = ImGui::InputInt2(item.info.internalLabel.c_str(), config.value->data(), flags); - break; - case 3: - res = ImGui::InputInt3(item.info.internalLabel.c_str(), config.value->data(), flags); - break; - case 4: - res = ImGui::InputInt4(item.info.internalLabel.c_str(), config.value->data(), flags); - break; - default: - break; - } - - if (res) - { - auto inital_value = *config.value; - // determines clamped cases - if (config.min_clamped && config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - else if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - else if (config.min_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] < config.minv) config.value->data()[i] = config.minv; - } - } - else if (config.max_clamped) - { - for (int i = 0; i < 4; i++) - { - if (config.value->data()[i] > config.maxv) config.value->data()[i] = config.maxv; - } - } - - // If the widget is edited through ctrl+click mode the active value will be entered every frame. - // If the value is out of bounds the value will be overwritten with max or min so each frame the value will be switching between the - // ctrl+click value and the bounds value until the widget is not in ctrl+click mode. To prevent the callback from running every - // frame we check if the value was already submitted. - if (config.last_value != *config.value) - { - config.last_value = *config.value; - - item.submitCallback(*config.value); - } - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_text(ImDrawList* drawlist, mvAppItem& item, mvTextConfig& config) -{ - //----------------------------------------------------------------------------- - // predraw - //----------------------------------------------------------------------------- - if (!item.config.show) - return; - - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - item.info.previousCursorPos = ImGui::GetCursorPos(); - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - // this fixes the vertical text alignment issue according it DearImGui issue #2317 - ImGui::AlignTextToFramePadding(); - - const ImGuiStyle& style = ImGui::GetStyle(); - const float w = ImGui::CalcItemWidth(); - const float textVertCenter = ImGui::GetCursorPosY(); - const float valueEndX = ImGui::GetCursorPosX() + w; - - if (config.color.r >= 0.0f) - ImGui::PushStyleColor(ImGuiCol_Text, config.color.toVec4()); - - if (config.wrap == 0) - ImGui::PushTextWrapPos((float)config.wrap); - else if (config.wrap > 0) - ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + (float)config.wrap); - - if (config.bullet) - ImGui::Bullet(); - - //ImGui::Text("%s", _value.c_str()); - ImGui::TextUnformatted(config.value->c_str()); // this doesn't have a buffer size limit - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - if (config.wrap >= 0) - ImGui::PopTextWrapPos(); - - if (config.color.r >= 0.0f) - ImGui::PopStyleColor(); - - if (config.show_label) - { - ImGui::SameLine(); - ImGui::SetCursorPos({ valueEndX + style.ItemInnerSpacing.x, textVertCenter }); - ImGui::TextUnformatted(item.config.specifiedLabel.c_str()); - - //----------------------------------------------------------------------------- - // update state - locally updating the item state when label is used. We do not - // need to update RectMin parameter since its based on the text corner. - //----------------------------------------------------------------------------- - item.state.hovered |= ImGui::IsItemHovered(); - item.state.active |= ImGui::IsItemActive(); - item.state.focused |= ImGui::IsItemFocused(); - item.state.leftclicked |= ImGui::IsItemClicked(); - item.state.rightclicked |= ImGui::IsItemClicked(1); - item.state.middleclicked |= ImGui::IsItemClicked(2); - for (int i = 0; i < item.state.doubleclicked.size(); i++) - { - item.state.doubleclicked[i] = IsItemDoubleClicked(i); - } - item.state.visible |= ImGui::IsItemVisible(); - item.state.edited |= ImGui::IsItemEdited(); - item.state.activated |= ImGui::IsItemActivated(); - item.state.deactivated |= ImGui::IsItemDeactivated(); - item.state.deactivatedAfterEdit |= ImGui::IsItemDeactivatedAfterEdit(); - item.state.toggledOpen = ImGui::IsItemToggledOpen(); - item.state.rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y}; - item.state.rectSize = { item.state.rectMax.x - item.state.rectMin.x, item.state.rectMax.y - item.state.rectMin.y }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x + item.state.contextRegionAvail.x, ImGui::GetContentRegionAvail().y + item.state.contextRegionAvail.y }; - - if (item.state.mvPrevRectSize.x != item.state.rectSize.x || item.state.mvPrevRectSize.y != item.state.rectSize.y) { item.state.mvRectSizeResized = true; } - else item.state.mvRectSizeResized = false; - item.state.mvPrevRectSize = item.state.rectSize; - } - } - - //----------------------------------------------------------------------------- - // postdraw - //----------------------------------------------------------------------------- - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.info.previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - if (item.font) - { - ImGui::PopFont(); - } - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop payloads - apply_drag_drop(&item); -} - -void -DearPyGui::draw_selectable(ImDrawList* drawlist, mvAppItem& item, mvSelectableConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (ImGui::Selectable(item.info.internalLabel.c_str(), config.value.get(), config.flags, ImVec2((float)item.config.width, (float)item.config.height))) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_tab_button(ImDrawList* drawlist, mvAppItem& item, mvTabButtonConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (ImGui::TabItemButton(item.info.internalLabel.c_str(), config.flags)) - { - item.submitCallback(); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_menu_item(ImDrawList* drawlist, mvAppItem& item, mvMenuItemConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - // This is ugly and goes against our style system but its the only widget that ImGui chooses to push the disable color for us - // so we have to map our text disable color to the system text disable color, or we can create a new constant which goes agains our - // constants. - ImGui::PushStyleColor(ImGuiCol_TextDisabled, ImGui::GetStyleColorVec4(ImGuiCol_Text)); - - // create menu item and see if its selected - if (ImGui::MenuItem(item.info.internalLabel.c_str(), config.shortcut.c_str(), config.check ? config.value.get() : nullptr, item.config.enabled)) - { - item.submitCallback(*config.value); - } - - ImGui::PopStyleColor(); - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_progress_bar(ImDrawList* drawlist, mvAppItem& item, mvProgressBarConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - ImGui::ProgressBar(*config.value, ImVec2((float)item.config.width, (float)item.config.height), config.overlay.c_str()); - - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_image(ImDrawList* drawlist, mvAppItem& item, mvImageConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - if (config.texture && config.texture->state.ok) - { - // if width/height is not set by user, use texture dimensions - if (item.config.width == 0) - item.config.width = config.texture->config.width; - - if (item.config.height == 0) - item.config.height = config.texture->config.height; - - auto type = config.texture->type; - if (type == mvAppItemType::mvStaticTexture || - type == mvAppItemType::mvDynamicTexture || - type == mvAppItemType::mvRawTexture) - { - ImTextureRef texture = static_cast(config.texture.get())->getTexRef(); - ImGuiContext& g = *GImGui; - ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, (config.borderColor.a > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); - ImGui::PushStyleColor(ImGuiCol_Border, config.borderColor.toVec4()); - ImGui::ImageWithBg( - texture, - ImVec2((float)item.config.width, (float)item.config.height), - ImVec2(config.uv_min.x, config.uv_min.y), - ImVec2(config.uv_max.x, config.uv_max.y), - ImVec4(0, 0, 0, 0), - config.tintColor.toVec4()); - ImGui::PopStyleColor(); - ImGui::PopStyleVar(); - } - } - } - - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_image_button(ImDrawList* drawlist, mvAppItem& item, mvImageButtonConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - if (config.texture && config.texture->state.ok) - { - // if width/height is not set by user, use texture dimensions - if (item.config.width == 0) - item.config.width = config.texture->config.width; - - if (item.config.height == 0) - item.config.height = config.texture->config.height; - - auto type = config.texture->type; - if (type == mvAppItemType::mvStaticTexture || - type == mvAppItemType::mvDynamicTexture || - type == mvAppItemType::mvRawTexture) - { - ScopedID id(item.uuid); - - ImTextureRef texture = static_cast(config.texture.get())->getTexRef(); - - if (config.framePadding >= 0) - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)config.framePadding, (float)config.framePadding)); - - if (ImGui::ImageButton(item.info.internalLabel.c_str(), texture, ImVec2((float)item.config.width, (float)item.config.height), - ImVec2(config.uv_min.x, config.uv_min.y), ImVec2(config.uv_max.x, config.uv_max.y), - config.backgroundColor, config.tintColor)) - { - item.submitCallback(); - } - - if (config.framePadding >= 0) - ImGui::PopStyleVar(); - } - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_filter_set(ImDrawList* drawlist, mvAppItem& item, mvFilterSetConfig& config) -{ - ScopedID id(item.uuid); - - if (item.config.width != 0) - ImGui::PushItemWidth((float)item.config.width); - - if (config.imguiFilter.IsActive()) - { - for (auto& childset : item.childslots) - { - for (auto& child : childset) { - if (!config.imguiFilter.PassFilter(child->config.filter.c_str())) - continue; - - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } - } - } - else - { - for (auto& childset : item.childslots) - { - for (auto& child : childset) - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } - } - - if (item.config.width != 0) - ImGui::PopItemWidth(); -} - -void -DearPyGui::draw_separator(ImDrawList* drawlist, mvAppItem& item) -{ - if (!item.config.show) - return; - if (!item.config.specifiedLabel.empty()) { - ImGui::SeparatorText(item.config.specifiedLabel.c_str()); - } else { - ImGui::Separator(); - } -} - -void -DearPyGui::draw_spacer(ImDrawList* drawlist, mvAppItem& item) -{ - if (!item.config.show) - return; - if (item.config.width == 0 && item.config.height == 0) - ImGui::Spacing(); - else - ImGui::Dummy({ (float)item.config.width, (float)item.config.height }); -} - -void -DearPyGui::draw_menubar(ImDrawList* drawlist, mvAppItem& item) -{ - if (ImGui::BeginMenuBar()) - { - - item.state.lastFrameUpdate = GContext->frame; - item.state.visible = true; - - for (auto& item : item.childslots[1]) - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - ImGui::EndMenuBar(); - } -} - -void -DearPyGui::draw_viewport_menubar(ImDrawList* drawlist, mvAppItem& item) -{ - if (ImGui::BeginMainMenuBar()) - { - - for (auto& item : item.childslots[1]) - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - ImGui::EndMainMenuBar(); - } -} - -void -DearPyGui::draw_clipper(ImDrawList* drawlist, mvAppItem& item) -{ - ScopedID id(item.uuid); - - if (item.config.width != 0) - ImGui::PushItemWidth((float)item.config.width); - - - ImGuiListClipper clipper; - clipper.Begin((int)item.childslots[1].size()); - - while (clipper.Step()) - { - for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) - item.childslots[1][row_n]->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } - clipper.End(); - if (item.config.width != 0) - ImGui::PopItemWidth(); -} - -void -DearPyGui::draw_tooltip(ImDrawList* drawlist, mvAppItem& item) -{ - mvTooltip* tooltip = (mvTooltip*)&item; - // TODO: Check if this can be done with a way easier ImGui::SetItemTooltip() (and check "ImGui::BeginItemTooltip()") - if (ImGui::IsItemHovered() && item.config.show) - { - ImVec2 mousePos = ImGui::GetMousePos(); - - bool mouse_moved = (mousePos.x != tooltip->last_mouse_pos.x || mousePos.y != tooltip->last_mouse_pos.y); - bool state_changed = item.state.visible? - (tooltip->configData.hide_on_move && mouse_moved) : - (!tooltip->hovered_last_frame || mouse_moved); - - if (state_changed) - { - tooltip->hovered_last_frame = true; - tooltip->last_mouse_pos = mousePos; - tooltip->change_time = GContext->time; - } - // Note: state_changed and the following condition are not mutually - // exclusive and *may* both be true in the same frame - in particular, - // when activation_delay is zero. - if (GContext->time - tooltip->change_time >= tooltip->configData.activation_delay) - { - if (item.font) - static_cast(item.font.get())->pushFont(); - apply_local_theming(&item); - - // TODO: we should probably be using ImGuiTooltipFlags_OverridePrevious - if(ImGui::BeginTooltip()) - { - item.state.visible = true; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - item.state.rectSize = { ImGui::GetWindowSize().x, ImGui::GetWindowSize().y }; - - for (auto& item : item.childslots[1]) - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - ImGui::EndTooltip(); - } - else - { - item.state.visible = false; - item.state.contextRegionAvail = { 0.0f, 0.0f }; - item.state.rectSize = { 0.0f, 0.0f }; - } - item.state.lastFrameUpdate = GContext->frame; - - cleanup_local_theming(&item); - if (item.font) - ImGui::PopFont(); - } - } - else - { - tooltip->hovered_last_frame = false; - item.state.visible = false; - item.state.lastFrameUpdate = GContext->frame; - // TODO: should we reset rectSize and contextRegionAvail? - } - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); -} - -void -mvDragIntMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToIntVect(value); - while (temp.size() < 4) - temp.push_back(0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvDragFloatMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToFloatVect(value); - while (temp.size() < 4) - temp.push_back(0.0f); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvDragDoubleMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToDoubleVect(value); - while (temp.size() < 4) - temp.push_back(0.0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvSliderFloatMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToFloatVect(value); - while (temp.size() < 4) - temp.push_back(0.0f); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvSliderDoubleMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToDoubleVect(value); - while (temp.size() < 4) - temp.push_back(0.0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvSliderIntMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToIntVect(value); - while (temp.size() < 4) - temp.push_back(0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvListbox::setPyValue(PyObject *value) -{ - *configData.value = ToString(value); - - configData.index = 0; - configData.disabledindex = 0; - - int index = 0; - for (const auto& name : configData.names) - { - if (name == *configData.value) - { - configData.index = index; - configData.disabledindex = index; - break; - } - index++; - } -} - -void -mvRadioButton::setPyValue(PyObject* value) -{ - *configData.value = ToString(value); - - // update index - configData.index = 0; - configData.disabledindex = 0; - - int index = 0; - for (const auto& name : configData.itemnames) - { - if (name == *configData.value) - { - configData.index = index; - configData.disabledindex = index; - break; - } - index++; - } -} - -void -mvInputIntMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToIntVect(value); - while (temp.size() < 4) - temp.push_back(0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvInputFloatMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToFloatVect(value); - while (temp.size() < 4) - temp.push_back(0.0f); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvInputDoubleMulti::setPyValue(PyObject* value) -{ - std::vector temp = ToDoubleVect(value); - while (temp.size() < 4) - temp.push_back(0.0); - std::array temp_array; - for (size_t i = 0; i < temp_array.size(); i++) - temp_array[i] = temp[i]; - if (configData.value) - *configData.value = temp_array; - else - configData.value = std::make_shared>(temp_array); -} - -void -mvFilterSet::setPyValue(PyObject* value) -{ - auto str_value = ToString(value); - - int i = 0; - for (auto& character : str_value) - { - if (i > 254) - break; - - configData.imguiFilter.InputBuf[i] = character; - - ++i; - } - configData.imguiFilter.InputBuf[i] = 0; - configData.imguiFilter.Build(); -} - -void -mvSimplePlot::setPyValue(PyObject* value) -{ - *configData.value = ToFloatVect(value); - - if (!configData.autosize) - return; - if (!configData.value->empty()) - { - configData.scaleMax = configData.value->data()[0]; - configData.scaleMin = configData.value->data()[0]; - - for (auto& item : *configData.value) - { - if (item > configData.scaleMax) configData.scaleMax = item; - if (item < configData.scaleMin)configData.scaleMin = item; - } - } -} - -bool KnobFloat(const char* label, float* p_value, float v_min, float v_max, float v_step) { - - //@ocornut https://github.com/ocornut/imgui/issues/942 - ImGuiIO& io = ImGui::GetIO(); - ImGuiStyle& style = ImGui::GetStyle(); - - float radius_outer = 20.0f; - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec2 center = ImVec2(pos.x + radius_outer, pos.y + radius_outer); - float line_height = (strlen(label)) ? ImGui::GetTextLineHeight() : 0; - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - - float ANGLE_MIN = 3.141592f * 0.75f; - float ANGLE_MAX = 3.141592f * 2.25f; - - ImGui::InvisibleButton(label, ImVec2(radius_outer * 2, radius_outer * 2 + line_height + style.ItemInnerSpacing.y)); - bool value_changed = false; - bool is_active = ImGui::IsItemActive(); - bool is_hovered = ImGui::IsItemHovered(); - if (is_active && io.MouseDelta.x != 0.0f) { - if (v_step <= 0) v_step = 50.f; - float step = (v_max - v_min) / v_step; - *p_value += io.MouseDelta.x * step; - - if (*p_value < v_min) *p_value = v_min; - if (*p_value > v_max) *p_value = v_max; - value_changed = true; - } - else if (is_hovered && (io.MouseDoubleClicked[0] || io.MouseClicked[2])) { - *p_value = (v_max + v_min) * 0.5f; // reset value - value_changed = true; - } - - float t = (*p_value - v_min) / (v_max - v_min); - float angle = ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * t; - float angle_cos = cosf(angle), angle_sin = sinf(angle); - float radius_inner = radius_outer * 0.40f; - draw_list->AddCircleFilled(center, radius_outer, ImGui::GetColorU32(ImGuiCol_FrameBg), 16); - draw_list->AddLine(ImVec2(center.x + angle_cos * radius_inner, center.y + angle_sin * radius_inner), ImVec2(center.x + angle_cos * (radius_outer - 2), center.y + angle_sin * (radius_outer - 2)), ImGui::GetColorU32(ImGuiCol_SliderGrabActive), 2.0f); - draw_list->AddCircleFilled(center, radius_inner, ImGui::GetColorU32(is_active ? ImGuiCol_FrameBgActive : is_hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); - draw_list->AddText(ImVec2(pos.x, pos.y + radius_outer * 2 + style.ItemInnerSpacing.y), ImGui::GetColorU32(ImGuiCol_Text), label); - - if (is_active || is_hovered) { - ImGui::SetNextWindowPos(ImVec2(pos.x - style.WindowPadding.x, pos.y - line_height - style.ItemInnerSpacing.y - style.WindowPadding.y)); - if(ImGui::BeginTooltip()) { - ImGui::Text("%.3f", *p_value); - ImGui::EndTooltip(); - } - } - - return value_changed; -} \ No newline at end of file diff --git a/src/mvBasicWidgets.h b/src/mvBasicWidgets.h deleted file mode 100644 index 81990df9c..000000000 --- a/src/mvBasicWidgets.h +++ /dev/null @@ -1,1114 +0,0 @@ -#pragma once - -#include "mvItemRegistry.h" -#include - -struct mvSimplePlotConfig; -struct mvButtonConfig; -struct mvCheckboxConfig; -struct mvComboConfig; -struct mvDragFloatConfig; -struct mvDragIntConfig; -struct mvDragDoubleConfig; -struct mvDragFloatMultiConfig; -struct mvDragDoubleMultiConfig; -struct mvDragIntMultiConfig; -struct mvSliderIntConfig; -struct mvSliderFloatConfig; -struct mvSliderDoubleConfig; -struct mvSliderDoubleMultiConfig; -struct mvSliderFloatMultiConfig; -struct mvSliderIntMultiConfig; -struct mvListboxConfig; -struct mvRadioButtonConfig; -struct mvInputTextConfig; -struct mvInputIntConfig; -struct mvInputFloatConfig; -struct mvInputDoubleConfig; -struct mvInputFloatMultiConfig; -struct mvInputDoubleMultiConfig; -struct mvInputIntMultiConfig; -struct mvTextConfig; -struct mvSelectableConfig; -struct mvTabButtonConfig; -struct mvMenuItemConfig; -struct mvProgressBarConfig; -struct mvImageConfig; -struct mvImageButtonConfig; -struct mvFilterSetConfig; -struct mvTooltipConfig; -struct mvKnobFloatConfig; - -namespace DearPyGui -{ - // specific part of `get_item_configuration(...)` - void fill_configuration_dict(const mvSimplePlotConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvButtonConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvComboConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragFloatConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragFloatMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragDoubleConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragDoubleMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragIntConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragIntMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderIntConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderIntMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderFloatConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderFloatMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderDoubleConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSliderDoubleMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvListboxConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvRadioButtonConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputTextConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputIntConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputFloatConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputFloatMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputDoubleConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputDoubleMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvInputIntMultiConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvTextConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvSelectableConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvTabButtonConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvMenuItemConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvProgressBarConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvImageConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvImageButtonConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvKnobFloatConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvTooltipConfig& inConfig, PyObject* outDict); - - // specific part of `configure_item(...)` - void set_configuration(PyObject* inDict, mvSimplePlotConfig& outConfig); - void set_configuration(PyObject* inDict, mvButtonConfig& outConfig); - void set_configuration(PyObject* inDict, mvComboConfig& outConfig); - void set_configuration(PyObject* inDict, mvDragFloatConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvDragDoubleConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvDragIntConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvDragDoubleMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvDragFloatMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvDragIntMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderIntConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderIntMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderFloatConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderFloatMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderDoubleConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvSliderDoubleMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvListboxConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvRadioButtonConfig& outConfig); - void set_configuration(PyObject* inDict, mvInputTextConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputIntConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputFloatConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputFloatMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputDoubleConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputDoubleMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvInputIntMultiConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvTextConfig& outConfig); - void set_configuration(PyObject* inDict, mvSelectableConfig& outConfig, mvAppItemInfo& info); - void set_configuration(PyObject* inDict, mvTabButtonConfig& outConfig); - void set_configuration(PyObject* inDict, mvMenuItemConfig& outConfig); - void set_configuration(PyObject* inDict, mvProgressBarConfig& outConfig); - void set_configuration(PyObject* inDict, mvImageConfig& outConfig); - void set_configuration(PyObject* inDict, mvImageButtonConfig& outConfig); - void set_configuration(PyObject* inDict, mvTooltipConfig& outConfig); - void set_configuration(PyObject* inDict, mvKnobFloatConfig& outConfig); - - // positional args TODO: combine with above - void set_required_configuration(PyObject* inDict, mvImageConfig& outConfig); - void set_required_configuration(PyObject* inDict, mvImageButtonConfig& outConfig); - - // positional args TODO: combine with above - void set_positional_configuration(PyObject* inDict, mvComboConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvListboxConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvRadioButtonConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvTextConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvTooltipConfig& outConfig, mvAppItemConfig& config); - - // data source handling - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSimplePlotConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvComboConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvCheckboxConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragFloatConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragFloatMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragIntConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragIntMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragDoubleConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvDragDoubleMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderFloatConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderFloatMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderDoubleConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderDoubleMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderIntConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSliderIntMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvListboxConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvRadioButtonConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputTextConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputIntConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputFloatConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputDoubleConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputFloatMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputDoubleMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvInputIntMultiConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvTextConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvSelectableConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvMenuItemConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvProgressBarConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvKnobFloatConfig& outConfig); - - // draw commands - void draw_simple_plot (ImDrawList* drawlist, mvAppItem& item, const mvSimplePlotConfig& config); - void draw_button (ImDrawList* drawlist, mvAppItem& item, const mvButtonConfig& config); - void draw_combo (ImDrawList* drawlist, mvAppItem& item, mvComboConfig& config); - void draw_checkbox (ImDrawList* drawlist, mvAppItem& item, mvCheckboxConfig& config); - void draw_drag_float (ImDrawList* drawlist, mvAppItem& item, mvDragFloatConfig& config); - void draw_drag_floatx (ImDrawList* drawlist, mvAppItem& item, mvDragFloatMultiConfig& config); - void draw_drag_double (ImDrawList* drawlist, mvAppItem& item, mvDragDoubleConfig& config); - void draw_drag_doublex (ImDrawList* drawlist, mvAppItem& item, mvDragDoubleMultiConfig& config); - void draw_drag_int (ImDrawList* drawlist, mvAppItem& item, mvDragIntConfig& config); - void draw_drag_intx (ImDrawList* drawlist, mvAppItem& item, mvDragIntMultiConfig& config); - void draw_slider_float (ImDrawList* drawlist, mvAppItem& item, mvSliderFloatConfig& config); - void draw_slider_floatx(ImDrawList* drawlist, mvAppItem& item, mvSliderFloatMultiConfig& config); - void draw_slider_double(ImDrawList* drawlist, mvAppItem& item, mvSliderDoubleConfig& config); - void draw_slider_doublex(ImDrawList* drawlist, mvAppItem& item, mvSliderDoubleMultiConfig& config); - void draw_slider_int (ImDrawList* drawlist, mvAppItem& item, mvSliderIntConfig& config); - void draw_slider_intx (ImDrawList* drawlist, mvAppItem& item, mvSliderIntMultiConfig& config); - void draw_listbox (ImDrawList* drawlist, mvAppItem& item, mvListboxConfig& config); - void draw_radio_button (ImDrawList* drawlist, mvAppItem& item, mvRadioButtonConfig& config); - void draw_input_text (ImDrawList* drawlist, mvAppItem& item, mvInputTextConfig& config); - void draw_input_float (ImDrawList* drawlist, mvAppItem& item, mvInputFloatConfig& config); - void draw_input_floatx (ImDrawList* drawlist, mvAppItem& item, mvInputFloatMultiConfig& config); - void draw_input_double (ImDrawList* drawlist, mvAppItem& item, mvInputDoubleConfig& config); - void draw_input_doublex(ImDrawList* drawlist, mvAppItem& item, mvInputDoubleMultiConfig& config); - void draw_input_int (ImDrawList* drawlist, mvAppItem& item, mvInputIntConfig& config); - void draw_input_intx (ImDrawList* drawlist, mvAppItem& item, mvInputIntMultiConfig& config); - void draw_text (ImDrawList* drawlist, mvAppItem& item, mvTextConfig& config); - void draw_selectable (ImDrawList* drawlist, mvAppItem& item, mvSelectableConfig& config); - void draw_tab_button (ImDrawList* drawlist, mvAppItem& item, mvTabButtonConfig& config); - void draw_menu_item (ImDrawList* drawlist, mvAppItem& item, mvMenuItemConfig& config); - void draw_progress_bar (ImDrawList* drawlist, mvAppItem& item, mvProgressBarConfig& config); - void draw_image (ImDrawList* drawlist, mvAppItem& item, mvImageConfig& config); - void draw_image_button (ImDrawList* drawlist, mvAppItem& item, mvImageButtonConfig& config); - void draw_filter_set (ImDrawList* drawlist, mvAppItem& item, mvFilterSetConfig& config); - void draw_knob_float (ImDrawList* drawlist, mvAppItem& item, mvKnobFloatConfig& config); - void draw_separator (ImDrawList* drawlist, mvAppItem& item); - void draw_spacer (ImDrawList* drawlist, mvAppItem& item); - void draw_menubar (ImDrawList* drawlist, mvAppItem& item); - void draw_viewport_menubar(ImDrawList* drawlist, mvAppItem& item); - void draw_clipper (ImDrawList* drawlist, mvAppItem& item); - void draw_tooltip (ImDrawList* drawlist, mvAppItem& item); -} - -enum class mvComboHeightMode -{ - mvComboHeight_Small = 0L, - mvComboHeight_Regular, - mvComboHeight_Large, - mvComboHeight_Largest -}; - -struct mvSimplePlotConfig -{ - std::shared_ptr> value = std::make_shared>(std::vector{0.0f}); - std::string overlay; - float scaleMin = 0.0f; - float scaleMax = 0.0f; - bool histogram = false; - bool autosize = true; -}; - -struct mvButtonConfig -{ - ImGuiDir direction = ImGuiDir_Up; - bool small_button = false; - bool arrow = false; - bool repeat = false; -}; - -struct mvComboConfig -{ - ImGuiComboFlags flags = ImGuiComboFlags_None; - std::vector items; - bool popup_align_left = false; - bool no_preview = false; - bool fit_width = false; - std::shared_ptr value = std::make_shared(""); - std::string disabled_value; -}; - -struct mvCheckboxConfig -{ - std::shared_ptr value = std::make_shared(false); - bool disabled_value = false; -}; - -struct mvDragFloatConfig -{ - float speed = 1.0f; - float minv = 0.0f; - float maxv = 100.0f; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0.0f); - float disabled_value = 0.0f; -}; - -struct mvDragDoubleConfig -{ - float speed = 1.0f; - double minv = 0.0; - double maxv = 100.0; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0.0); - double disabled_value = 0.0; -}; - -struct mvDragIntConfig -{ - float speed = 1.0f; - int minv = 0; - int maxv = 100; - std::string format = "%d"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0); - int disabled_value = 0; -}; - -struct mvDragIntMultiConfig -{ - float speed = 1.0f; - int minv = 0; - int maxv = 100; - std::string format = "%d"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0, 0, 0, 0}); - int disabled_value[4]{}; -}; - -struct mvDragFloatMultiConfig -{ - float speed = 1.0f; - float minv = 0.0f; - float maxv = 100.0f; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 0.0f}); - float disabled_value[4]{}; -}; - -struct mvDragDoubleMultiConfig -{ - float speed = 1.0f; - double minv = 0.0; - double maxv = 100.0; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr>value = std::make_shared>(std::array{0.0, 0.0, 0.0, 0.0}); - double disabled_value[4]{}; -}; - -struct mvSliderIntConfig -{ - int minv = 0; - int maxv = 100; - std::string format = "%d"; - bool vertical = false; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0); - int disabled_value = 0; -}; - -struct mvSliderFloatConfig -{ - float minv = 0.0f; - float maxv = 100.0f; - std::string format = "%.3f"; - bool vertical = false; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0.0f); - float disabled_value = 0.0f; -}; - -struct mvSliderDoubleConfig -{ - double minv = 0.0; - double maxv = 100.0; - std::string format = "%.3f"; - bool vertical = false; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - std::shared_ptr value = std::make_shared(0.0); - double disabled_value = 0.0; -}; - -struct mvSliderFloatMultiConfig -{ - float minv = 0.0f; - float maxv = 100.0f; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 0.0f}); - float disabled_value[4]{}; -}; - -struct mvSliderIntMultiConfig -{ - int minv = 0; - int maxv = 100; - std::string format = "%d"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0, 0, 0, 0}); - int disabled_value[4]{}; -}; - -struct mvSliderDoubleMultiConfig -{ - double minv = 0.0; - double maxv = 100.0; - std::string format = "%d"; - ImGuiInputTextFlags flags = ImGuiSliderFlags_None; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0.0, 0.0, 0.0, 0.0}); - double disabled_value[4]{}; -}; - -struct mvListboxConfig -{ - std::vector names; - int itemsHeight = 3; // number of items to show (default -1) - std::vector charNames; - int index = 0; - int disabledindex = 0; - std::shared_ptr value = std::make_shared(""); - std::string disabled_value; -}; - -struct mvRadioButtonConfig -{ - std::vector itemnames; - bool horizontal = false; - int index = 0; - int disabledindex = 0; - std::shared_ptr value = std::make_shared(""); - std::string disabled_value = ""; -}; - -struct mvInputTextConfig -{ - std::string hint; - bool multiline = false; - ImGuiInputTextFlags flags = 0; - std::shared_ptr value = std::make_shared(""); - std::string disabled_value = ""; -}; - -struct mvInputIntConfig -{ - int step = 1; - int step_fast = 100; - int minv = 0; - int maxv = 100; - bool min_clamped = false; - bool max_clamped = false; - ImGuiInputTextFlags flags = 0; - int last_value = 0; - std::shared_ptr value = std::make_shared(0); - int disabled_value = 0; -}; - -struct mvInputFloatConfig -{ - float minv = 0.0f; - float maxv = 100.0f; - bool min_clamped = false; - bool max_clamped = false; - std::string format = "%.3f"; - float step = 0.1f; - float step_fast = 1.0f; - ImGuiInputTextFlags flags = 0; - float last_value = 0.0f; - std::shared_ptr value = std::make_shared(0.0f); - float disabled_value = 0.0f; -}; - -struct mvInputDoubleConfig -{ - double minv = 0.0; - double maxv = 100.0; - bool min_clamped = false; - bool max_clamped = false; - std::string format = "%.3f"; - double step = 0.1; - double step_fast = 1.0; - ImGuiInputTextFlags flags = 0; - double last_value = 0.0; - std::shared_ptr value = std::make_shared(0.0); - double disabled_value = 0.0; -}; - -struct mvInputFloatMultiConfig -{ - float minv = 0.0f; - float maxv = 100.0f; - bool min_clamped = false; - bool max_clamped = false; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = 0; - std::array last_value = { 0.0f, 0.0f, 0.0f, 0.0f }; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 0.0f}); - float disabled_value[4]{}; -}; - -struct mvInputIntMultiConfig -{ - int minv = 0; - int maxv = 100; - bool min_clamped = false; - bool max_clamped = false; - ImGuiInputTextFlags flags = 0; - std::array last_value = { 0, 0, 0, 0 }; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0, 0, 0, 0}); - int disabled_value[4]{}; -}; - -struct mvInputDoubleMultiConfig -{ - double minv = 0.0; - double maxv = 100.0; - bool min_clamped = false; - bool max_clamped = false; - std::string format = "%.3f"; - ImGuiInputTextFlags flags = 0; - std::array last_value = { 0.0f, 0.0f, 0.0f, 0.0f }; - int size = 4; - std::shared_ptr> value = std::make_shared>(std::array{0.0, 0.0, 0.0, 0.0}); - double disabled_value[4]{}; -}; - -struct mvTextConfig -{ - mvColor color = { -1.0f, 0.0f, 0.0f, 1.0f }; - int wrap = -1; - bool bullet = false; - bool show_label = false; - std::shared_ptr value = std::make_shared(""); - std::string disabled_value = ""; -}; - -struct mvSelectableConfig -{ - ImGuiSelectableFlags flags = ImGuiSelectableFlags_None; - std::shared_ptr value = std::make_shared(false); - bool disabled_value = false; -}; - -struct mvTabButtonConfig -{ - ImGuiTabItemFlags flags = ImGuiTabItemFlags_None; -}; - -struct mvMenuItemConfig -{ - std::string shortcut; - bool check = false; - std::shared_ptr value = std::make_shared(false); - bool disabled_value = false; -}; - -struct mvProgressBarConfig -{ - std::string overlay; - std::shared_ptr value = std::make_shared(0.0f); - float disabled_value = 0.0f; -}; - -struct mvImageConfig -{ - // pointer to existing item or internal - std::shared_ptr texture = nullptr; - mvVec2 uv_min = { 0.0f, 0.0f }; - mvVec2 uv_max = { 1.0f, 1.0f }; - mvColor tintColor = { 1.0f, 1.0f, 1.0f, 1.0f }; - mvColor borderColor = { 0.0f, 0.0f, 0.0f, 0.0f }; -}; - -struct mvImageButtonConfig -{ - // pointer to existing item or internal - std::shared_ptr texture = nullptr; - mvVec2 uv_min = { 0.0f, 0.0f }; - mvVec2 uv_max = { 1.0f, 1.0f }; - mvColor tintColor = { 1.0f, 1.0f, 1.0f, 1.0f }; - mvColor backgroundColor = { 0.0f, 0.0f, 0.0f, 0.0f }; - int framePadding = -1; -}; - -struct mvFilterSetConfig -{ - ImGuiTextFilter imguiFilter; -}; - -struct mvTooltipConfig -{ - float activation_delay = 0.0f; - bool hide_on_move = false; -}; - -struct mvKnobFloatConfig -{ - std::shared_ptr value = std::make_shared(0.0f); - float disabled_value = 0.0f; - float minv = 0.0f; - float maxv = 100.0f; - float step = 50.0f; -}; - -//----------------------------------------------------------------------------- -// Old Classes, in the process of removing OOP crap -//----------------------------------------------------------------------------- - -class mvSimplePlot : public mvAppItem -{ -public: - mvSimplePlotConfig configData{}; - explicit mvSimplePlot(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_simple_plot(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyList(*configData.value); } - void setPyValue(PyObject* value) override; -}; - -class mvButton : public mvAppItem -{ -public: - mvButtonConfig configData{}; - explicit mvButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_button(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvCombo : public mvAppItem -{ -public: - mvComboConfig configData{}; - explicit mvCombo(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_combo(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyString(*configData.value); }; - void setPyValue(PyObject* value) override { *configData.value = ToString(value); } -}; - -class mvCheckbox : public mvAppItem -{ -public: - mvCheckboxConfig configData{}; - explicit mvCheckbox(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_checkbox(drawlist, *this, configData); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override{ return ToPyBool(*configData.value); } -}; - -class mvDragFloat : public mvAppItem -{ -public: - mvDragFloatConfig configData{}; - explicit mvDragFloat(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_float(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override{ return ToPyFloat(*configData.value); } - void setPyValue(PyObject* value) override{ *configData.value = ToFloat(value); } -}; - -class mvDragDouble : public mvAppItem -{ -public: - mvDragDoubleConfig configData{}; - explicit mvDragDouble(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_double(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyDouble(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToDouble(value); } -}; - -class mvDragInt : public mvAppItem -{ - -public: - mvDragIntConfig configData{}; - explicit mvDragInt(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_int(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyInt(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToInt(value); } - -}; - -class mvDragIntMulti : public mvAppItem -{ - -public: - mvDragIntMultiConfig configData{}; - explicit mvDragIntMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_intx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyIntList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvDragFloatMulti : public mvAppItem -{ -public: - mvDragFloatMultiConfig configData{}; - explicit mvDragFloatMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_floatx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvDragDoubleMulti : public mvAppItem -{ -public: - mvDragDoubleMultiConfig configData{}; - explicit mvDragDoubleMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_doublex(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvSliderFloat : public mvAppItem -{ -public: - mvSliderFloatConfig configData{}; - explicit mvSliderFloat(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_float(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloat(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToFloat(value); } -}; - -class mvSliderDouble : public mvAppItem -{ -public: - mvSliderDoubleConfig configData{}; - explicit mvSliderDouble(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_double(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyDouble(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToDouble(value); } -}; - -class mvSliderFloatMulti : public mvAppItem -{ -public: - mvSliderFloatMultiConfig configData{}; - explicit mvSliderFloatMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_floatx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvSliderDoubleMulti : public mvAppItem -{ -public: - mvSliderDoubleMultiConfig configData{}; - explicit mvSliderDoubleMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_doublex(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvSliderInt : public mvAppItem -{ -public: - mvSliderIntConfig configData{}; - explicit mvSliderInt(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_int(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyInt(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToInt(value); } -}; - -class mvSliderIntMulti : public mvAppItem -{ -public: - mvSliderIntMultiConfig configData{}; - explicit mvSliderIntMulti(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_slider_intx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyIntList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvListbox : public mvAppItem -{ -public: - mvListboxConfig configData{}; - explicit mvListbox(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_listbox(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData);} - void handleSpecificKeywordArgs(PyObject* dict) override{ DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setPyValue(PyObject* value) override; - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override {return ToPyString(*configData.value);} -}; - -class mvRadioButton : public mvAppItem -{ -public: - mvRadioButtonConfig configData{}; - explicit mvRadioButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_radio_button(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setPyValue(PyObject* value) override; - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyString(*configData.value); } -}; - -class mvInputText : public mvAppItem -{ - -public: - mvInputTextConfig configData{}; - explicit mvInputText(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_text(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override{ return ToPyString(*configData.value); } - void setPyValue(PyObject* value) override{ *configData.value = ToString(value); } -}; - -class mvInputInt : public mvAppItem -{ -public: - mvInputIntConfig configData{}; - explicit mvInputInt(mvUUID uuid) : mvAppItem(uuid) { configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_int(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override{ return ToPyInt(*configData.value); } - void setPyValue(PyObject* value) override{ *configData.value = ToInt(value); configData.last_value = *configData.value;} -}; - -class mvInputIntMulti : public mvAppItem -{ -public: - mvInputIntMultiConfig configData{}; - explicit mvInputIntMulti(mvUUID uuid) : mvAppItem(uuid){ configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_intx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override{ return ToPyIntList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvInputFloat : public mvAppItem -{ -public: - mvInputFloatConfig configData{}; - explicit mvInputFloat(mvUUID uuid) : mvAppItem(uuid) { configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_float(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloat(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToFloat(value); configData.last_value = *configData.value; } -}; - -class mvInputFloatMulti : public mvAppItem -{ -public: - mvInputFloatMultiConfig configData{}; - explicit mvInputFloatMulti(mvUUID uuid) : mvAppItem(uuid) { configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_floatx(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvInputDouble : public mvAppItem -{ -public: - mvInputDoubleConfig configData{}; - explicit mvInputDouble(mvUUID uuid) : mvAppItem(uuid) { configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_double(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyDouble(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToDouble(value); configData.last_value = *configData.value; } -}; - -class mvInputDoubleMulti : public mvAppItem -{ -public: - mvInputDoubleMultiConfig configData{}; - explicit mvInputDoubleMulti(mvUUID uuid) : mvAppItem(uuid) { configData.last_value = *configData.value; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_input_doublex(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloatList(configData.value->data(), 4); } - void setPyValue(PyObject* value) override; -}; - -class mvText : public mvAppItem -{ - -public: - mvTextConfig configData{}; - explicit mvText(mvUUID uuid) : mvAppItem(uuid) { *configData.value = "Not Specified"; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_text(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyString(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToString(value); } -}; - -class mvSelectable : public mvAppItem -{ -public: - mvSelectableConfig configData{}; - explicit mvSelectable(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_selectable(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, info); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } -}; - -class mvTabButton : public mvAppItem -{ -public: - mvTabButtonConfig configData{}; - explicit mvTabButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_tab_button(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvMenuItem : public mvAppItem -{ - -public: - mvMenuItemConfig configData{}; - explicit mvMenuItem(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_menu_item(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } -}; - -class mvProgressBar : public mvAppItem -{ -public: - mvProgressBarConfig configData{}; - explicit mvProgressBar(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_progress_bar(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloat(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToFloat(value); } -}; - -class mvImage : public mvAppItem -{ -public: - mvImageConfig configData{}; - mvImage(mvUUID uuid) : mvAppItem(uuid){ config.width = 0; config.height = 0;} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_image(drawlist, *this, configData); } - void handleSpecificRequiredArgs(PyObject* dict) override { DearPyGui::set_required_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvImageButton : public mvAppItem -{ -public: - mvImageButtonConfig configData{}; - mvImageButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_image_button(drawlist, *this, configData); } - void handleSpecificRequiredArgs(PyObject* dict) override { DearPyGui::set_required_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvKnobFloat : public mvAppItem -{ - -public: - mvKnobFloatConfig configData{}; - explicit mvKnobFloat(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_knob_float(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return ToPyFloat(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToFloat(value); } -}; - -class mvFilterSet : public mvAppItem -{ -public: - mvFilterSetConfig configData{}; - explicit mvFilterSet(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_filter_set(drawlist, *this, configData); } - void setPyValue(PyObject* value) override; - PyObject* getPyValue() override { return ToPyString(std::string(configData.imguiFilter.InputBuf)); } -}; - -class mvTooltip : public mvAppItem -{ -public: - mvTooltipConfig configData{}; - explicit mvTooltip(mvUUID uuid) : mvAppItem(uuid) { config.show = true; } //has to be shown to check hovering - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_tooltip(drawlist, *this); } - void handleSpecificRequiredArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData, config); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - -// TODO: make these members private - double change_time = 0; - bool hovered_last_frame = false; - ImVec2 last_mouse_pos; -}; - -class mvSeparator : public mvAppItem -{ -public: - explicit mvSeparator(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_separator(drawlist, *this); } -}; - -class mvSpacer : public mvAppItem -{ -public: - explicit mvSpacer(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_spacer(drawlist, *this); } - -}; - -class mvMenuBar : public mvAppItem -{ -public: - explicit mvMenuBar(mvUUID uuid) : mvAppItem(uuid) { config.height = 21; } // TODO: fix - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_menubar(drawlist, *this); } -}; - -class mvViewportMenuBar : public mvAppItem -{ -public: - explicit mvViewportMenuBar(mvUUID uuid) : mvAppItem(uuid) - { - - // TODO use code below to set item height when font and scale systems are done - //float FontSize = ImGui::GetFontSize(); // = Base Font Size * Current Window Scale - //ImGuiStyle currentStyle = ImGui::GetStyle(); // = Padding for the Top and Bottom - //_height = int(currentStyle.FramePadding.y * 2 + FontSize); - config.height = 21; - } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_viewport_menubar(drawlist, *this); } -}; - -class mvStage : public mvAppItem -{ -public: - explicit mvStage(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} -}; - -class mvTemplateRegistry : public mvAppItem -{ -public: - explicit mvTemplateRegistry(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} -}; - -class mvClipper : public mvAppItem -{ -public: - explicit mvClipper(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_clipper(drawlist, *this); } - -}; diff --git a/src/mvCallbackRegistry.cpp b/src/mvCallbackRegistry.cpp deleted file mode 100644 index a32829d35..000000000 --- a/src/mvCallbackRegistry.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvCallbackRegistry.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" - -void mvRunTasks(bool early /* = false */) -{ - - auto& tasks = early? GContext->callbackRegistry->earlyTasks : GContext->callbackRegistry->tasks; - while (!tasks.empty()) - { - mvFunctionWrapper t; - tasks.wait_and_pop(t); - t(); - } -} - -void mvFrameCallback(i32 frame) -{ - auto callbackRegistry = GContext->callbackRegistry; // for brevity - - if (frame > callbackRegistry->highestFrame) - return; - - if (callbackRegistry->frameCallbacks.count(frame) == 0) - return; - - // We have to use `std::unordered_map::at()` instead of indexing it with `[]`: - // `mvPyObject` has no default constructor, whereas `operator[]` can insert - // a new value into the map and therefore requires a default constructor. - - auto callback = std::make_shared(std::move(callbackRegistry->frameCallbacks.at(frame))); - auto user_data = std::make_shared(std::move(callbackRegistry->frameCallbacksUserData.at(frame))); - - // Since mvPyObject objects remaining in the maps are now "empty", it's safe to - // delete them right here even though we don't own the GIL. - callbackRegistry->frameCallbacks.erase(frame); - callbackRegistry->frameCallbacksUserData.erase(frame); - - mvAddOwnerlessCallback(callback, user_data, (mvUUID)frame, "", []() -> PyObject* { return nullptr; }); -} - -bool mvRunCallbacks() -{ - GContext->callbackRegistry->running = true; - - mvGlobalIntepreterLock gil; - - while (GContext->callbackRegistry->running) - { - mvFunctionWrapper t2; - Py_BEGIN_ALLOW_THREADS; - GContext->callbackRegistry->calls.wait_and_pop(t2); - Py_END_ALLOW_THREADS; - t2(); - GContext->callbackRegistry->callCount--; - } - - return true; -} - -void mvAddCallback(const std::weak_ptr& owner, - PyObject* callback, - const std::shared_ptr& user_data, - mvUUID sender, - const std::string& alias) -{ - mvAddCallback(owner, callback, user_data, sender, alias, []() -> PyObject* { return nullptr; }); -} - -void mvAddOwnerlessCallback(const std::shared_ptr& callback, - const std::shared_ptr& user_data, - mvUUID sender, - const std::string& alias) -{ - mvAddOwnerlessCallback(callback, user_data, sender, alias, []() -> PyObject* { return nullptr; }); -} - -void mvRunOwnedCallback(const std::weak_ptr& owner, PyObject* callback, PyObject* user_data, mvUUID sender /* = 0 */, const std::string& sender_alias /* = "" */, PyObject* app_data /* = nullptr */) -{ - auto liveOwner = owner.lock(); - if (liveOwner) - { - // Make our own callback ref - mvPyObject ownCallback(callback, true); - { - // We need to lock the mutex while releasing the `owner` pointer. When `liveOwner` - // goes out of scope, the mvAppItem that it holds might get deleted, thus - // invalidating all mvAppItem* pointers that we might be holding in various DPG functions - // e.g. in another thread. By locking the mutex and explicitly resetting - // `liveOwner`, we guarantee that destruction of mvAppItem only occurs with - // the mutex locked, and thus cannot happen in the middle of an API function - // that also locks the mutex. - mvPySafeLockGuard lk(GContext->mutex); - liveOwner.reset(); - } - mvRunCallback(ownCallback, user_data, sender, sender_alias, app_data); - } -} - -void mvRunCallback(PyObject* callback, PyObject* user_data, mvUUID sender, const std::string& sender_alias, PyObject* app_data) -{ - - if (callback == nullptr) - return; - - if (!PyCallable_Check(callback)) - { - mvThrowPythonError(mvErrorCode::mvNone, "Callable not callable."); - PyErr_Print(); - return; - } - - //PyErr_Clear(); - if (PyErr_Occurred()) - PyErr_Print(); - - PyObject* fc = PyObject_GetAttrString(callback, "__code__"); - if (fc) { - PyObject* ac = PyObject_GetAttrString(fc, "co_argcount"); - if (ac) { - i32 count = PyLong_AsLong(ac); - - if (PyMethod_Check(callback)) - count--; - - mvPyObject pArgs(count > 0 ? PyTuple_New(count) : nullptr); - - if (count > 0) - { - PyTuple_SetItem(pArgs, 0, ToPyUUID(sender, sender_alias)); - - if (count > 1) - { - if (app_data == nullptr) - app_data = Py_None; - // Need an owned ref here: PyTuple_SetItem takes ownership; - // this also handles Py_None correctly (need to incref it). - Py_INCREF(app_data); - PyTuple_SetItem(pArgs, 1, app_data); - - if (count > 2) - { - if (user_data == nullptr) - user_data = Py_None; - // Need an owned ref here: PyTuple_SetItem takes ownership; - // this also handles Py_None correctly (need to incref it). - Py_INCREF(user_data); - PyTuple_SetItem(pArgs, 2, user_data); - - // If the callback takes more parms, just pass None in there - for (int i = 3; i < count; i++) - PyTuple_SetItem(pArgs, i, GetPyNone()); - } - } - } - - // perform the actual call - mvPyObject result(PyObject_CallObject(callback, pArgs)); - - // check if call succeeded - if (!result.isOk()) - PyErr_Print(); - - Py_DECREF(ac); - } - Py_DECREF(fc); - } - -} diff --git a/src/mvCallbackRegistry.h b/src/mvCallbackRegistry.h deleted file mode 100644 index 323d11fe0..000000000 --- a/src/mvCallbackRegistry.h +++ /dev/null @@ -1,353 +0,0 @@ -#pragma once - -#include -#include -#include -#include "mvContext.h" - -//----------------------------------------------------------------------------- -// mvFunctionWrapper -//----------------------------------------------------------------------------- - -class mvFunctionWrapper -{ - struct impl_base { - virtual void call() = 0; - virtual ~impl_base() = default; - }; - - template - struct impl_type : impl_base - { - F f; - explicit impl_type(F&& f) : f(std::move(f)) {} - void call() override { f(); } - }; - -public: - - mvFunctionWrapper() = default; - - template - mvFunctionWrapper(F&& f) : m_impl(new impl_type(std::move(f))) {} - - mvFunctionWrapper(mvFunctionWrapper&& other) noexcept - : m_impl(std::move(other.m_impl)) - { - - } - - mvFunctionWrapper& operator=(mvFunctionWrapper&& other) - { - m_impl = std::move(other.m_impl); - return *this; - } - - // delete copy constructor and assignment operator - mvFunctionWrapper(const mvFunctionWrapper&) = delete; - mvFunctionWrapper(mvFunctionWrapper&) = delete; - mvFunctionWrapper& operator=(const mvFunctionWrapper&) = delete; - - void operator()() - { - m_impl->call(); - } - -private: - - std::unique_ptr m_impl; - -}; - -//----------------------------------------------------------------------------- -// mvQueue -//----------------------------------------------------------------------------- -template -class mvQueue -{ - -public: - - struct node - { - std::shared_ptr data; - std::unique_ptr next; - }; - -public: - - mvQueue() : m_head(new node), m_tail(m_head.get()) {} - - // copy assignment and constructor deleted - mvQueue(const mvQueue& other) = delete; - mvQueue& operator=(const mvQueue& other) = delete; - - std::shared_ptr wait_and_pop() - { - std::unique_ptr const old_head = wait_pop_head(); - return old_head->data; - } - - std::shared_ptr try_pop() - { - std::unique_ptr const old_head = try_pop_head(); - return old_head ? old_head->data : std::shared_ptr(); - } - - void wait_and_pop(T& value) - { - std::unique_ptr const old_head = wait_pop_head(value); - } - - bool try_pop(T& value) - { - std::unique_ptr const old_head = try_pop_head(value); - if (old_head) - return true; - return false; - } - - void push(T value) - { - std::shared_ptr new_data = std::make_shared(std::move(value)); - auto p = std::make_unique(); - - // scoped in order to unlock tail mutex before notifying other threads - { - std::lock_guard tail_lock(m_tail_mutex); - m_tail->data = std::move(new_data); - node* const new_tail = p.get(); - m_tail->next = std::move(p); - m_tail = new_tail; - } - - m_data_cond.notify_one(); - } - - bool empty() - { - std::lock_guard head_lock(m_head_mutex); - return (m_head.get() == get_tail()); - } - -private: - - node* get_tail() - { - std::lock_guard tail_lock(m_tail_mutex); - return m_tail; - } - - std::unique_ptr pop_head() - { - std::unique_ptr old_head = std::move(m_head); - m_head = std::move(old_head->next); - return old_head; - } - - std::unique_ptr try_pop_head() - { - std::lock_guard head_lock(m_head_mutex); - if (m_head.get() == get_tail()) - return std::unique_ptr(); - return pop_head(); - } - - std::unique_ptr try_pop_head(T& value) - { - std::lock_guard head_lock(m_head_mutex); - if (m_head.get() == get_tail()) - return std::unique_ptr(); - - value = std::move(*m_head->data); - return pop_head(); - } - - std::unique_ptr wait_pop_head() - { - std::unique_lock head_lock(wait_for_data()); - return pop_head(); - } - - std::unique_ptr wait_pop_head(T& value) - { - std::unique_lock head_lock(wait_for_data()); - value = std::move(*m_head->data); - return pop_head(); - } - - std::unique_lock wait_for_data() - { - std::unique_lock head_lock(m_head_mutex); - m_data_cond.wait(head_lock, [&] {return m_head.get() != get_tail(); }); - return head_lock; - } - -private: - - std::mutex m_head_mutex; - std::mutex m_tail_mutex; - std::unique_ptr m_head; - node* m_tail; - std::condition_variable m_data_cond; - -}; - -struct mvCallbackJob -{ - std::weak_ptr owner; - // Only valid if `owner` is alive; one must lock() the owner before accessing - // the callback. - PyObject* callback = nullptr; - std::shared_ptr user_data; - mvUUID sender = 0; - std::string alias; - std::function app_data_func; - // Either `callback` (and `owner`) or `ownerless_callback` must be set, - // but not both - otherwise one of them will be ignored. - std::shared_ptr ownerless_callback = nullptr; -}; - -struct mvCallbackRegistry -{ - // TODO: ideally, it should be configurable (e.g. via configure_app) - const i32 maxNumberOfCalls = 500; - - std::vector jobs; - mvQueue tasks; - // These are like `tasks` but they run very early at the start of the frame, - // whereas `tasks` can be run mid-frame either before or after Render(). - mvQueue earlyTasks; - mvQueue calls; - std::atomic running = false; - std::atomic callCount = 0; - - // callbacks - std::shared_ptr resizeCallback = std::make_shared(nullptr); - std::shared_ptr resizeCallbackUserData = std::make_shared(nullptr); - std::shared_ptr onCloseCallback = std::make_shared(nullptr); - std::shared_ptr onCloseCallbackUserData = std::make_shared(nullptr); - - i32 highestFrame = 0; - std::unordered_map frameCallbacks; - std::unordered_map frameCallbacksUserData; -}; - -void mvFrameCallback(i32 frame); -// Runs either `tasks` or `earlyTasks` from mvCallbackRegistry, depending on the `early` flag. -void mvRunTasks(bool early = false); -// All PyObject references here are borrowed references - caller must release them after this call -void mvRunCallback(PyObject* callback, PyObject* user_data, mvUUID sender = 0, const std::string& sender_alias = "", PyObject* app_data = nullptr); -// This version checks if owner is still alive (by obtaining shared_ptr), and if it is, -// INCREFs the callback and releases the owner. The owner is released under mvContext::mutex. -// All PyObject references except `callback` are borrowed references - the caller must release -// them after this call. -void mvRunOwnedCallback(const std::weak_ptr& owner, PyObject* callback, PyObject* user_data, mvUUID sender = 0, const std::string& sender_alias = "", PyObject* app_data = nullptr); - -// Note: We pass the `callback` and its `user_data` as two separate arguments (rather -// than a single object) because, even though they only make sense together, `mvAppItem` may -// combine the same `user_data` with different callbacks. We don't want to spread `user_data` -// instances all across `mvAppItem`. -// The `callback` must be valid all the time while `owner` is alive. This works for -// the fields of `owner`; if `callback` is not a field of `owner`, the caller must make -// sure that `callback`'s lifetime is at least as long as `owner`'s. -// When the callback is about to be executed on the handlers thread, the callback queue -// acquires a shared_ptr to `owner` and holds it while the callback is being executed. -// If the `owner` is already lost by the moment the callback is fetched from the -// queue, the callback will be silently ignored. This effectively cleans the queue -// from irrelevant callbacks - lingering there after `mvAppItem` deletion and such. -template -void mvAddCallback(const std::weak_ptr& owner, - PyObject* callback, - const std::shared_ptr& user_data, - mvUUID sender, - const std::string& alias, - AppDataFunc&& app_data_func) -{ - if (GContext->IO.manualCallbacks) - { - GContext->callbackRegistry->jobs.push_back({owner, callback, user_data, sender, alias, std::forward(app_data_func)}); - return; - } - mvSubmitCallback([=, app_data_func = std::forward(app_data_func)] () { - mvRunOwnedCallback(owner, callback, *user_data, sender, alias, mvPyObject(app_data_func())); - }); -} - -// This overload exists purely to provide default argument values - we can't do this -// directly on the template version above because the compiler won't be able to deduce -// `app_data_func` type if `app_data_func` is omitted (that is, we can't really use -// the default on `app_data_func`). -void mvAddCallback(const std::weak_ptr& owner, - PyObject* callback, - const std::shared_ptr& user_data, - mvUUID sender = 0, - const std::string& alias = ""); - -template -void mvAddOwnerlessCallback(const std::shared_ptr& callback, - const std::shared_ptr& user_data, - mvUUID sender, - const std::string& alias, - AppDataFunc&& app_data_func) -{ - if (GContext->IO.manualCallbacks) - { - GContext->callbackRegistry->jobs.push_back({{}, nullptr, user_data, sender, alias, std::forward(app_data_func), callback}); - return; - } - mvSubmitCallback([=, app_data_func = std::forward(app_data_func)]() { - mvRunCallback(*callback, *user_data, sender, alias, mvPyObject(app_data_func())); - }); -} - -// This overload exists purely to provide default argument values - we can't do this -// directly on the template version above because the compiler won't be able to deduce -// `app_data_func` type if `app_data_func` is omitted (that is, we can't really use -// the default on `app_data_func`). -void mvAddOwnerlessCallback(const std::shared_ptr& callback, - const std::shared_ptr& user_data, - mvUUID sender = 0, - const std::string& alias = ""); - -bool mvRunCallbacks(); - -template -std::future::type> mvSubmitTask(F f, bool runEarlyInFrame = false) -{ - - typedef typename std::invoke_result::type result_type; - std::packaged_task task(std::move(f)); - std::future res(task.get_future()); - - if (GContext->running) - { - auto& tasks = runEarlyInFrame? GContext->callbackRegistry->earlyTasks : GContext->callbackRegistry->tasks; - tasks.push(std::move(task)); - } - else - task(); - - return res; -} - -template -std::future::type> mvSubmitCallback(F f, bool ignore_limit = false) -{ - - if (GContext->callbackRegistry->callCount > GContext->callbackRegistry->maxNumberOfCalls && !ignore_limit) - { - assert(false); - return {}; - } - - GContext->callbackRegistry->callCount++; - - typedef typename std::invoke_result::type result_type; - std::packaged_task task(std::move(f)); - std::future res(task.get_future()); - - GContext->callbackRegistry->calls.push(std::move(task)); - - return res; -} \ No newline at end of file diff --git a/src/mvColors.cpp b/src/mvColors.cpp deleted file mode 100644 index 9d94777f8..000000000 --- a/src/mvColors.cpp +++ /dev/null @@ -1,1278 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvColors.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvContainers.h" -#include "mvItemHandlers.h" - -#include - -void -DearPyGui::draw_color_button(ImDrawList* drawlist, mvAppItem& item, mvColorButtonConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - ImVec4 col = { (*config.value)[0], (*config.value)[1], (*config.value)[2], (*config.value)[3] }; - - if (ImGui::ColorButton(item.info.internalLabel.c_str(), col, config.flags, ImVec2((float)item.config.width, (float)item.config.height))) - { - item.submitCallback(); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_edit(ImDrawList* drawlist, mvAppItem& item, mvColorEditConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 4, config.disabled_value); - - if (ImGui::ColorEdit4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.flags)) - { - mvColor color = mvColor((*config.value)[0], (*config.value)[1], (*config.value)[2], (*config.value)[3]); - item.submitCallback(color); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_map(ImDrawList* drawlist, mvAppItem& item, mvColorMapConfig& config) -{ - ScopedID id(item.uuid); - - ImPlot::ColormapButton(item.info.internalLabel.c_str(), ImVec2(-1.0f, 0.0f), config.colorMap); -} - -void -DearPyGui::draw_color_map_button(ImDrawList* drawlist, mvAppItem& item, mvColorMapButtonConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - if (ImPlot::ColormapButton(item.info.internalLabel.c_str(), ImVec2((float)item.config.width, (float)item.config.height), config.colorMap)) - { - item.submitCallback(); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_map_scale(ImDrawList* drawlist, mvAppItem& item, mvColorMapScaleConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - ImPlot::ColormapScale(item.info.internalLabel.c_str(), config.scale_min, config.scale_max, ImVec2((float)item.config.width, (float)item.config.height), config.format.c_str(), config.flags, config.colorMap); - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_picker(ImDrawList* drawlist, mvAppItem& item, mvColorPickerConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (!item.config.enabled) std::copy(config.value->data(), config.value->data() + 4, config.disabled_value); - - if (ImGui::ColorPicker4(item.info.internalLabel.c_str(), item.config.enabled ? config.value->data() : &config.disabled_value[0], config.flags)) - { - mvColor color = mvColor((*config.value)[0], (*config.value)[1], (*config.value)[2], (*config.value)[3]); - item.submitCallback(color); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_map_slider(ImDrawList* drawlist, mvAppItem& item, mvColorMapSliderConfig& config) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - if (ImPlot::ColormapSlider(item.info.internalLabel.c_str(), config.value.get(), &config.color, "", config.colorMap)) - { - item.submitCallback(*config.value); - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(item.state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_color_map_registry(ImDrawList* drawlist, mvAppItem& item) -{ - - if (!item.config.show) - return; - - ImGui::PushID(&item); - - ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_FirstUseEver); - if (ImGui::Begin(item.info.internalLabel.c_str(), &item.config.show)) - { - ImGui::Text("Builtin:"); - for (int i = 0; i < 16; i++) - ImPlot::ColormapButton(ImPlot::GetColormapName(i), ImVec2(-1.0f, 0.0f), i); - - ImGui::Text("User:"); - - for (auto& item : item.childslots[1]) - item->draw(drawlist, 0.0f, 0.0f); - - } - - ImGui::End(); - - ImGui::PopID(); -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvColorButtonConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvColorButton)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - mvColor color; - switch (i) - { - case 0: - color = ToColor(item); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); - break; - - default: - break; - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvColorEditConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvColorEdit)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - mvColor color; - switch (i) - { - case 0: - color = ToColor(item); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); - break; - - default: - break; - } - } -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvColorPickerConfig& outConfig) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvColorPicker)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* item = PyTuple_GetItem(inDict, i); - mvColor color; - switch (i) - { - case 0: - color = ToColor(item); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); - break; - - default: - break; - } - } - -} - -void -DearPyGui::set_positional_configuration(PyObject* inDict, mvColorMapConfig& outConfig, mvAppItem& item) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(mvAppItemType::mvColorMap)], inDict)) - return; - - for (int i = 0; i < PyTuple_Size(inDict); i++) - { - PyObject* arg = PyTuple_GetItem(inDict, i); - std::vector> rawColors; - switch (i) - { - case 0: - rawColors = ToVectVectInt(arg); - for (const auto& color : rawColors) - { - - std::vector c; - - for (int j = 0; j < color.size(); j++) - c.push_back((float)color[j] / 255.0f); - - while (c.size() < 4) - c.push_back(1.0f); - - outConfig.colors.push_back(ImVec4(c[0], c[1], c[2], c[3])); - - } - break; - case 1: - outConfig.qualitative = ToBool(arg); - break; - default: - break; - } - } - outConfig.colorMap = ImPlot::AddColormap(item.info.internalLabel.c_str(), outConfig.colors.data(), (int)outConfig.colors.size(), outConfig.qualitative); -} - -PyObject* -DearPyGui::set_data_source(mvColorButtonConfig& outConfig) -{ - // nasty hack - int r = (int)(outConfig.value->data()[0] * 255.0f * 255.0f); - int g = (int)(outConfig.value->data()[1] * 255.0f * 255.0f); - int b = (int)(outConfig.value->data()[2] * 255.0f * 255.0f); - int a = (int)(outConfig.value->data()[3] * 255.0f * 255.0f); - - auto color = mvColor(r, g, b, a); - return ToPyColor(color); -} - -PyObject* -DearPyGui::set_data_source(mvColorEditConfig& outConfig) -{ - // nasty hack - int r = (int)(outConfig.value->data()[0] * 255.0f * 255.0f); - int g = (int)(outConfig.value->data()[1] * 255.0f * 255.0f); - int b = (int)(outConfig.value->data()[2] * 255.0f * 255.0f); - int a = (int)(outConfig.value->data()[3] * 255.0f * 255.0f); - - auto color = mvColor(r, g, b, a); - return ToPyColor(color); -} - -PyObject* -DearPyGui::set_data_source(mvColorPickerConfig& outConfig) -{ - // nasty hack - int r = (int)(outConfig.value->data()[0] * 255.0f * 255.0f); - int g = (int)(outConfig.value->data()[1] * 255.0f * 255.0f); - int b = (int)(outConfig.value->data()[2] * 255.0f * 255.0f); - int a = (int)(outConfig.value->data()[3] * 255.0f * 255.0f); - - auto color = mvColor(r, g, b, a); - return ToPyColor(color); -} - -PyObject* -DearPyGui::set_data_source(mvColorMapSliderConfig& outConfig) -{ - return ToPyFloat(*outConfig.value); -} - -void -DearPyGui::set_py_value(PyObject* inDict, mvColorButtonConfig& outConfig) -{ - mvColor color = ToColor(inDict); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); -} - -void -DearPyGui::set_py_value(PyObject* inDict, mvColorMapSliderConfig& outConfig) -{ - *outConfig.value = ToFloat(inDict); -} - -void -DearPyGui::set_py_value(PyObject* inDict, mvColorEditConfig& outConfig) -{ - mvColor color = ToColor(inDict); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); -} - -void -DearPyGui::set_py_value(PyObject* inDict, mvColorPickerConfig& outConfig) -{ - mvColor color = ToColor(inDict); - std::array temp_array; - temp_array[0] = color.r; - temp_array[1] = color.g; - temp_array[2] = color.b; - temp_array[3] = color.a; - if (outConfig.value) - *outConfig.value = temp_array; - else - outConfig.value = std::make_shared>(temp_array); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvColorButtonConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvColorEditConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvColorPickerConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast>*>(srcItem->getValue()); - -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvColorMapSliderConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); - -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvColorButtonConfig& outConfig) -{ - if (inDict == nullptr) - return; - - - // helpers for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, outConfig.flags); - flagop("no_border", ImGuiColorEditFlags_NoBorder, outConfig.flags); - flagop("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, outConfig.flags); - flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, outConfig.flags); - - if (PyObject* item = PyDict_GetItemString(inDict, "alpha_preview")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~(ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - outConfig.flags |= mode; - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvColorEditConfig& outConfig) -{ - if (inDict == nullptr) - return; - - // helpers for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, outConfig.flags); - flagop("no_picker", ImGuiColorEditFlags_NoPicker, outConfig.flags); - flagop("no_options", ImGuiColorEditFlags_NoOptions, outConfig.flags); - flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, outConfig.flags); - flagop("no_inputs", ImGuiColorEditFlags_NoInputs, outConfig.flags); - flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, outConfig.flags); - flagop("no_label", ImGuiColorEditFlags_NoLabel, outConfig.flags); - flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, outConfig.flags); - flagop("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, outConfig.flags); - flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, outConfig.flags); - - if (PyObject* item = PyDict_GetItemString(inDict, "alpha_preview")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~(ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - outConfig.flags |= mode; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "display_mode")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_DisplayRGB; - outConfig.flags &= ~ImGuiColorEditFlags_DisplayHSV; - outConfig.flags &= ~ImGuiColorEditFlags_DisplayHex; - - switch (mode) - { - case ImGuiColorEditFlags_DisplayHex: - outConfig.flags |= ImGuiColorEditFlags_DisplayHex; - break; - case ImGuiColorEditFlags_DisplayHSV: - outConfig.flags |= ImGuiColorEditFlags_DisplayHSV; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_DisplayRGB; - break; - } - } - - if (PyObject* item = PyDict_GetItemString(inDict, "display_type")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_Uint8; - outConfig.flags &= ~ImGuiColorEditFlags_Float; - - switch (mode) - { - case ImGuiColorEditFlags_Float: - outConfig.flags |= ImGuiColorEditFlags_Float; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_Uint8; - break; - } - } - - if (PyObject* item = PyDict_GetItemString(inDict, "input_mode")) - { - long mode = (long)ToUUID(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_InputRGB; - outConfig.flags &= ~ImGuiColorEditFlags_InputHSV; - - switch (mode) - { - case ImGuiColorEditFlags_InputHSV: - outConfig.flags |= ImGuiColorEditFlags_InputHSV; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_InputRGB; - break; - } - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvColorPickerConfig& outConfig) -{ - if (inDict == nullptr) - return; - - // helpers for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - - flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, outConfig.flags); - flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, outConfig.flags); - flagop("no_inputs", ImGuiColorEditFlags_NoInputs, outConfig.flags); - flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, outConfig.flags); - flagop("no_label", ImGuiColorEditFlags_NoLabel, outConfig.flags); - flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, outConfig.flags); - flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, outConfig.flags); - flagop("display_rgb", ImGuiColorEditFlags_DisplayRGB, outConfig.flags); - flagop("display_hsv", ImGuiColorEditFlags_DisplayHSV, outConfig.flags); - flagop("display_hex", ImGuiColorEditFlags_DisplayHex, outConfig.flags); - - if (PyObject* item = PyDict_GetItemString(inDict, "picker_mode")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_PickerHueBar; - outConfig.flags &= ~ImGuiColorEditFlags_PickerHueWheel; - - switch (mode) - { - case ImGuiColorEditFlags_PickerHueWheel: - outConfig.flags |= ImGuiColorEditFlags_PickerHueWheel; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_PickerHueBar; - break; - } - } - - if (PyObject* item = PyDict_GetItemString(inDict, "alpha_preview")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~(ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - outConfig.flags |= mode; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "display_type")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_Uint8; - outConfig.flags &= ~ImGuiColorEditFlags_Float; - - switch (mode) - { - case ImGuiColorEditFlags_Float: - outConfig.flags |= ImGuiColorEditFlags_Float; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_Uint8; - break; - } - } - - if (PyObject* item = PyDict_GetItemString(inDict, "input_mode")) - { - long mode = ToLong(item); - - // reset target flags - outConfig.flags &= ~ImGuiColorEditFlags_InputRGB; - outConfig.flags &= ~ImGuiColorEditFlags_InputHSV; - - switch (mode) - { - case ImGuiColorEditFlags_InputHSV: - outConfig.flags |= ImGuiColorEditFlags_InputHSV; - break; - default: - outConfig.flags |= ImGuiColorEditFlags_InputRGB; - break; - } - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvColorMapScaleConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "min_scale")) outConfig.scale_min = (double)ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "max_scale")) outConfig.scale_max = (double)ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "format")) outConfig.format = ToString(item); - if (PyObject* item = PyDict_GetItemString(inDict, "colormap")) - { - outConfig.colorMap = (ImPlotColormap)GetIDFromPyObject(item); - if (outConfig.colorMap > 10) - { - auto asource = GetItem(*GContext->itemRegistry, outConfig.colorMap); - if (asource == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_colormap", - "Source Item not found: " + std::to_string(outConfig.colorMap), nullptr); - outConfig.colorMap = 0; - } - - else if (asource->type == mvAppItemType::mvColorMap) - { - mvColorMap* colormap = static_cast(asource); - outConfig.colorMap = colormap->configData.colorMap; - } - } - } - - // helpers for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - - flagop("reverse_dir", ImPlotColormapScaleFlags_Invert, outConfig.flags); - flagop("mirror", ImPlotColormapScaleFlags_Opposite, outConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvColorButtonConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, inConfig.flags); - checkbitset("no_border", ImGuiColorEditFlags_NoBorder, inConfig.flags); - checkbitset("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, inConfig.flags); - checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, inConfig.flags); - - // alpha_preview - auto alphaMode = inConfig.flags & (ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - PyDict_SetItemString(outDict, "alpha_preview", mvPyObject(ToPyLong(alphaMode))); -} - -void -DearPyGui::fill_configuration_dict(const mvColorEditConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, inConfig.flags); - checkbitset("no_picker", ImGuiColorEditFlags_NoPicker, inConfig.flags); - checkbitset("no_options", ImGuiColorEditFlags_NoOptions, inConfig.flags); - checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, inConfig.flags); - checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, inConfig.flags); - checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, inConfig.flags); - checkbitset("no_label", ImGuiColorEditFlags_NoLabel, inConfig.flags); - checkbitset("no_drag_drop", ImGuiColorEditFlags_NoDragDrop, inConfig.flags); - checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, inConfig.flags); - - // input_mode - if (inConfig.flags & ImGuiColorEditFlags_InputRGB) - PyDict_SetItemString(outDict, "input_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_InputRGB))); - else if (inConfig.flags & ImGuiColorEditFlags_InputHSV) - PyDict_SetItemString(outDict, "input_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_InputHSV))); - - // alpha_preview - auto alphaMode = inConfig.flags & (ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - PyDict_SetItemString(outDict, "alpha_preview", mvPyObject(ToPyLong(alphaMode))); - - // display_mode - if (inConfig.flags & ImGuiColorEditFlags_DisplayHSV) - PyDict_SetItemString(outDict, "display_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_DisplayHSV))); - else if (inConfig.flags & ImGuiColorEditFlags_DisplayHex) - PyDict_SetItemString(outDict, "display_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_DisplayHex))); - else - PyDict_SetItemString(outDict, "display_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_DisplayRGB))); - - // display_type - if (inConfig.flags & ImGuiColorEditFlags_Uint8) - PyDict_SetItemString(outDict, "display_type", mvPyObject(ToPyLong(ImGuiColorEditFlags_Uint8))); - else if (inConfig.flags & ImGuiColorEditFlags_Float) - PyDict_SetItemString(outDict, "display_type", mvPyObject(ToPyLong(ImGuiColorEditFlags_Float))); - -} - -void -DearPyGui::fill_configuration_dict(const mvColorPickerConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, inConfig.flags); - checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, inConfig.flags); - checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, inConfig.flags); - checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, inConfig.flags); - checkbitset("no_label", ImGuiColorEditFlags_NoLabel, inConfig.flags); - checkbitset("no_side_preview", ImGuiColorEditFlags_NoSidePreview, inConfig.flags); - checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, inConfig.flags); - checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, inConfig.flags); - checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, inConfig.flags); - checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, inConfig.flags); - - // input_mode - if (inConfig.flags & ImGuiColorEditFlags_InputRGB) - PyDict_SetItemString(outDict, "input_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_InputRGB))); - else if (inConfig.flags & ImGuiColorEditFlags_InputHSV) - PyDict_SetItemString(outDict, "input_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_InputHSV))); - - // alpha_preview - auto alphaMode = inConfig.flags & (ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaPreviewHalf); - PyDict_SetItemString(outDict, "alpha_preview", mvPyObject(ToPyLong(alphaMode))); - - // display_type - if (inConfig.flags & ImGuiColorEditFlags_Uint8) - PyDict_SetItemString(outDict, "display_type", mvPyObject(ToPyLong(ImGuiColorEditFlags_Uint8))); - else if (inConfig.flags & ImGuiColorEditFlags_Float) - PyDict_SetItemString(outDict, "display_type", mvPyObject(ToPyLong(ImGuiColorEditFlags_Float))); - - // picker_mode - if (inConfig.flags & ImGuiColorEditFlags_PickerHueWheel) - PyDict_SetItemString(outDict, "picker_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_PickerHueWheel))); - else if (inConfig.flags & ImGuiColorEditFlags_PickerHueBar) - PyDict_SetItemString(outDict, "picker_mode", mvPyObject(ToPyLong(ImGuiColorEditFlags_PickerHueBar))); -} - -void -DearPyGui::fill_configuration_dict(const mvColorMapScaleConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "min_scale", mvPyObject(ToPyFloat((float)inConfig.scale_min))); - PyDict_SetItemString(outDict, "max_scale", mvPyObject(ToPyFloat((float)inConfig.scale_max))); - PyDict_SetItemString(outDict, "format", mvPyObject(ToPyString(inConfig.format))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("reverse_dir", ImPlotColormapScaleFlags_Invert, inConfig.flags); - checkbitset("mirror", ImPlotColormapScaleFlags_Opposite, inConfig.flags); -} \ No newline at end of file diff --git a/src/mvColors.h b/src/mvColors.h deleted file mode 100644 index 3208c07fe..000000000 --- a/src/mvColors.h +++ /dev/null @@ -1,215 +0,0 @@ -#pragma once - -#include -#include "mvItemRegistry.h" - -struct mvColorButtonConfig; -struct mvColorEditConfig; -struct mvColorPickerConfig; -struct mvColorMapConfig; -struct mvColorMapButtonConfig; -struct mvColorMapScaleConfig; -struct mvColorMapSliderConfig; - -namespace DearPyGui -{ - // draw commands - void draw_color_button(ImDrawList* drawlist, mvAppItem& item, mvColorButtonConfig& config); - void draw_color_edit(ImDrawList* drawlist, mvAppItem& item, mvColorEditConfig& config); - void draw_color_picker(ImDrawList* drawlist, mvAppItem& item, mvColorPickerConfig& config); - void draw_color_map(ImDrawList* drawlist, mvAppItem& item, mvColorMapConfig& config); - void draw_color_map_button(ImDrawList* drawlist, mvAppItem& item, mvColorMapButtonConfig& config); - void draw_color_map_scale(ImDrawList* drawlist, mvAppItem& item, mvColorMapScaleConfig& config); - void draw_color_map_slider(ImDrawList* drawlist, mvAppItem& item, mvColorMapSliderConfig& config); - void draw_color_map_registry(ImDrawList* drawlist, mvAppItem& item); - - // positional args TODO: combine with above - void set_positional_configuration(PyObject* inDict, mvColorButtonConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvColorEditConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvColorPickerConfig& outConfig); - void set_positional_configuration(PyObject* inDict, mvColorMapConfig& outConfig, mvAppItem& item); - - // specific part of `configure_item(...)` - void set_configuration(PyObject* inDict, mvColorButtonConfig& outConfig); - void set_configuration(PyObject* inDict, mvColorEditConfig& outConfig); - void set_configuration(PyObject* inDict, mvColorPickerConfig& outConfig); - void set_configuration(PyObject* inDict, mvColorMapScaleConfig& outConfig); - - // specific part of `get_item_configuration(...)` - void fill_configuration_dict(const mvColorButtonConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvColorEditConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvColorPickerConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvColorMapScaleConfig& inConfig, PyObject* outDict); - - // data source handling - void set_data_source(mvAppItem& item, mvUUID dataSource, mvColorButtonConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvColorEditConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvColorPickerConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvColorMapSliderConfig& outConfig); - - // get python value - PyObject* set_data_source(mvColorButtonConfig& outConfig); - PyObject* set_data_source(mvColorEditConfig& outConfig); - PyObject* set_data_source(mvColorPickerConfig& outConfig); - PyObject* set_data_source(mvColorMapSliderConfig& outConfig); - - // set python value - void set_py_value(PyObject* inDict, mvColorButtonConfig& outConfig); - void set_py_value(PyObject* inDict, mvColorEditConfig& outConfig); - void set_py_value(PyObject* inDict, mvColorPickerConfig& outConfig); - void set_py_value(PyObject* inDict, mvColorMapSliderConfig& outConfig); -} - -struct mvColorButtonConfig -{ - - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 1.0f}); - float disabled_value[4]{}; - ImGuiColorEditFlags flags = ImGuiColorEditFlags_None; - bool no_border = false; - -}; - -struct mvColorEditConfig -{ - - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 1.0f}); - float disabled_value[4]{}; - ImGuiColorEditFlags flags = ImGuiColorEditFlags_DefaultOptions_; - bool no_picker = false; - bool no_options = false; - bool no_inputs = false; - bool no_label = false; - bool alpha_bar = false; - -}; - -struct mvColorPickerConfig -{ - std::shared_ptr> value = std::make_shared>(std::array{0.0f, 0.0f, 0.0f, 1.0f}); - float disabled_value[4]{}; - ImGuiColorEditFlags flags = ImGuiColorEditFlags_DefaultOptions_; - bool no_inputs = false; - bool no_label = false; - bool no_side_preview = false; - bool alpha_bar = false; -}; - -struct mvColorMapConfig -{ - ImPlotColormap colorMap = -1; - bool qualitative = true; - std::vector colors; -}; - -struct mvColorMapButtonConfig -{ - ImPlotColormap colorMap = 0; -}; - -struct mvColorMapScaleConfig -{ - double scale_min = 0; - double scale_max = 0; - ImPlotColormap colorMap = 0; - std::string format = "%g"; - ImPlotColormapScaleFlags flags = ImPlotColormapScaleFlags_None; -}; - -struct mvColorMapSliderConfig -{ - std::shared_ptr value = std::make_shared(0.0f); - ImVec4 color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - ImPlotColormap colorMap = 0; -}; - -class mvColorButton : public mvAppItem -{ -public: - mvColorButtonConfig configData{}; - explicit mvColorButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_button(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject * dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject * dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject * dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return DearPyGui::set_data_source(configData); } - void setPyValue(PyObject* value) override { return DearPyGui::set_py_value(value, configData); } -}; - -class mvColorEdit : public mvAppItem -{ -public: - mvColorEditConfig configData{}; - explicit mvColorEdit(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_edit(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return DearPyGui::set_data_source(configData); } - void setPyValue(PyObject* value) override { return DearPyGui::set_py_value(value, configData); } -}; - -class mvColorPicker : public mvAppItem -{ -public: - mvColorPickerConfig configData{}; - explicit mvColorPicker(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_picker(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return DearPyGui::set_data_source(configData); } - void setPyValue(PyObject* value) override { return DearPyGui::set_py_value(value, configData); } -}; - -class mvColorMap : public mvAppItem -{ -public: - mvColorMapConfig configData{}; - explicit mvColorMap(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_map(drawlist, *this, configData); } - void handleSpecificPositionalArgs(PyObject* dict) override { DearPyGui::set_positional_configuration(dict, configData, *this); } -}; - -class mvColorMapButton : public mvAppItem -{ -public: - mvColorMapButtonConfig configData{}; - explicit mvColorMapButton(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_map_button(drawlist, *this, configData); } -}; - -class mvColorMapRegistry : public mvAppItem -{ -public: - explicit mvColorMapRegistry(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_map_registry(drawlist, *this); } -}; - -class mvColorMapScale : public mvAppItem -{ -public: - mvColorMapScaleConfig configData{}; - explicit mvColorMapScale(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_map_scale(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvColorMapSlider : public mvAppItem -{ -public: - mvColorMapSliderConfig configData{}; - explicit mvColorMapSlider(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_color_map_slider(drawlist, *this, configData); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, dataSource, configData); } - void* getValue() override { return &configData.value; } - PyObject* getPyValue() override { return DearPyGui::set_data_source(configData); } - void setPyValue(PyObject* value) override { return DearPyGui::set_py_value(value, configData); } -}; \ No newline at end of file diff --git a/src/mvContainers.cpp b/src/mvContainers.cpp deleted file mode 100644 index 1d4e45b2e..000000000 --- a/src/mvContainers.cpp +++ /dev/null @@ -1,1783 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvContainers.h" - -#include "mvViewport.h" -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvContainers.h" -#include "mvItemHandlers.h" -#include "mvTextureItems.h" - -#include -// For ImGuiWindow -#include - -//----------------------------------------------------------------------------- -// [SECTION] get_item_configuration(...) specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::fill_configuration_dict(const mvMenuConfig& inConfig, PyObject* outDict, mvAppItem& item) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "enabled", mvPyObject(ToPyBool(item.config.enabled))); -} - -void -DearPyGui::fill_configuration_dict(const mvTabConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "closable", mvPyObject(ToPyBool(inConfig.closable))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("no_tooltip", ImGuiTabItemFlags_NoTooltip, inConfig._flags); - checkbitset("unsaved_document", ImGuiTabItemFlags_UnsavedDocument, inConfig._flags); - checkbitset("no_close_with_middle_click", ImGuiTabItemFlags_NoCloseWithMiddleMouseButton, inConfig._flags); - checkbitset("no_reorder", ImGuiTabItemFlags_NoReorder, inConfig._flags); - - if (inConfig._flags & ImGuiTabItemFlags_Leading) - PyDict_SetItemString(outDict, "order_mode", mvPyObject(ToPyLong((long)TabOrdering::mvTabOrder_Leading))); - else if (inConfig._flags & ImGuiTabItemFlags_Trailing) - PyDict_SetItemString(outDict, "order_mode", mvPyObject(ToPyLong((long)TabOrdering::mvTabOrder_Trailing))); - else if (inConfig._flags & ImGuiTabBarFlags_Reorderable) - PyDict_SetItemString(outDict, "order_mode", mvPyObject(ToPyLong((long)TabOrdering::mvTabOrder_Reorderable))); - else - PyDict_SetItemString(outDict, "order_mode", mvPyObject(ToPyLong((long)TabOrdering::mvTabOrder_Fixed))); - -} - -void -DearPyGui::fill_configuration_dict(const mvChildWindowConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "autosize_x", mvPyObject(ToPyBool(inConfig.autosize_x))); - PyDict_SetItemString(outDict, "autosize_y", mvPyObject(ToPyBool(inConfig.autosize_y))); - - // helper for bit flipping - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - // window flags - checkbitset("no_scrollbar", ImGuiWindowFlags_NoScrollbar, inConfig.windowflags); - checkbitset("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, inConfig.windowflags); - checkbitset("menubar", ImGuiWindowFlags_MenuBar, inConfig.windowflags); - checkbitset("no_scroll_with_mouse", ImGuiWindowFlags_NoScrollWithMouse, inConfig.windowflags); - - // child flags - checkbitset("border", ImGuiChildFlags_Borders, inConfig.childFlags); - checkbitset("always_auto_resize", ImGuiChildFlags_AlwaysAutoResize, inConfig.childFlags); - checkbitset("always_use_window_padding", ImGuiChildFlags_AlwaysUseWindowPadding, inConfig.childFlags); - checkbitset("auto_resize_x", ImGuiChildFlags_AutoResizeX, inConfig.childFlags); - checkbitset("auto_resize_y", ImGuiChildFlags_AutoResizeY, inConfig.childFlags); - checkbitset("frame_style", ImGuiChildFlags_FrameStyle, inConfig.childFlags); - checkbitset("resizable_x", ImGuiChildFlags_ResizeX, inConfig.childFlags); - checkbitset("resizable_y", ImGuiChildFlags_ResizeY, inConfig.childFlags); - checkbitset("flattened_navigation", ImGuiChildFlags_NavFlattened, inConfig.childFlags); -} - -void -DearPyGui::fill_configuration_dict(const mvGroupConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "horizontal", mvPyObject(ToPyBool(inConfig.horizontal))); - PyDict_SetItemString(outDict, "horizontal_spacing", mvPyObject(ToPyFloat(inConfig.hspacing))); - PyDict_SetItemString(outDict, "xoffset", mvPyObject(ToPyFloat(inConfig.xoffset))); -} - -void -DearPyGui::fill_configuration_dict(const mvDragPayloadConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyObject* dragData = *(inConfig.dragData); - PyDict_SetItemString(outDict, "drag_data", dragData? dragData : Py_None); - - PyObject* dropData = *(inConfig.dropData); - PyDict_SetItemString(outDict, "drop_data", dropData? dropData : Py_None); -} - -void -DearPyGui::fill_configuration_dict(const mvTreeNodeConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "selectable", mvPyObject(ToPyBool(inConfig.selectable))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - // flags - checkbitset("default_open", ImGuiTreeNodeFlags_DefaultOpen, inConfig.flags); - checkbitset("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, inConfig.flags); - checkbitset("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, inConfig.flags); - checkbitset("leaf", ImGuiTreeNodeFlags_Leaf, inConfig.flags); - checkbitset("bullet", ImGuiTreeNodeFlags_Bullet, inConfig.flags); - checkbitset("span_text_width", ImGuiTreeNodeFlags_SpanLabelWidth, inConfig.flags); - // checkbitset("span_available_width", ImGuiTreeNodeFlags_SpanAvailWidth, inConfig.flags); - checkbitset("span_full_width", ImGuiTreeNodeFlags_SpanFullWidth, inConfig.flags); - // checkbitset("span_all_columns", ImGuiTreeNodeFlags_SpanAllColumns, inConfig.flags); - checkbitset("catch_nav_left", ImGuiTreeNodeFlags_NavLeftJumpsToParent, inConfig.flags); - - PyDict_SetItemString(outDict, "lines", mvPyObject(ToPyInt(inConfig.flags & (ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)))); -} - -void -DearPyGui::fill_configuration_dict(const mvTabBarConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - checkbitset("reorderable", ImGuiTabBarFlags_Reorderable, inConfig.flags); - checkbitset("tab_list_popup_button", ImGuiTabBarFlags_TabListPopupButton, inConfig.flags); - checkbitset("no_close_with_middle_click", ImGuiTabBarFlags_NoCloseWithMiddleMouseButton, inConfig.flags); - checkbitset("no_scrolling_buttons", ImGuiTabBarFlags_NoTabListScrollingButtons, inConfig.flags); - checkbitset("no_tooltip", ImGuiTabBarFlags_NoTooltip, inConfig.flags); - checkbitset("draw_selected_overline", ImGuiTabBarFlags_DrawSelectedOverline, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvCollapsingHeaderConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "closable", mvPyObject(ToPyBool(inConfig.closable))); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - // flags - checkbitset("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, inConfig.flags); - checkbitset("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, inConfig.flags); - checkbitset("leaf", ImGuiTreeNodeFlags_Leaf, inConfig.flags); - checkbitset("bullet", ImGuiTreeNodeFlags_Bullet, inConfig.flags); -} - -void -DearPyGui::fill_configuration_dict(const mvWindowAppItemConfig& inConfig, PyObject* outDict) -{ - if (outDict == nullptr) - return; - - PyDict_SetItemString(outDict, "no_open_over_existing_popup", mvPyObject(ToPyBool(inConfig.no_open_over_existing_popup))); - PyDict_SetItemString(outDict, "modal", mvPyObject(ToPyBool(inConfig.modal))); - PyDict_SetItemString(outDict, "popup", mvPyObject(ToPyBool(inConfig.popup))); - PyDict_SetItemString(outDict, "no_close", mvPyObject(ToPyBool(inConfig.no_close))); - PyDict_SetItemString(outDict, "collapsed", mvPyObject(ToPyBool(inConfig.collapsed))); - PyDict_SetItemString(outDict, "min_size", mvPyObject(ToPyPairII((int)inConfig.min_size.x, (int)inConfig.min_size.y))); - PyDict_SetItemString(outDict, "max_size", mvPyObject(ToPyPairII((int)inConfig.max_size.x, (int)inConfig.max_size.y))); - PyDict_SetItemString(outDict, "copy_contents_shortcut", mvPyObject(ToPyBool(inConfig.copy_contents_shortcut))); - - PyObject* on_close = inConfig.on_close; - PyDict_SetItemString(outDict, "on_close", on_close? on_close : Py_None); - - // helper to check and set bit - auto checkbitset = [outDict](const char* keyword, int flag, const int& flags) - { - PyDict_SetItemString(outDict, keyword, mvPyObject(ToPyBool(flags & flag))); - }; - - // window flags - checkbitset("autosize", ImGuiWindowFlags_AlwaysAutoResize, inConfig.windowflags); - checkbitset("no_resize", ImGuiWindowFlags_NoResize, inConfig.windowflags); - checkbitset("no_title_bar", ImGuiWindowFlags_NoTitleBar, inConfig.windowflags); - checkbitset("no_move", ImGuiWindowFlags_NoMove, inConfig.windowflags); - checkbitset("no_scrollbar", ImGuiWindowFlags_NoScrollbar, inConfig.windowflags); - checkbitset("no_collapse", ImGuiWindowFlags_NoCollapse, inConfig.windowflags); - checkbitset("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, inConfig.windowflags); - checkbitset("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, inConfig.windowflags); - checkbitset("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, inConfig.windowflags); - checkbitset("menubar", ImGuiWindowFlags_MenuBar, inConfig.windowflags); - checkbitset("no_background", ImGuiWindowFlags_NoBackground, inConfig.windowflags); - checkbitset("no_saved_settings", ImGuiWindowFlags_NoSavedSettings, inConfig.windowflags); - checkbitset("no_scroll_with_mouse", ImGuiWindowFlags_NoScrollWithMouse, inConfig.windowflags); - checkbitset("unsaved_document", ImGuiWindowFlags_UnsavedDocument, inConfig.windowflags); - checkbitset("no_docking", ImGuiWindowFlags_NoDocking, inConfig.windowflags); -} - -//----------------------------------------------------------------------------- -// [SECTION] configure_item(...) specifics -//----------------------------------------------------------------------------- - -void -DearPyGui::set_configuration(PyObject* inDict, mvMenuConfig& outConfig, mvAppItem& itemc) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "enabled")) itemc.config.enabled = ToBool(item); - -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTabConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "closable")) outConfig.closable = ToBool(item); - - - if (PyObject* item = PyDict_GetItemString(inDict, "order_mode")) - { - long order_mode = (long)ToUUID(item); - - if (order_mode == (long)TabOrdering::mvTabOrder_Fixed) - outConfig._flags = ImGuiTabItemFlags_NoReorder; - else if (order_mode == (long)TabOrdering::mvTabOrder_Leading) - outConfig._flags = ImGuiTabItemFlags_Leading; - else if (order_mode == (long)TabOrdering::mvTabOrder_Trailing) - outConfig._flags = ImGuiTabItemFlags_Trailing; - else - outConfig._flags = ImGuiTabItemFlags_None; - } - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - flagop("no_tooltip", ImGuiTabItemFlags_NoTooltip, outConfig._flags); - flagop("unsaved_document", ImGuiTabItemFlags_UnsavedDocument, outConfig._flags); - flagop("no_close_with_middle_click", ImGuiTabItemFlags_NoCloseWithMiddleMouseButton, outConfig._flags); - flagop("no_reorder", ImGuiTabItemFlags_NoReorder, outConfig._flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvChildWindowConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "autosize_x")) outConfig.autosize_x = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "autosize_y")) outConfig.autosize_y = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // window flags - flagop("no_scrollbar", ImGuiWindowFlags_NoScrollbar, outConfig.windowflags); - flagop("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, outConfig.windowflags); - flagop("menubar", ImGuiWindowFlags_MenuBar, outConfig.windowflags); - flagop("no_scroll_with_mouse", ImGuiWindowFlags_NoScrollWithMouse, outConfig.windowflags); - - // child flags - flagop("border", ImGuiChildFlags_Borders, outConfig.childFlags); - flagop("always_auto_resize", ImGuiChildFlags_AlwaysAutoResize, outConfig.childFlags); - flagop("always_use_window_padding", ImGuiChildFlags_AlwaysUseWindowPadding, outConfig.childFlags); - flagop("auto_resize_x", ImGuiChildFlags_AutoResizeX, outConfig.childFlags); - flagop("auto_resize_y", ImGuiChildFlags_AutoResizeY, outConfig.childFlags); - flagop("frame_style", ImGuiChildFlags_FrameStyle, outConfig.childFlags); - flagop("resizable_x", ImGuiChildFlags_ResizeX, outConfig.childFlags); - flagop("resizable_y", ImGuiChildFlags_ResizeY, outConfig.childFlags); - flagop("flattened_navigation", ImGuiChildFlags_NavFlattened, outConfig.childFlags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvGroupConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "horizontal")) outConfig.horizontal = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "horizontal_spacing")) outConfig.hspacing = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(inDict, "xoffset")) outConfig.xoffset = ToFloat(item); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvDragPayloadConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "payload_type")) outConfig.payloadType = ToString(item); - - if (PyObject* item = PyDict_GetItemString(inDict, "drag_data")) - { - *outConfig.dragData = mvPyObject(item == Py_None? nullptr : item, true); - } - - if (PyObject* item = PyDict_GetItemString(inDict, "drop_data")) - { - *outConfig.dropData = mvPyObject(item == Py_None? nullptr : item, true); - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTreeNodeConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "selectable")) outConfig.selectable = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "default_open")) *outConfig.value = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("default_open", ImGuiTreeNodeFlags_DefaultOpen, outConfig.flags); - flagop("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, outConfig.flags); - flagop("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, outConfig.flags); - flagop("leaf", ImGuiTreeNodeFlags_Leaf, outConfig.flags); - flagop("bullet", ImGuiTreeNodeFlags_Bullet, outConfig.flags); - flagop("span_text_width", ImGuiTreeNodeFlags_SpanLabelWidth, outConfig.flags); - // flagop("span_available_width", ImGuiTreeNodeFlags_SpanAvailWidth, outConfig.flags); - flagop("span_full_width", ImGuiTreeNodeFlags_SpanFullWidth, outConfig.flags); - // flagop("span_all_columns", ImGuiTreeNodeFlags_SpanAllColumns, outConfig.flags); - flagop("catch_nav_left", ImGuiTreeNodeFlags_NavLeftJumpsToParent, outConfig.flags); - - if (PyObject* item = PyDict_GetItemString(inDict, "lines")) - { - outConfig.flags &= ~(ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes); - outConfig.flags |= ToInt(item); - } -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvTabBarConfig& outConfig) -{ - if (inDict == nullptr) - return; - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - flagop("reorderable", ImGuiTabBarFlags_Reorderable, outConfig.flags); - flagop("tab_list_popup_button", ImGuiTabBarFlags_TabListPopupButton, outConfig.flags); - flagop("no_close_with_middle_click", ImGuiTabBarFlags_NoCloseWithMiddleMouseButton, outConfig.flags); - flagop("no_scrolling_buttons", ImGuiTabBarFlags_NoTabListScrollingButtons, outConfig.flags); - flagop("no_tooltip", ImGuiTabBarFlags_NoTooltip, outConfig.flags); - flagop("draw_selected_overline", ImGuiTabBarFlags_DrawSelectedOverline, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvCollapsingHeaderConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "closable")) outConfig.closable = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "default_open")) *outConfig.value = ToBool(item); - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // flags - flagop("open_on_double_click", ImGuiTreeNodeFlags_OpenOnDoubleClick, outConfig.flags); - flagop("open_on_arrow", ImGuiTreeNodeFlags_OpenOnArrow, outConfig.flags); - flagop("leaf", ImGuiTreeNodeFlags_Leaf, outConfig.flags); - flagop("bullet", ImGuiTreeNodeFlags_Bullet, outConfig.flags); -} - -void -DearPyGui::set_configuration(PyObject* inDict, mvAppItem& itemc, mvWindowAppItemConfig& outConfig) -{ - if (inDict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(inDict, "modal")) - { - outConfig.modal = ToBool(item); - itemc.info.shownLastFrame = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "popup")) - { - outConfig.popup = ToBool(item); - itemc.info.shownLastFrame = true; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "label")) - { - if (item != Py_None) - { - itemc.info.dirtyPos = true; - itemc.info.dirty_size = true; - } - } - - if (PyObject* item = PyDict_GetItemString(inDict, "no_open_over_existing_popup")) outConfig.no_open_over_existing_popup = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "no_close")) outConfig.no_close = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "copy_contents_shortcut")) outConfig.copy_contents_shortcut = ToBool(item); - if (PyObject* item = PyDict_GetItemString(inDict, "collapsed")) - { - outConfig._collapsedDirty = true; - outConfig.collapsed = ToBool(item); - } - - if (PyObject* item = PyDict_GetItemString(inDict, "min_size")) - { - auto min_size = ToIntVect(item); - outConfig.min_size = { (float)min_size[0], (float)min_size[1] }; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "max_size")) - { - auto max_size = ToIntVect(item); - outConfig.max_size = { (float)max_size[0], (float)max_size[1] }; - } - - if (PyObject* item = PyDict_GetItemString(inDict, "on_close")) - { - outConfig.on_close = mvPyObject(item == Py_None? nullptr : item, true); - } - - // helper for bit flipping - auto flagop = [inDict](const char* keyword, int flag, int& flags) - { - if (PyObject* item = PyDict_GetItemString(inDict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; - }; - - // window flags - flagop("autosize", ImGuiWindowFlags_AlwaysAutoResize, outConfig.windowflags); - flagop("no_move", ImGuiWindowFlags_NoMove, outConfig.windowflags); - flagop("no_resize", ImGuiWindowFlags_NoResize, outConfig.windowflags); - flagop("no_title_bar", ImGuiWindowFlags_NoTitleBar, outConfig.windowflags); - flagop("no_scrollbar", ImGuiWindowFlags_NoScrollbar, outConfig.windowflags); - flagop("no_collapse", ImGuiWindowFlags_NoCollapse, outConfig.windowflags); - flagop("horizontal_scrollbar", ImGuiWindowFlags_HorizontalScrollbar, outConfig.windowflags); - flagop("no_focus_on_appearing", ImGuiWindowFlags_NoFocusOnAppearing, outConfig.windowflags); - flagop("no_bring_to_front_on_focus", ImGuiWindowFlags_NoBringToFrontOnFocus, outConfig.windowflags); - flagop("menubar", ImGuiWindowFlags_MenuBar, outConfig.windowflags); - flagop("no_background", ImGuiWindowFlags_NoBackground, outConfig.windowflags); - flagop("no_saved_settings", ImGuiWindowFlags_NoSavedSettings, outConfig.windowflags); - flagop("no_scroll_with_mouse", ImGuiWindowFlags_NoScrollWithMouse, outConfig.windowflags); - flagop("unsaved_document", ImGuiWindowFlags_UnsavedDocument, outConfig.windowflags); - flagop("no_docking", ImGuiWindowFlags_NoDocking, outConfig.windowflags); -} - -//----------------------------------------------------------------------------- -// [SECTION] positional args specifics -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// [SECTION] data sources -//----------------------------------------------------------------------------- - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvMenuConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvTabConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(item.type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvTreeNodeConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(mvAppItemType::mvTreeNode)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvTabBarConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(mvAppItemType::mvTabBar)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -void -DearPyGui::set_data_source(mvAppItem& item, mvUUID dataSource, mvCollapsingHeaderConfig& outConfig) -{ - if (dataSource == item.config.source) return; - item.config.source = dataSource; - - mvAppItem* srcItem = GetItem((*GContext->itemRegistry), dataSource); - if (!srcItem) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), &item); - return; - } - if (DearPyGui::GetEntityValueType(srcItem->type) != DearPyGui::GetEntityValueType(mvAppItemType::mvCollapsingHeader)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), &item); - return; - } - outConfig.value = *static_cast*>(srcItem->getValue()); -} - -//----------------------------------------------------------------------------- -// [SECTION] draw commands -//----------------------------------------------------------------------------- - -void -DearPyGui::draw_menu(ImDrawList* drawlist, mvAppItem& item, mvMenuConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - // create menu and see if its selected - if (ImGui::BeginMenu(item.info.internalLabel.c_str(), item.config.enabled)) - { - item.state.lastFrameUpdate = GContext->frame; - item.state.active = ImGui::IsItemActive(); - item.state.activated = ImGui::IsItemActivated(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.prevFocused = item.state.focused; - item.state.focused = ImGui::IsWindowFocused(); - item.state.prevHovered = item.state.hovered; - item.state.hovered = ImGui::IsWindowHovered(); - item.state.rectSize = { ImGui::GetWindowWidth(), ImGui::GetWindowHeight() }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - - // set other menus's value false on same level - for (auto& sibling : item.info.parentPtr->childslots[1]) - { - // ensure sibling - if (sibling->type == mvAppItemType::mvMenu) - *((mvMenu*)sibling.get())->configData.value = false; - } - - // set current menu value true - *config.value = true; - - for (auto& child : item.childslots[1]) - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows)) - { - - // update mouse - ImVec2 mousePos = ImGui::GetMousePos(); - float x = mousePos.x - ImGui::GetWindowPos().x; - float y = mousePos.y - ImGui::GetWindowPos().y; - GContext->input.mousePos.x = (int)x; - GContext->input.mousePos.y = (int)y; - - - GContext->activeWindow = item.uuid; - - } - - ImGui::EndMenu(); - } - else - { - // even if menu popup is not open, we still need to update the state - item.state.lastFrameUpdate = GContext->frame; - item.state.active = ImGui::IsItemActive(); - item.state.activated = ImGui::IsItemActivated(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.prevFocused = item.state.focused; - item.state.focused = false; - item.state.prevHovered = item.state.hovered; - item.state.hovered = false; - item.state.rectSize = { 0.0f, 0.0f }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - } - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_tab(ImDrawList* drawlist, mvAppItem& item, mvTabConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - // cast parent to mvTabBar - auto parent = (mvTabBar*)item.info.parentPtr; - - // check if this is first tab - if (parent->getSpecificValue() == 0) - { - // set mvTabBar value to the first tab name - parent->setValue(item.uuid); - *config.value = true; - } - - item.state.lastFrameUpdate = GContext->frame; - item.state.prevHovered = item.state.hovered; - // create tab item and see if it is selected - if (ImGui::BeginTabItem(item.info.internalLabel.c_str(), config.closable ? &item.config.show : nullptr, config._flags)) - { - - item.state.hovered = ImGui::IsItemHovered(); - item.state.active = ImGui::IsItemActive(); - item.state.leftclicked = ImGui::IsItemClicked(); - item.state.rightclicked = ImGui::IsItemClicked(1); - item.state.middleclicked = ImGui::IsItemClicked(2); - for (int i = 0; i < item.state.doubleclicked.size(); i++) - { - item.state.doubleclicked[i] = IsItemDoubleClicked(i); - } - item.state.visible = ImGui::IsItemVisible(); - item.state.activated = ImGui::IsItemActivated(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y }; - item.state.rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y }; - item.state.rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - - // set other tab's value false - for (auto& child : parent->childslots[1]) - { - if (child->type == mvAppItemType::mvTab) - *((mvTab*)child.get())->configData.value = false; - } - - // set current tab value true - *config.value = true; - - // run call back if it exists - if (parent->getSpecificValue() != item.uuid) - { - parent->submitCallback(&item); - } - - parent->setValue(item.uuid); - - for (auto& item : item.childslots[1]) - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - ImGui::EndTabItem(); - } - - else - { - item.state.hovered = ImGui::IsItemHovered(); - item.state.active = ImGui::IsItemActive(); - item.state.leftclicked = ImGui::IsItemClicked(); - item.state.rightclicked = ImGui::IsItemClicked(1); - item.state.middleclicked = ImGui::IsItemClicked(2); - for (int i = 0; i < item.state.doubleclicked.size(); i++) - { - item.state.doubleclicked[i] = IsItemDoubleClicked(i); - } - item.state.visible = ImGui::IsItemVisible(); - item.state.activated = ImGui::IsItemActivated(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y }; - item.state.rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y }; - item.state.rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - } - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_child_window(ImDrawList* drawlist, mvAppItem& item, mvChildWindowConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - item.handleImmediateScroll(); - - // TODO: Do we want to put an if statement to prevent further drawing if not shown? - ImGui::BeginChild(item.info.internalLabel.c_str(), ImVec2(config.autosize_x ? 0 : (float)item.config.width, config.autosize_y ? 0 : (float)item.config.height), config.childFlags, config.windowflags); - item.state.lastFrameUpdate = GContext->frame; - item.state.active = ImGui::IsItemActive(); - item.state.deactivated = ImGui::IsItemDeactivated(); - item.state.prevFocused = item.state.focused; - item.state.focused = ImGui::IsWindowFocused(); - item.state.prevHovered = item.state.hovered; - item.state.hovered = ImGui::IsWindowHovered(); - item.state.rectSize = { ImGui::GetWindowWidth(), ImGui::GetWindowHeight() }; - item.state.contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y }; - - for (auto& child : item.childslots[1]) - { - - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - if (child->config.tracked) - { - ImGui::SetScrollHereX(child->config.trackOffset); - ImGui::SetScrollHereY(child->config.trackOffset); - } - - } - - item.handleDelayedScroll(); - item.config.scrollXFlags = item.config.scrollYFlags = mvSetScrollFlags_None; - - // allows this item to have a render callback - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows)) - { - - // update mouse - ImVec2 mousePos = ImGui::GetMousePos(); - float x = mousePos.x - ImGui::GetWindowPos().x; - float y = mousePos.y - ImGui::GetWindowPos().y; - GContext->input.mousePos.x = (int)x; - GContext->input.mousePos.y = (int)y; - - GContext->activeWindow = item.uuid; - - } - - UpdateAppItemScrollInfo(item.state); - - ImGui::EndChild(); - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - // update state (for resize handler) - if (item.state.mvPrevRectSize.x != item.state.rectSize.x || item.state.mvPrevRectSize.y != item.state.rectSize.y) { item.state.mvRectSizeResized = true; } - else item.state.mvRectSizeResized = false; - item.state.mvPrevRectSize = item.state.rectSize; - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_group(ImDrawList* drawlist, mvAppItem& item, mvGroupConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - if (item.config.width != 0) - ImGui::PushItemWidth((float)item.config.width); - - if (!item.config.enabled) - ImGui::BeginDisabled(); - - ImGui::BeginGroup(); - - for (auto& child : item.childslots[1]) - { - if (item.config.width != 0) - child->config.width = item.config.width; - - if (item.config.height != 0) - child->config.height = item.config.height; - - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - if (config.horizontal && child->config.show) - ImGui::SameLine((1 + child->info.location) * config.xoffset, config.hspacing); - - if (child->config.tracked) - { - ImGui::SetScrollHereX(child->config.trackOffset); - ImGui::SetScrollHereY(child->config.trackOffset); - } - } - - if (item.config.width != 0) - ImGui::PopItemWidth(); - - ImGui::EndGroup(); - - if (!item.config.enabled) - ImGui::EndDisabled(); - - UpdateAppItemState(item.state); - - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_drag_payload(ImDrawList* drawlist, mvAppItem& item, mvDragPayloadConfig& config) -{ - if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) - { - // ImGui uses memcpy to store the drag data, and the only thing we can - // store this way more ore less safely is the numeric UUID. Worst case if - // the payload gets deleted during drag'n'drop, we'll simply abandon - // the drop callback. - ImGui::SetDragDropPayload(config.payloadType.c_str(), &item.uuid, sizeof(item.uuid)); - - // The mvDragPayload item is a bit peculiar: historically, it uses its own user_data - // to pass to the parent item's drag callback. That's why we can't directly - // call parentPtr->submitCallback(), as it would take user_data from the parent - // instead of mvDragPayload. - mvAppItem* parent = item.info.parentPtr; - if (parent->config.dragCallback) - { - // We can't use mvAppItem::submitCallbackEx here because we need custom user_data. - mvAddCallback( - parent->weak_from_this(), - parent->config.dragCallback, - item.config.user_data, - parent->uuid, parent->config.alias, - [dragData=config.dragData] () { - PyObject* pyDragData = *dragData; - Py_XINCREF(pyDragData); - return pyDragData; - } - ); - } - - for (auto& childset : item.childslots) - { - for (auto& child : childset) - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } - - ImGui::EndDragDropSource(); - } -} - -void -DearPyGui::draw_tree_node(ImDrawList* drawlist, mvAppItem& item, mvTreeNodeConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(item.uuid); - - ImGui::BeginGroup(); - - if (*config.value && config.selectable) - config.flags |= ImGuiTreeNodeFlags_Selected; - else - config.flags &= ~ImGuiTreeNodeFlags_Selected; - - ImGui::SetNextItemOpen(*config.value); - - bool is_open = ImGui::TreeNodeEx(item.info.internalLabel.c_str(), config.flags); - - UpdateAppItemState(item.state); - - // We're only updating the value when we know that the change was triggered - // by the user. Note that `is_open` might be reset to `false` while the - // tree node is actually open, e.g. when the parent window gets out of sight. - if (item.state.toggledOpen) - *config.value = is_open; - - if (item.state.toggledOpen && !*config.value) - { - item.state.toggledOpen = false; - } - - if (!is_open) - { - ImGui::EndGroup(); - } - else - { - for (auto& child : item.childslots[1]) - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - ImGui::TreePop(); - ImGui::EndGroup(); - } - - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_tab_bar(ImDrawList* drawlist, mvAppItem& item, mvTabBarConfig& config) -{ - if (!item.config.show) - return; - - ScopedID id(item.uuid); - - ImGui::BeginGroup(); - - if (ImGui::BeginTabBar(item.info.internalLabel.c_str(), config.flags)) - { - - item.state.lastFrameUpdate = GContext->frame; - item.state.visible = true; // BeginTabBar(...) only reaches this if visible - - for (auto& child : item.childslots[1]) - { - - if (*config.value == child->uuid && config._lastValue != *config.value) - static_cast(child.get())->configData._flags |= ImGuiTabItemFlags_SetSelected; - - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - if (*config.value == child->uuid) - static_cast(child.get())->configData._flags &= ~ImGuiTabItemFlags_SetSelected; - } - - ImGui::EndTabBar(); - } - - ImGui::EndGroup(); - - *config.value = config.uiValue; - config._lastValue = *config.value; -} - -void -DearPyGui::draw_collapsing_header(ImDrawList* drawlist, mvAppItem& item, mvCollapsingHeaderConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!item.config.show) - return; - - // focusing - if (item.info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - item.info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (item.info.dirtyPos) - ImGui::SetCursorPos(item.state.pos); - - // update widget's position state - item.state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (item.config.width != 0) - ImGui::SetNextItemWidth((float)item.config.width); - - // set indent - if (item.config.indent > 0.0f) - ImGui::Indent(item.config.indent); - - // push font if a font object is attached - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(item.uuid); - - bool* toggle = nullptr; - if (config.closable) - toggle = &item.config.show; - - ImGui::SetNextItemOpen(*config.value); - - bool is_open = ImGui::CollapsingHeader(item.info.internalLabel.c_str(), toggle, config.flags); - - UpdateAppItemState(item.state); - - // We're only updating the value when we know that the change was triggered - // by the user. Note that `is_open` might be reset to `false` while the - // header is actually open, e.g. when the parent window gets out of sight. - if (item.state.toggledOpen) - *config.value = is_open; - - if (is_open) - { - for (auto& child : item.childslots[1]) - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } - - if (item.state.toggledOpen && !*config.value) - { - item.state.toggledOpen = false; - } - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (item.info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (item.config.indent > 0.0f) - ImGui::Unindent(item.config.indent); - - // pop font off stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); - - // handle drag & drop if used - apply_drag_drop(&item); -} - -void -DearPyGui::draw_window(ImDrawList* drawlist, mvAppItem& item, mvWindowAppItemConfig& config) -{ - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - if (!item.config.show) - return; - - if (GContext->frame == 1 && !GContext->IO.iniFile.empty() && !(config.windowflags & ImGuiWindowFlags_NoSavedSettings)) - { - item.info.dirtyPos = false; - item.info.dirty_size = false; - config._collapsedDirty = false; - } - - if (item.info.focusNextFrame) - { - ImGui::SetNextWindowFocus(); - item.info.focusNextFrame = false; - } - - // handle fonts - if (item.font) - static_cast(item.font.get())->pushFont(); - - // themes - apply_local_theming(&item); - - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - - ScopedID id(item.uuid); - - // For primary windows, we'll need to massage the flags - ImGuiWindowFlags windowFlags = config.windowflags; - if (config.mainWindow) - { - ImGui::SetNextWindowBgAlpha(1.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); // to prevent main window corners from showing - ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); - ImGui::SetNextWindowSize(ImVec2((float)GContext->viewport->clientWidth, (float)GContext->viewport->clientHeight)); - windowFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings - | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove; - windowFlags &= ~ImGuiWindowFlags_AlwaysAutoResize; - } - - else if (item.info.dirtyPos) - { - ImGui::SetNextWindowPos(item.state.pos); - item.info.dirtyPos = false; - } - - if (item.info.dirty_size) - { - ImGui::SetNextWindowSize(ImVec2((float)item.config.width, (float)item.config.height)); - item.info.dirty_size = false; - } - - if (config._collapsedDirty) - { - ImGui::SetNextWindowCollapsed(config.collapsed); - config._collapsedDirty = false; - } - - ImGui::SetNextWindowSizeConstraints(config.min_size, config.max_size); - - item.handleImmediateScroll(); - - if (config.modal) - { - if (item.info.shownLastFrame) - { - item.info.shownLastFrame = false; - ImGui::OpenPopup(item.info.internalLabel.c_str(), config.no_open_over_existing_popup ? ImGuiPopupFlags_NoOpenOverExistingPopup : ImGuiPopupFlags_None); - } - - if (!ImGui::BeginPopupModal(item.info.internalLabel.c_str(), config.no_close ? nullptr : &item.config.show, windowFlags)) - { - if (config.mainWindow) - ImGui::PopStyleVar(); - - // shouldn't have to do this but do. Fix later - item.config.show = false; - item.state.lastFrameUpdate = GContext->frame; - item.state.prevHovered = item.state.hovered; - item.state.hovered = false; - item.state.prevFocused = item.state.focused; - item.state.focused = false; - item.state.toggledOpen = false; - item.state.visible = false; - - item.submitCallbackEx(config.on_close, []() -> PyObject* { return nullptr; }); - - // handle popping themes - cleanup_local_theming(&item); - - return; - } - } - - else if (config.popup) - { - if (item.info.shownLastFrame) - { - item.info.shownLastFrame = false; - ImGui::OpenPopup(item.info.internalLabel.c_str(), config.no_open_over_existing_popup ? ImGuiPopupFlags_NoOpenOverExistingPopup : ImGuiPopupFlags_None); - } - - if (!ImGui::BeginPopup(item.info.internalLabel.c_str(), windowFlags)) - { - if (config.mainWindow) - ImGui::PopStyleVar(); - - // handle popping themes - cleanup_local_theming(&item); - - // See if it's just been closed (can't rely on BeginPopup == false here - // because BeginPopup can, even if only theoretically, return false for - // an open popup - e.g. when it has zero size). - if (!ImGui::IsPopupOpen(item.info.internalLabel.c_str())) - { - // Hide it so that the callback doesn't fire at the next frame - item.config.show = false; - // Update item state so that get_item_state is valid - item.state.lastFrameUpdate = GContext->frame; - item.state.prevHovered = item.state.hovered; - item.state.hovered = false; - item.state.prevFocused = item.state.focused; - item.state.focused = false; - item.state.toggledOpen = false; - item.state.visible = false; - // Fire the close callback, if any - item.submitCallbackEx(config.on_close, []() -> PyObject* { return nullptr; }); - } - return; - } - } - - else - { - ImGuiIO &io = ImGui::GetIO(); - io.ConfigWindowsCopyContentsWithCtrlC = config.copy_contents_shortcut; - - if (!ImGui::Begin(item.info.internalLabel.c_str(), config.no_close ? nullptr : &item.config.show, windowFlags)) - { - if (config.mainWindow) - ImGui::PopStyleVar(); - - ImGui::End(); - - // handle popping themes - cleanup_local_theming(&item); - - return; - } - } - - ImDrawList* this_drawlist = ImGui::GetWindowDrawList(); - - float startx = (float)ImGui::GetCursorScreenPos().x; - float starty = (float)ImGui::GetCursorScreenPos().y; - - if (config.mainWindow) - ImGui::PopStyleVar(); - - for (auto& child : item.childslots[0]) - { - // skip item if it's not shown - if (!child->config.show) - continue; - - child->draw(this_drawlist, startx, starty); - - UpdateAppItemState(child->state); - - } - - for (auto& child : item.childslots[1]) - { - - child->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - if (child->config.tracked) - ImGui::SetScrollHereY(child->config.trackOffset); - - } - - for (auto& child : item.childslots[2]) - { - // skip item if it's not shown - if (!child->config.show) - continue; - - child->draw(this_drawlist, startx, starty); - - UpdateAppItemState(child->state); - - } - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // pop font from stack - if (item.font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(&item); - - item.handleDelayedScroll(); - item.config.scrollXFlags = item.config.scrollYFlags = mvSetScrollFlags_None; - - UpdateAppItemScrollInfo(item.state); - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - - item.state.lastFrameUpdate = GContext->frame; - item.state.visible = true; - item.state.prevHovered = item.state.hovered; - item.state.hovered = ImGui::IsWindowHovered(); - item.state.prevFocused = item.state.focused; - item.state.focused = ImGui::IsWindowFocused(); - item.state.rectSize = { ImGui::GetWindowSize().x, ImGui::GetWindowSize().y }; - item.state.toggledOpen = ImGui::IsWindowCollapsed(); - if (item.state.mvPrevRectSize.x != item.state.rectSize.x || item.state.mvPrevRectSize.y != item.state.rectSize.y) { item.state.mvRectSizeResized = true; } - else item.state.mvRectSizeResized = false; - item.state.mvPrevRectSize = item.state.rectSize; - - if (ImGui::GetWindowWidth() != (float)item.config.width || ImGui::GetWindowHeight() != (float)item.config.height) - { - item.config.width = (int)ImGui::GetWindowWidth(); - item.config.height = (int)ImGui::GetWindowHeight(); - config.resized = true; - } - - item.config.width = (int)ImGui::GetWindowWidth(); - item.config.height = (int)ImGui::GetWindowHeight(); - - // update active window - if (IsItemFocused(item.state)) - { - - float titleBarHeight = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); - - // update mouse - ImVec2 mousePos = ImGui::GetMousePos(); - float x = mousePos.x - ImGui::GetWindowPos().x; - float y = mousePos.y - ImGui::GetWindowPos().y - titleBarHeight; - GContext->input.mousePos.x = (int)x; - GContext->input.mousePos.y = (int)y; - - GContext->activeWindow = item.uuid; - - } - - item.state.pos = { ImGui::GetWindowPos().x , ImGui::GetWindowPos().y }; - - if (config.popup || config.modal) - ImGui::EndPopup(); - else - ImGui::End(); - - config.collapsed = ImGui::IsWindowCollapsed(); - - if (!item.config.show) - { - item.state.lastFrameUpdate = GContext->frame; - item.state.prevHovered = item.state.hovered; - item.state.hovered = false; - item.state.prevFocused = item.state.focused; - item.state.focused = false; - item.state.toggledOpen = false; - item.state.visible = false; - - item.submitCallbackEx(config.on_close, []() -> PyObject* { return nullptr; }); - } - - if (item.handlerRegistry) - item.handlerRegistry->checkEvents(&item.state); -} - -void -check_drop_event(mvAppItem* item) -{ - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(item->config.payloadType.c_str())) - { - IM_ASSERT(payload->DataSize == sizeof(mvUUID) && "Unexpected drag payload data size."); - mvUUID payloadUUID = *(mvUUID*)payload->Data; - // Let's see if the payload still exists. - auto payloadItem = GetItem(*GContext->itemRegistry, payloadUUID); - if (payloadItem && payloadItem->type == mvAppItemType::mvDragPayload) - { - auto payloadActual = static_cast(payloadItem); - // Note: we're passing None in user_data for backward compatibility - // (mvAddCallback will derive None from the mvPyObject that stores nullptr). - // One day this may change, but we need to decide which of the user_data's - // (parent's or payload's) we're going to pass here. - // We can't use mvAppItem::submitCallbackEx here because we need custom user_data. - mvAddCallback( - item->weak_from_this(), - item->config.dropCallback, - std::make_shared(nullptr), - item->uuid, item->config.alias, - [dragData = payloadActual->configData.dragData] () { - PyObject* pyDragData = *dragData; - Py_XINCREF(pyDragData); - return pyDragData; - } - ); - } - } -} - -void -apply_drag_drop(mvAppItem* item) -{ - for (auto& item : item->childslots[3]) - item->draw(nullptr, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - - if (item->config.dropCallback) - { - ScopedID id(item->uuid); - if (ImGui::BeginDragDropTarget()) - { - check_drop_event(item); - ImGui::EndDragDropTarget(); - } - } -} - -void -apply_drag_drop_nodraw(mvAppItem* item) -{ - if (item->config.dropCallback) - { - ScopedID id(item->uuid); - if (ImGui::BeginDragDropTarget()) - { - check_drop_event(item); - ImGui::EndDragDropTarget(); - } - } -} diff --git a/src/mvContainers.h b/src/mvContainers.h deleted file mode 100644 index 5d9ca99c0..000000000 --- a/src/mvContainers.h +++ /dev/null @@ -1,275 +0,0 @@ -#pragma once - -#include "mvItemRegistry.h" - -// check_drop_event() implements the typical contents of Dear ImGui's drop target -// (ImGui::BeginDragDropTarget()) tied to DearPyGui's drop callback. You usually -// don't need to call it directly, but it can be used need to implement custom -// drag'n'drop mechanics. -// To implement drag'n'drop in an arbitrary ImGui item, use `apply_drag_drop()` - -// it both implements the entire drop target and renders the drag payload. -void check_drop_event(mvAppItem* item); -// During drag'n'drop, renders drag payload and checks whether it's time to call -// the drop callback. -void apply_drag_drop(mvAppItem* item); -void apply_drag_drop_nodraw(mvAppItem* item); - -struct mvChildWindowConfig; -struct mvTreeNodeConfig; -struct mvGroupConfig; -struct mvDragPayloadConfig; -struct mvCollapsingHeaderConfig; -struct mvTabBarConfig; -struct mvWindowAppItemConfig; -struct mvMenuConfig; -struct mvTabConfig; - -namespace DearPyGui -{ - // specific part of `get_item_configuration(...)` - void fill_configuration_dict(const mvMenuConfig& inConfig, PyObject* outDict, mvAppItem& item); - void fill_configuration_dict(const mvTabConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvChildWindowConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvGroupConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvDragPayloadConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvTreeNodeConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvTabBarConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvCollapsingHeaderConfig& inConfig, PyObject* outDict); - void fill_configuration_dict(const mvWindowAppItemConfig& inConfig, PyObject* outDict); - - // specific part of `configure_item(...)` - void set_configuration(PyObject* inDict, mvMenuConfig& outConfig, mvAppItem& item); - void set_configuration(PyObject* inDict, mvTabConfig& outConfig); - void set_configuration(PyObject* inDict, mvChildWindowConfig& outConfig); - void set_configuration(PyObject* inDict, mvGroupConfig& outConfig); - void set_configuration(PyObject* inDict, mvDragPayloadConfig& outConfig); - void set_configuration(PyObject* inDict, mvTreeNodeConfig& outConfig); - void set_configuration(PyObject* inDict, mvTabBarConfig& outConfig); - void set_configuration(PyObject* inDict, mvCollapsingHeaderConfig& outConfig); - void set_configuration(PyObject* inDict, mvAppItem& item, mvWindowAppItemConfig& outConfig); - - // positional args TODO: combine with above - //void set_required_configuration(PyObject* inDict, mvMenuConfig& outConfig); - - // positional args TODO: combine with above - //void set_positional_configuration(PyObject* inDict, mvMenuConfig& outConfig); - - // data source handling - void set_data_source(mvAppItem& item, mvUUID dataSource, mvMenuConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvTabConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvTreeNodeConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvTabBarConfig& outConfig); - void set_data_source(mvAppItem& item, mvUUID dataSource, mvCollapsingHeaderConfig& outConfig); - - // draw commands - void draw_menu(ImDrawList* drawlist, mvAppItem& item, mvMenuConfig& config); - void draw_tab(ImDrawList* drawlist, mvAppItem& item, mvTabConfig& config); - void draw_child_window(ImDrawList* drawlist, mvAppItem& item, mvChildWindowConfig& config); - void draw_group(ImDrawList* drawlist, mvAppItem& item, mvGroupConfig& config); - void draw_drag_payload(ImDrawList* drawlist, mvAppItem& item, mvDragPayloadConfig& config); - void draw_tree_node(ImDrawList* drawlist, mvAppItem& item, mvTreeNodeConfig& config); - void draw_tab_bar(ImDrawList* drawlist, mvAppItem& item, mvTabBarConfig& config); - void draw_collapsing_header(ImDrawList* drawlist, mvAppItem& item, mvCollapsingHeaderConfig& config); - void draw_window(ImDrawList* drawlist, mvAppItem& item, mvWindowAppItemConfig& config); -} - -struct mvMenuConfig -{ - std::shared_ptr value = std::make_shared(false); - bool _disabled_value = false; -}; - -struct mvTabConfig -{ - std::shared_ptr value = std::make_shared(false); - bool closable = false; - bool _disabled_value = false; - ImGuiTabItemFlags _flags = ImGuiTabItemFlags_None; -}; - -enum class TabOrdering { - mvTabOrder_Reorderable = 0L, - mvTabOrder_Fixed, - mvTabOrder_Leading, - mvTabOrder_Trailing -}; - -struct mvChildWindowConfig -{ - ImGuiChildFlags childFlags = ImGuiChildFlags_Borders|ImGuiChildFlags_NavFlattened; - bool autosize_x = false; - bool autosize_y = false; - ImGuiWindowFlags windowflags = ImGuiWindowFlags_NoSavedSettings; -}; - -struct mvTreeNodeConfig -{ - std::shared_ptr value = std::make_shared(false); - bool disabled_value = false; - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_None; - bool selectable = false; -}; - -struct mvGroupConfig -{ - bool horizontal = false; - float hspacing = -1.0f; - float xoffset = 0.0f; -}; - -struct mvDragPayloadConfig -{ - std::string payloadType = "$$DPG_PAYLOAD"; - std::shared_ptr dragData = std::make_shared(nullptr); - std::shared_ptr dropData = std::make_shared(nullptr); -}; - -struct mvCollapsingHeaderConfig -{ - std::shared_ptr value = std::make_shared(false); - bool disabled_value = false; - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_None; - bool closable = false; -}; - -struct mvTabBarConfig -{ - std::shared_ptr value = std::make_shared(0); - mvUUID disabled_value = 0; - ImGuiTabBarFlags flags = ImGuiTabBarFlags_None; - mvUUID uiValue = 0; // value suggested from UI - mvUUID _lastValue = 0; -}; - -struct mvWindowAppItemConfig -{ - ImGuiWindowFlags windowflags = ImGuiWindowFlags_None; - bool mainWindow = false; - bool resized = false; - bool modal = false; - bool popup = false; - bool no_close = false; - bool collapsed = false; - bool no_open_over_existing_popup = true; - bool copy_contents_shortcut = false; - mvPyObject on_close = nullptr; - mvVec2 min_size = { 100.0f, 100.0f }; - mvVec2 max_size = { 30000.0f, 30000.0f }; - bool _collapsedDirty = true; - float _oldxpos = 200; - float _oldypos = 200; - int _oldWidth = 200; - int _oldHeight = 200; -}; - -//----------------------------------------------------------------------------- -// Old Classes, in the process of removing OOP crap -//----------------------------------------------------------------------------- - -class mvMenu : public mvAppItem -{ -public: - mvMenuConfig configData{}; - explicit mvMenu(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_menu(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData, *this); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict, *this); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, uuid, configData);} - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override {*configData.value = ToBool(value);} -}; - -class mvTab : public mvAppItem -{ -public: - mvTabConfig configData{}; - explicit mvTab(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_tab(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, uuid, configData); } - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } -}; - -class mvChildWindow : public mvAppItem -{ -public: - mvChildWindowConfig configData{}; - explicit mvChildWindow(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_child_window(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvGroup : public mvAppItem -{ -public: - mvGroupConfig configData{}; - explicit mvGroup(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_group(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvDragPayload : public mvAppItem -{ - -public: - mvDragPayloadConfig configData{}; - explicit mvDragPayload(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_drag_payload(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; - -class mvTreeNode : public mvAppItem -{ -public: - mvTreeNodeConfig configData{}; - explicit mvTreeNode(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_tree_node(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, uuid, configData); } - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } -}; - -class mvTabBar : public mvAppItem -{ -public: - mvTabBarConfig configData{}; - explicit mvTabBar(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_tab_bar(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, uuid, configData); } - PyObject* getPyValue() override{ return PyUUIDFromItem(*configData.value); } - void setPyValue(PyObject* value) override{ *configData.value = ToUUID(value); } - mvUUID getSpecificValue() { return configData.uiValue; } - void setValue(mvUUID value) { configData.uiValue = value; } -}; - -class mvCollapsingHeader : public mvAppItem -{ -public: - mvCollapsingHeaderConfig configData{}; - explicit mvCollapsingHeader(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_collapsing_header(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } - void setDataSource(mvUUID dataSource) override { DearPyGui::set_data_source(*this, uuid, configData); } - PyObject* getPyValue() override { return ToPyBool(*configData.value); } - void setPyValue(PyObject* value) override { *configData.value = ToBool(value); } -}; - -class mvWindowAppItem : public mvAppItem -{ -public: - mvWindowAppItemConfig configData{}; - explicit mvWindowAppItem(mvUUID uuid) : mvAppItem(uuid) { config.width = config.height = 500; info.dirty_size = true; } - void draw(ImDrawList* drawlist, float x, float y) override { DearPyGui::draw_window(drawlist, *this, configData); } - void handleSpecificKeywordArgs(PyObject* dict) override { DearPyGui::set_configuration(dict, *this, configData); } - void getSpecificConfiguration(PyObject* dict) override { DearPyGui::fill_configuration_dict(configData, dict); } -}; \ No newline at end of file diff --git a/src/mvContext.cpp b/src/mvContext.cpp deleted file mode 100644 index 4f8de0808..000000000 --- a/src/mvContext.cpp +++ /dev/null @@ -1,447 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvContext.h" - -#include "dearpygui.h" -#include "mvViewport.h" -#include "mvCallbackRegistry.h" -#include "mvProfiler.h" -#include "mvFontManager.h" -#include "mvCallbackRegistry.h" -#include "mvToolManager.h" -#include "mvCustomTypes.h" -#include "mvItemRegistry.h" - -#include -#include -#include -#include -#include -#include -#include - -mvContext* GContext = nullptr; - -static void -UpdateInputs(mvInput& input) -{ - - MV_PROFILE_SCOPE("Input Routing") - - // update mouse - // mouse move event - ImVec2 mousepos = ImGui::GetMousePos(); - if (ImGui::IsMousePosValid(&mousepos)) - { - if (input.mouseGlobalPos.x != mousepos.x || input.mouseGlobalPos.y != mousepos.y) - { - input.mouseGlobalPos.x = (i32)mousepos.x; - input.mouseGlobalPos.y = (i32)mousepos.y; - } - } - - // route mouse wheel event - if (ImGui::GetIO().MouseWheel != 0.0f) - input.mousewheel = (i32)ImGui::GetIO().MouseWheel; - - // route mouse dragging event - for (i32 i = 0; i < 3; i++) - { - input.mouseDragging[i] = ImGui::IsMouseDragging(i, (f32)input.mouseDragThreshold); - - if (ImGui::IsMouseDragging(i, (f32)input.mouseDragThreshold)) - { - input.mouseDragDelta.x = (i32)ImGui::GetMouseDragDelta().x; - input.mouseDragDelta.y = (i32)ImGui::GetMouseDragDelta().y; - break; - } - - } - - // route other mouse events (note mouse move callbacks are handled in mvWindowAppItem) - for (i32 i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - input.mousedown[i] = ImGui::GetIO().MouseDown[i]; - - // route mouse down event - if (ImGui::GetIO().MouseDownDuration[i] >= 0.0f) - input.mousedownduration[i] = (i32)(ImGui::GetIO().MouseDownDuration[i] * 100.0); - else - input.mousedownduration[i] = 0; - } -} - -mvUUID -GenerateUUID() -{ - return ++GContext->id; -} - -void -SetDefaultTheme() -{ - ImGuiStyle* style = &ImGui::GetStyle(); - ImVec4* colors = style->Colors; - - colors[ImGuiCol_Text] = MV_BASE_COL_textColor; - colors[ImGuiCol_TextDisabled] = MV_BASE_COL_textDisabledColor; - colors[ImGuiCol_WindowBg] = mvImGuiCol_WindowBg; - colors[ImGuiCol_ChildBg] = mvImGuiCol_ChildBg; - colors[ImGuiCol_PopupBg] = mvImGuiCol_PopupBg; - colors[ImGuiCol_Border] = mvImGuiCol_Border; - colors[ImGuiCol_BorderShadow] = mvImGuiCol_BorderShadow; - colors[ImGuiCol_FrameBg] = mvImGuiCol_FrameBg; - colors[ImGuiCol_FrameBgHovered] = mvImGuiCol_FrameBgHovered; - colors[ImGuiCol_FrameBgActive] = mvImGuiCol_FrameBgActive; - colors[ImGuiCol_TitleBg] = mvImGuiCol_TitleBg; - colors[ImGuiCol_TitleBgActive] = mvImGuiCol_TitleBgActive; - colors[ImGuiCol_TitleBgCollapsed] = mvImGuiCol_TitleBgCollapsed; - colors[ImGuiCol_MenuBarBg] = mvImGuiCol_MenuBarBg; - colors[ImGuiCol_ScrollbarBg] = mvImGuiCol_ScrollbarBg; - colors[ImGuiCol_ScrollbarGrab] = mvImGuiCol_ScrollbarGrab; - colors[ImGuiCol_ScrollbarGrabHovered] = mvImGuiCol_ScrollbarGrabHovered; - colors[ImGuiCol_ScrollbarGrabActive] = mvImGuiCol_ScrollbarGrabActive; - colors[ImGuiCol_CheckMark] = mvImGuiCol_CheckMark; - colors[ImGuiCol_SliderGrab] = mvImGuiCol_SliderGrab; - colors[ImGuiCol_SliderGrabActive] = mvImGuiCol_SliderGrabActive; - colors[ImGuiCol_Button] = mvImGuiCol_Button; - colors[ImGuiCol_ButtonHovered] = mvImGuiCol_ButtonHovered; - colors[ImGuiCol_ButtonActive] = mvImGuiCol_ButtonActive; - colors[ImGuiCol_Header] = mvImGuiCol_Header; - colors[ImGuiCol_HeaderHovered] = mvImGuiCol_HeaderHovered; - colors[ImGuiCol_HeaderActive] = mvImGuiCol_HeaderActive; - colors[ImGuiCol_Separator] = mvImGuiCol_Separator; - colors[ImGuiCol_SeparatorHovered] = mvImGuiCol_SeparatorHovered; - colors[ImGuiCol_SeparatorActive] = mvImGuiCol_SeparatorActive; - colors[ImGuiCol_ResizeGrip] = mvImGuiCol_ResizeGrip; - colors[ImGuiCol_ResizeGripHovered] = mvImGuiCol_ResizeGripHovered; - colors[ImGuiCol_ResizeGripActive] = mvImGuiCol_ResizeGripHovered; - colors[ImGuiCol_InputTextCursor] = MV_BASE_COL_textColor; - colors[ImGuiCol_Tab] = mvImGuiCol_Tab; - colors[ImGuiCol_TabHovered] = mvImGuiCol_TabHovered; - colors[ImGuiCol_TabSelected] = mvImGuiCol_TabActive; - colors[ImGuiCol_TabSelectedOverline] = mvImGuiCol_HeaderActive; - colors[ImGuiCol_TabDimmed] = mvImGuiCol_TabUnfocused; - colors[ImGuiCol_TabDimmedSelected] = mvImGuiCol_TabUnfocusedActive; - colors[ImGuiCol_TabDimmedSelectedOverline] = mvImGuiCol_TabUnfocusedActiveOverline; - colors[ImGuiCol_DockingPreview] = mvImGuiCol_DockingPreview; - colors[ImGuiCol_DockingEmptyBg] = mvImGuiCol_DockingEmptyBg; - colors[ImGuiCol_PlotLines] = mvImGuiCol_PlotLines; - colors[ImGuiCol_PlotLinesHovered] = mvImGuiCol_PlotLinesHovered; - colors[ImGuiCol_PlotHistogram] = mvImGuiCol_PlotHistogram; - colors[ImGuiCol_PlotHistogramHovered] = mvImGuiCol_PlotHistogramHovered; - colors[ImGuiCol_TableHeaderBg] = mvImGuiCol_TableHeaderBg; - colors[ImGuiCol_TableBorderStrong] = mvImGuiCol_TableBorderStrong; // Prefer using Alpha=1.0 here - colors[ImGuiCol_TableBorderLight] = mvImGuiCol_TableBorderLight; // Prefer using Alpha=1.0 here - colors[ImGuiCol_TableRowBg] = mvImGuiCol_TableRowBg; - colors[ImGuiCol_TableRowBgAlt] = mvImGuiCol_TableRowBgAlt; - colors[ImGuiCol_TextLink] = mvImGuiCol_HeaderActive; - colors[ImGuiCol_TextSelectedBg] = mvImGuiCol_TextSelectedBg; - colors[ImGuiCol_TreeLines] = mvImGuiCol_Border; - colors[ImGuiCol_DragDropTarget] = mvImGuiCol_DragDropTarget; - colors[ImGuiCol_DragDropTargetBg] = mvImGuiCol_DragDropTargetBg; - colors[ImGuiCol_UnsavedMarker] = mvImGuiCol_Text; - colors[ImGuiCol_NavCursor] = mvImGuiCol_NavHighlight; - colors[ImGuiCol_NavWindowingHighlight] = mvImGuiCol_NavWindowingHighlight; - colors[ImGuiCol_NavWindowingDimBg] = mvImGuiCol_NavWindowingDimBg; - colors[ImGuiCol_ModalWindowDimBg] = mvImGuiCol_ModalWindowDimBg; - - ImNodes::GetStyle().Colors[ImNodesCol_NodeBackground] = mvColor::ConvertToUnsignedInt(mvColor(62, 62, 62, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_NodeBackgroundHovered] = mvColor::ConvertToUnsignedInt(mvColor(75, 75, 75, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_NodeBackgroundSelected] = mvColor::ConvertToUnsignedInt(mvColor(75, 75, 75, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_NodeOutline] = mvColor::ConvertToUnsignedInt(mvColor(100, 100, 100, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_TitleBar] = mvColor::ConvertToUnsignedInt(mvImGuiCol_TitleBg); - ImNodes::GetStyle().Colors[ImNodesCol_TitleBarHovered] = mvColor::ConvertToUnsignedInt(mvImGuiCol_TitleBgActive); - ImNodes::GetStyle().Colors[ImNodesCol_TitleBarSelected] = mvColor::ConvertToUnsignedInt(mvImGuiCol_FrameBgActive); - ImNodes::GetStyle().Colors[ImNodesCol_Link] = mvColor::ConvertToUnsignedInt(mvColor(255, 255, 255, 200)); - ImNodes::GetStyle().Colors[ImNodesCol_LinkHovered] = mvColor::ConvertToUnsignedInt(mvColor(66, 150, 250, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_LinkSelected] = mvColor::ConvertToUnsignedInt(mvColor(66, 150, 250, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_Pin] = mvColor::ConvertToUnsignedInt(mvColor(199, 199, 41, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_PinHovered] = mvColor::ConvertToUnsignedInt(mvColor(255, 255, 50, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_BoxSelector] = mvColor::ConvertToUnsignedInt(mvColor(61, 133, 224, 30)); - ImNodes::GetStyle().Colors[ImNodesCol_BoxSelectorOutline] = mvColor::ConvertToUnsignedInt(mvColor(61, 133, 224, 150)); - ImNodes::GetStyle().Colors[ImNodesCol_GridBackground] = mvColor::ConvertToUnsignedInt(mvColor(35, 35, 35, 255)); - ImNodes::GetStyle().Colors[ImNodesCol_GridLine] = mvColor::ConvertToUnsignedInt(mvColor(0, 0, 0, 255)); - -} - -void -Render() -{ - // We lock the mutex from the very start so that frame count is kept valid - // for API calls. - std::lock_guard lk(GContext->mutex); - - // update timing - GContext->deltaTime = ImGui::GetIO().DeltaTime; - GContext->time = ImGui::GetTime(); - GContext->frame = ImGui::GetFrameCount(); - GContext->framerate = (i32)ImGui::GetIO().Framerate; - - mvRunTasks(true); // this call runs early tasks only - - ImGuiStyle& style = ImGui::GetStyle(); - style.FontScaleMain = mvToolManager::GetFontManager().getGlobalFontScale(); - - if (GContext->IO.dockingViewport) - ImGui::DockSpaceOverViewport(); - - mvFrameCallback(ImGui::GetFrameCount()); - - // route input callbacks - UpdateInputs(GContext->input); - - mvToolManager::Draw(); - - if (GContext->resetTheme) - { - SetDefaultTheme(); - GContext->resetTheme = false; - } - - mvRunTasks(); - RenderItemRegistry(*GContext->itemRegistry); - mvRunTasks(); - - // release split_frame if it's waiting for the frame end - { - std::lock_guard lk(GContext->frameEndedMutex); - GContext->frameEnded = true; - } - GContext->frameEndedEvent.notify_all(); -} - -std::map& -GetParsers() -{ - return const_cast&>(GetModuleParsers()); -} - -void StopRendering() -{ - // While it may seem reasonable to set it to false with frameEndedMutex locked - // (to set it simultaneously with frameEnded), we don't want to spur another - // race condition between split_frame() and is_dearpygui_running() in the - // rendering loop. Let's trigger it as early as possible. - GContext->running = false; - - // Unblock handlers (or other code) that might be waiting in `split_frame()` - { - std::lock_guard lk(GContext->frameEndedMutex); - // Simulate an end of frame even though there's no real frame this time. - // Otherwise split_frame will continue waiting. - GContext->frameEnded = true; - } - GContext->frameEndedEvent.notify_all(); -} - -void -InsertConstants_mvContext(std::vector>& constants) -{ - - //----------------------------------------------------------------------------- - // Graphics Backends - //----------------------------------------------------------------------------- - constants.emplace_back("mvGraphicsBackend_D3D11", 0); - constants.emplace_back("mvGraphicsBackend_D3D12", 1); - constants.emplace_back("mvGraphicsBackend_VULKAN", 2); - constants.emplace_back("mvGraphicsBackend_METAL", 3); - constants.emplace_back("mvGraphicsBackend_OPENGL", 4); - - //----------------------------------------------------------------------------- - // Mouse Codes - //----------------------------------------------------------------------------- - constants.emplace_back("mvMouseButton_Left", ImGuiMouseButton_Left); - constants.emplace_back("mvMouseButton_Right", ImGuiMouseButton_Right); - constants.emplace_back("mvMouseButton_Middle", ImGuiMouseButton_Middle); - constants.emplace_back("mvMouseButton_X1", 3); // ImGuiKey_MouseX1 - constants.emplace_back("mvMouseButton_X2", 4); // ImGuiKey_MouseX2 - - //----------------------------------------------------------------------------- - // Key Codes - //----------------------------------------------------------------------------- - constants.emplace_back("mvKey_ModDisabled", -1); - constants.emplace_back("mvKey_None", ImGuiKey_None); - constants.emplace_back("mvKey_0", ImGuiKey_0); - constants.emplace_back("mvKey_1", ImGuiKey_1); - constants.emplace_back("mvKey_2", ImGuiKey_2); - constants.emplace_back("mvKey_3", ImGuiKey_3); - constants.emplace_back("mvKey_4", ImGuiKey_4); - constants.emplace_back("mvKey_5", ImGuiKey_5); - constants.emplace_back("mvKey_6", ImGuiKey_6); - constants.emplace_back("mvKey_7", ImGuiKey_7); - constants.emplace_back("mvKey_8", ImGuiKey_8); - constants.emplace_back("mvKey_9", ImGuiKey_9); - constants.emplace_back("mvKey_A", ImGuiKey_A); - constants.emplace_back("mvKey_B", ImGuiKey_B); - constants.emplace_back("mvKey_C", ImGuiKey_C); - constants.emplace_back("mvKey_D", ImGuiKey_D); - constants.emplace_back("mvKey_E", ImGuiKey_E); - constants.emplace_back("mvKey_F", ImGuiKey_F); - constants.emplace_back("mvKey_G", ImGuiKey_G); - constants.emplace_back("mvKey_H", ImGuiKey_H); - constants.emplace_back("mvKey_I", ImGuiKey_I); - constants.emplace_back("mvKey_J", ImGuiKey_J); - constants.emplace_back("mvKey_K", ImGuiKey_K); - constants.emplace_back("mvKey_L", ImGuiKey_L); - constants.emplace_back("mvKey_M", ImGuiKey_M); - constants.emplace_back("mvKey_N", ImGuiKey_N); - constants.emplace_back("mvKey_O", ImGuiKey_O); - constants.emplace_back("mvKey_P", ImGuiKey_P); - constants.emplace_back("mvKey_Q", ImGuiKey_Q); - constants.emplace_back("mvKey_R", ImGuiKey_R); - constants.emplace_back("mvKey_S", ImGuiKey_S); - constants.emplace_back("mvKey_T", ImGuiKey_T); - constants.emplace_back("mvKey_U", ImGuiKey_U); - constants.emplace_back("mvKey_V", ImGuiKey_V); - constants.emplace_back("mvKey_W", ImGuiKey_W); - constants.emplace_back("mvKey_X", ImGuiKey_X); - constants.emplace_back("mvKey_Y", ImGuiKey_Y); - constants.emplace_back("mvKey_Z", ImGuiKey_Z); - - constants.emplace_back("mvKey_Back", ImGuiKey_Backspace); - constants.emplace_back("mvKey_Tab", ImGuiKey_Tab); - constants.emplace_back("mvKey_Return", ImGuiKey_Enter); - constants.emplace_back("mvKey_LShift", ImGuiKey_LeftShift); - constants.emplace_back("mvKey_RShift", ImGuiKey_RightShift); - constants.emplace_back("mvKey_LControl", ImGuiKey_LeftCtrl); - constants.emplace_back("mvKey_RControl", ImGuiKey_RightCtrl); - constants.emplace_back("mvKey_LAlt", ImGuiKey_LeftAlt); - constants.emplace_back("mvKey_RAlt", ImGuiKey_RightAlt); - constants.emplace_back("mvKey_Pause", ImGuiKey_Pause); - constants.emplace_back("mvKey_CapsLock", ImGuiKey_CapsLock); - constants.emplace_back("mvKey_Escape", ImGuiKey_Escape); - constants.emplace_back("mvKey_Spacebar", ImGuiKey_Space); - constants.emplace_back("mvKey_End", ImGuiKey_End); - constants.emplace_back("mvKey_Home", ImGuiKey_Home); - constants.emplace_back("mvKey_Left", ImGuiKey_LeftArrow); - constants.emplace_back("mvKey_Up", ImGuiKey_UpArrow); - constants.emplace_back("mvKey_Right", ImGuiKey_RightArrow); - constants.emplace_back("mvKey_Down", ImGuiKey_DownArrow); - constants.emplace_back("mvKey_Print", ImGuiKey_PrintScreen); - constants.emplace_back("mvKey_Insert", ImGuiKey_Insert); - constants.emplace_back("mvKey_Delete", ImGuiKey_Delete); - constants.emplace_back("mvKey_NumPad0", ImGuiKey_Keypad0); - constants.emplace_back("mvKey_NumPad1", ImGuiKey_Keypad1); - constants.emplace_back("mvKey_NumPad2", ImGuiKey_Keypad2); - constants.emplace_back("mvKey_NumPad3", ImGuiKey_Keypad3); - constants.emplace_back("mvKey_NumPad4", ImGuiKey_Keypad4); - constants.emplace_back("mvKey_NumPad5", ImGuiKey_Keypad5); - constants.emplace_back("mvKey_NumPad6", ImGuiKey_Keypad6); - constants.emplace_back("mvKey_NumPad7", ImGuiKey_Keypad7); - constants.emplace_back("mvKey_NumPad8", ImGuiKey_Keypad8); - constants.emplace_back("mvKey_NumPad9", ImGuiKey_Keypad9); - constants.emplace_back("mvKey_NumPadEnter", ImGuiKey_KeypadEnter); - constants.emplace_back("mvKey_NumPadEqual", ImGuiKey_KeypadEqual); - constants.emplace_back("mvKey_Subtract", ImGuiKey_KeypadSubtract); - constants.emplace_back("mvKey_Decimal", ImGuiKey_KeypadDecimal); - constants.emplace_back("mvKey_Divide", ImGuiKey_KeypadDivide); - constants.emplace_back("mvKey_Multiply", ImGuiKey_KeypadMultiply); - constants.emplace_back("mvKey_Add", ImGuiKey_KeypadAdd); - constants.emplace_back("mvKey_F1", ImGuiKey_F1); - constants.emplace_back("mvKey_F2", ImGuiKey_F2); - constants.emplace_back("mvKey_F3", ImGuiKey_F3); - constants.emplace_back("mvKey_F4", ImGuiKey_F4); - constants.emplace_back("mvKey_F5", ImGuiKey_F5); - constants.emplace_back("mvKey_F6", ImGuiKey_F6); - constants.emplace_back("mvKey_F7", ImGuiKey_F7); - constants.emplace_back("mvKey_F8", ImGuiKey_F8); - constants.emplace_back("mvKey_F9", ImGuiKey_F9); - constants.emplace_back("mvKey_F10", ImGuiKey_F10); - constants.emplace_back("mvKey_F11", ImGuiKey_F11); - constants.emplace_back("mvKey_F12", ImGuiKey_F12); - constants.emplace_back("mvKey_F13", ImGuiKey_F13); - constants.emplace_back("mvKey_F14", ImGuiKey_F14); - constants.emplace_back("mvKey_F15", ImGuiKey_F15); - constants.emplace_back("mvKey_F16", ImGuiKey_F16); - constants.emplace_back("mvKey_F17", ImGuiKey_F17); - constants.emplace_back("mvKey_F18", ImGuiKey_F18); - constants.emplace_back("mvKey_F19", ImGuiKey_F19); - constants.emplace_back("mvKey_F20", ImGuiKey_F20); - constants.emplace_back("mvKey_F21", ImGuiKey_F21); - constants.emplace_back("mvKey_F22", ImGuiKey_F22); - constants.emplace_back("mvKey_F23", ImGuiKey_F23); - constants.emplace_back("mvKey_F24", ImGuiKey_F24); - constants.emplace_back("mvKey_NumLock", ImGuiKey_NumLock); - constants.emplace_back("mvKey_ScrollLock", ImGuiKey_ScrollLock); - constants.emplace_back("mvKey_Period", ImGuiKey_Period); - constants.emplace_back("mvKey_Slash", ImGuiKey_Slash); - constants.emplace_back("mvKey_Backslash", ImGuiKey_Backslash); - constants.emplace_back("mvKey_Open_Brace", ImGuiKey_LeftBracket); - constants.emplace_back("mvKey_Close_Brace", ImGuiKey_RightBracket); - constants.emplace_back("mvKey_Browser_Back", ImGuiKey_AppBack); - constants.emplace_back("mvKey_Browser_Forward", ImGuiKey_AppForward); - constants.emplace_back("mvKey_Comma", ImGuiKey_Comma); // -> it seems to be the old mvKey_Separator - constants.emplace_back("mvKey_Minus", ImGuiKey_Minus); - constants.emplace_back("mvKey_Menu", ImGuiKey_Menu); - constants.emplace_back("mvKey_ModSuper", ImGuiMod_Super); // Cmd/Super/Windows - constants.emplace_back("mvKey_ModShift", ImGuiMod_Shift); - constants.emplace_back("mvKey_ModAlt", ImGuiMod_Alt); - constants.emplace_back("mvKey_ModCtrl", ImGuiMod_Ctrl); - #if defined (_WIN32) - constants.emplace_back("mvKey_Clear", 0x0C); - constants.emplace_back("mvKey_Prior", 0x21); - constants.emplace_back("mvKey_Next", 0x22); - constants.emplace_back("mvKey_Select", 0x29); - constants.emplace_back("mvKey_Execute", 0x2B); - constants.emplace_back("mvKey_LWin", 0x5B); - constants.emplace_back("mvKey_RWin", 0x5C); - constants.emplace_back("mvKey_Apps", 0x5D); - constants.emplace_back("mvKey_Sleep", 0x5F); - constants.emplace_back("mvKey_Help", 0x2F); - constants.emplace_back("mvKey_Browser_Refresh", 0xA8); - constants.emplace_back("mvKey_Browser_Stop", 0xA9); - constants.emplace_back("mvKey_Browser_Search", 0xAA); - constants.emplace_back("mvKey_Browser_Favorites", 0xAB); - constants.emplace_back("mvKey_Browser_Home", 0xAC); - constants.emplace_back("mvKey_Volume_Mute", 0xAD); - constants.emplace_back("mvKey_Volume_Down", 0xAE); - constants.emplace_back("mvKey_Volume_Up", 0xAF); - constants.emplace_back("mvKey_Media_Next_Track", 0xB0); - constants.emplace_back("mvKey_Media_Prev_Track", 0xB1); - constants.emplace_back("mvKey_Media_Stop", 0xB2); - constants.emplace_back("mvKey_Media_Play_Pause", 0xB3); - constants.emplace_back("mvKey_Launch_Mail", 0xB4); - constants.emplace_back("mvKey_Launch_Media_Select", 0xB5); - constants.emplace_back("mvKey_Launch_App1", 0xB6); - constants.emplace_back("mvKey_Launch_App2", 0xB7); - constants.emplace_back("mvKey_Colon", 0xBA); - constants.emplace_back("mvKey_Plus", 0xBB); - constants.emplace_back("mvKey_Tilde", 0xC0); - constants.emplace_back("mvKey_Quote", 0xDE); - constants.emplace_back("mvKey_F25", 0x88); - #else - constants.emplace_back("mvKey_Clear", 259); - constants.emplace_back("mvKey_Prior", 266); - constants.emplace_back("mvKey_Next", 267); - constants.emplace_back("mvKey_Select", -1); - constants.emplace_back("mvKey_Execute", -1); - constants.emplace_back("mvKey_LWin", 343); - constants.emplace_back("mvKey_RWin", 347); - constants.emplace_back("mvKey_Apps", -1); - constants.emplace_back("mvKey_Sleep", -1); - constants.emplace_back("mvKey_Help", -1); - constants.emplace_back("mvKey_Browser_Refresh", -1); - constants.emplace_back("mvKey_Browser_Stop", -1); - constants.emplace_back("mvKey_Browser_Search", -1); - constants.emplace_back("mvKey_Browser_Favorites", -1); - constants.emplace_back("mvKey_Browser_Home", -1); - constants.emplace_back("mvKey_Volume_Mute", -1); - constants.emplace_back("mvKey_Volume_Down", -1); - constants.emplace_back("mvKey_Volume_Up", -1); - constants.emplace_back("mvKey_Media_Next_Track", -1); - constants.emplace_back("mvKey_Media_Prev_Track", -1); - constants.emplace_back("mvKey_Media_Stop", -1); - constants.emplace_back("mvKey_Media_Play_Pause", -1); - constants.emplace_back("mvKey_Launch_Mail", -1); - constants.emplace_back("mvKey_Launch_Media_Select", -1); - constants.emplace_back("mvKey_Launch_App1", -1); - constants.emplace_back("mvKey_Launch_App2", -1); - constants.emplace_back("mvKey_Colon", 59); - constants.emplace_back("mvKey_Plus", 61); - constants.emplace_back("mvKey_Tilde", 96); - constants.emplace_back("mvKey_Quote", 39); - constants.emplace_back("mvKey_F25", 314); - #endif -} diff --git a/src/mvContext.h b/src/mvContext.h deleted file mode 100644 index 14333b6ea..000000000 --- a/src/mvContext.h +++ /dev/null @@ -1,135 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include "mvCore.h" -#include "mvPyUtils.h" -#include "mvTypes.h" -#include "mvGraphics.h" - -//----------------------------------------------------------------------------- -// forward declarations -//----------------------------------------------------------------------------- -struct mvViewport; -struct mvCallbackRegistry; -struct mvItemRegistry; -struct mvIO; -struct mvContext; -struct mvInput; - -//----------------------------------------------------------------------------- -// public API -//----------------------------------------------------------------------------- - -extern mvContext* GContext; - -mvUUID GenerateUUID(); -void SetDefaultTheme(); -void Render(); -std::map& GetParsers(); -// Signals the rendering loop via GContext->running to quit. -void StopRendering(); - -struct mvInput -{ - struct AtomicVec2 - { - std::atomic_int x; - std::atomic_int y; - }; - - struct AtomicFloatVec2 - { - std::atomic x; - std::atomic y; - }; - - AtomicVec2 mousePos = { 0, 0 }; - AtomicVec2 mouseGlobalPos = { 0, 0 }; - AtomicFloatVec2 mousePlotPos = { 0, 0 }; - AtomicVec2 mouseDrawingPos = { 0, 0 }; - std::atomic_int mouseDragThreshold = 20; - AtomicVec2 mouseDragDelta = { 0, 0 }; - - // mouse - std::atomic_int mousewheel; - std::atomic_bool mousedown[5]; - std::atomic_bool mouseDragging[5]; - std::atomic_int mousedownduration[5]; // 1/100 seconds - std::atomic_bool mouseclick[5]; - std::atomic_bool mousedoubleclick[5]; - std::atomic_bool mousereleased[5]; -}; - -struct mvIO -{ - - bool docking = false; - bool dockingViewport = false; - bool dockingShiftOnly = false; - - bool kbdNavigation = false; - - std::string iniFile; - bool loadIniFile = false; - bool autoSaveIniFile = false; - bool waitForInput = false; - - // GPU selection - bool info_auto_device = false; - int info_device = -1; - std::string info_device_name; - - // item registry - bool allowAliasOverwrites = false; - bool manualAliasManagement = false; - bool skipRequiredArgs = false; - bool skipPositionalArgs = false; - bool skipKeywordArgs = false; - - // callback registry - bool manualCallbacks = false; - - bool altEnterFullscreen = false; - - ImWchar decimalPoint = '.'; -}; - -struct mvContext -{ - std::mutex frameEndedMutex; - std::condition_variable frameEndedEvent; - bool frameEnded = false; - // Indicates whether DPG has started at least once in this context, i.e. whether - // associated Dear ImGui contexts exist and can be read from. - std::atomic_bool started = false; - // If true, more frames are going to be rendered. Goes back to false on shutdown. - std::atomic_bool running = false; - std::recursive_mutex mutex; - std::future future; - float deltaTime = 0.0f; // time since last frame - double time = 0.0; // total time since starting - int frame = 0; // frame count - int framerate = 0; // frame rate - std::atomic id = MV_START_UUID; // current ID - mvViewport* viewport = nullptr; - mvGraphics graphics; - bool resetTheme = false; - mvIO IO; - mvItemRegistry* itemRegistry = nullptr; - mvCallbackRegistry* callbackRegistry = nullptr; - mvInput input; - mvUUID activeWindow = 0; - mvUUID focusedItem = 0; - -}; - -//----------------------------------------------------------------------------- -// Python Parsing -//----------------------------------------------------------------------------- - -void InsertConstants_mvContext(std::vector>& constants); \ No newline at end of file diff --git a/src/mvCore.h b/src/mvCore.h deleted file mode 100644 index d1473ba87..000000000 --- a/src/mvCore.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -#include "mvMath.h" - -//----------------------------------------------------------------------------- -// mvColor -//----------------------------------------------------------------------------- -struct mvColor -{ - static unsigned int ConvertToUnsignedInt(const mvColor& color) - { - return ImGui::ColorConvertFloat4ToU32(color.toVec4()); - } - - float r = -1.0f, g = -1.0f, b = -1.0f, a = -1.0f; - - mvColor() = default; - - mvColor(float r, float g, float b, float a) - : r(r), g(g), b(b), a(a) - { - } - - mvColor(int r, int g, int b, int a) - : r(r/255.0f), g(g/255.0f), b(b/255.0f), a(a/255.0f) - { - } - - explicit mvColor(ImVec4 color) - { - r = color.x; - g = color.y; - b = color.z; - a = color.w; - } - - operator ImU32() const - { - return ImGui::ColorConvertFloat4ToU32(toVec4()); - } - - operator float* () - { - return &r; - } - - operator ImVec4() const - { - return { r, g, b, a }; - } - - operator ImVec4*() - { - return (ImVec4*)&r; - } - - const ImVec4 toVec4() const - { - return { r, g, b, a }; - } - -}; - -#define MV_DEFAULT_COLOR mvColor(1.0f, 1.0f, 1.0f, 1.0f) - -// UUIDs (+ reserved uuids) -#define MV_INVALID_UUID 0 -#define MV_APP_UUID 1 -#define MV_ATLAS_UUID 2 -#define MV_TOOL_ABOUT_UUID 3 -#define MV_TOOL_DEBUG_UUID 4 -#define MV_TOOL_DOC_UUID 5 -#define MV_TOOL_ITEM_REGISTRY_UUID 6 -#define MV_TOOL_METRICS_UUID 7 -#define MV_TOOL_STYLE_UUID 8 -#define MV_TOOL_FONT_UUID 9 -#define MV_TOOL_STACK_UUID 10 -#define MV_RESERVED_UUIDs 11 -#define MV_RESERVED_UUID_start MV_TOOL_FONT_UUID+1 -#define MV_START_UUID MV_TOOL_FONT_UUID+MV_RESERVED_UUIDs+1 diff --git a/src/mvCustomTypes.cpp b/src/mvCustomTypes.cpp deleted file mode 100644 index 2f933f009..000000000 --- a/src/mvCustomTypes.cpp +++ /dev/null @@ -1,518 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvCustomTypes.h" - -#include "mvTypes.h" - -#include - -static void -intialize_mvMat4(mvMat4* a, - f32 m00, f32 m01, f32 m02, f32 m03, - f32 m10, f32 m11, f32 m12, f32 m13, - f32 m20, f32 m21, f32 m22, f32 m23, - f32 m30, f32 m31, f32 m32, f32 m33) -{ - a->cols[0][0] = m00; - a->cols[0][1] = m10; - a->cols[0][2] = m20; - a->cols[0][3] = m30; - a->cols[1][0] = m01; - a->cols[1][1] = m11; - a->cols[1][2] = m21; - a->cols[1][3] = m31; - a->cols[2][0] = m02; - a->cols[2][1] = m12; - a->cols[2][2] = m22; - a->cols[2][3] = m32; - a->cols[3][0] = m03; - a->cols[3][1] = m13; - a->cols[3][2] = m23; - a->cols[3][3] = m33; -} - -int -PymvMat4_init(PymvMat4* self, PyObject* args, PyObject* kwds) -{ - - f32 m00 = 0.0f; - f32 m01 = 0.0f; - f32 m02 = 0.0f; - f32 m03 = 0.0f; - f32 m10 = 0.0f; - f32 m11 = 0.0f; - f32 m12 = 0.0f; - f32 m13 = 0.0f; - f32 m20 = 0.0f; - f32 m21 = 0.0f; - f32 m22 = 0.0f; - f32 m23 = 0.0f; - f32 m30 = 0.0f; - f32 m31 = 0.0f; - f32 m32 = 0.0f; - f32 m33 = 0.0f; - - static char km00[] = "m00"; - static char km01[] = "m01"; - static char km02[] = "m02"; - static char km03[] = "m03"; - static char km10[] = "m10"; - static char km11[] = "m11"; - static char km12[] = "m12"; - static char km13[] = "m13"; - static char km20[] = "m20"; - static char km21[] = "m21"; - static char km22[] = "m22"; - static char km23[] = "m23"; - static char km30[] = "m30"; - static char km31[] = "m31"; - static char km32[] = "m32"; - static char km33[] = "m33"; - - static char* kwlist[] = { - km00, km01, km02, km03, - km10, km11, km12, km13, - km20, km21, km22, km23, - km30, km31, km32, km33, NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ffffffffffffffff", kwlist, - &m00, &m01, &m02, &m03, - &m10, &m11, &m12, &m13, - &m20, &m21, &m22, &m23, - &m30, &m31, &m32, &m33)) - return -1; - - intialize_mvMat4(&self->m, - m00, m01, m02, m03, - m10, m11, m12, m13, - m20, m21, m22, m23, - m30, m31, m32, m33); - - return 0; -} - -void -PymvMat4_dealloc(PymvMat4* self) -{ - Py_TYPE(self)->tp_free((PyObject*)self); -} - -PyObject* -PymvMat4_str(PymvMat4* self) -{ - std::string result; - - for (int i = 0; i < 4; i++) - { - result += "|"; - - for(int j = 0; j < 4; j++) - result += std::to_string(self->m.cols[j][i]) + "\t"; - - result += "\t|\n"; - } - - PyObject* ret = PyUnicode_FromString(result.c_str()); - - return ret; -} - -Py_ssize_t -PymvMat4_getLength(PyObject* obj) -{ - auto self = (PymvMat4*)obj; - return 16; -} - -PyObject* -PymvMat4_getItem(PyObject* obj, Py_ssize_t index) -{ - PymvMat4* self = (PymvMat4*)obj; - if(index > 15) - return Py_BuildValue("f", self->m.cols[3][3]); - - i32 column = (i32)index/4; - i32 row = (i32)index % 4; - return Py_BuildValue("f", self->m.cols[column][row]); -} - -int -PymvMat4_setItem(PyObject* obj, Py_ssize_t index, PyObject* value) -{ - PymvMat4* self = (PymvMat4*)obj; - if (index > 15) - return 0; - - i32 column = (i32)index/4; - i32 row = (i32)index % 4; - self->m.cols[column][row] = (float)PyFloat_AsDouble(value); - return 0; -} - -PyObject* -PymvMat4_add(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - PymvMat4* leftVect = (PymvMat4*)left; - PymvMat4* rightVect = (PymvMat4*)right; - - newbufferview->m = leftVect->m + rightVect->m; - - return newbuffer; -} - -PyObject* -PymvMat4_subtract(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - PymvMat4* leftVect = (PymvMat4*)left; - PymvMat4* rightVect = (PymvMat4*)right; - - newbufferview->m = leftVect->m - rightVect->m; - - return newbuffer; -} - -PyObject* -PymvMat4_multiply(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvMat4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvMat4, &PymvMat4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvMat4Type); - - PymvMat4* leftVect = (PymvMat4*)left; - PymvMat4* rightVect = (PymvMat4*)right; - - newbufferview->m = leftVect->m * rightVect->m; - - return newbuffer; -} - -static void -intialize_mvVec4(mvVec4* a, float x, float y, float z, float w) -{ - a->x = x; - a->y = y; - a->z = z; - a->w = w; -} - -int -PymvVec4_init(PymvVec4* self, PyObject* args, PyObject* kwds) -{ - - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; - float w = 0.0f; - static char kw_x[] = "x"; - static char kw_y[] = "y"; - static char kw_z[] = "z"; - static char kw_w[] = "w"; - static char* kwlist[] = { kw_x, kw_y, kw_z, kw_w, nullptr }; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ffff", kwlist, &x, &y, &z, &w)) - return -1; - - intialize_mvVec4(&self->vec4, x, y, z, w); - return 0; -} - -void -PymvVec4_dealloc(PymvVec4* self) -{ - Py_TYPE(self)->tp_free((PyObject*)self); -} - -PyObject* -PymvVec4_str(PymvVec4* self) -{ - std::string result = "[ "; - result += std::to_string(self->vec4.x) + " "; - result += std::to_string(self->vec4.y) + " "; - result += std::to_string(self->vec4.z) + " "; - result += std::to_string(self->vec4.w) + " "; - result += "]"; - - PyObject* ret = PyUnicode_FromString(result.c_str()); - - return ret; -} - -Py_ssize_t -PymvVec4_getLength(PyObject* obj) -{ - auto self = (PymvVec4*)obj; - return 4; -} - -PyObject* -PymvVec4_getItem(PyObject* obj, Py_ssize_t index) -{ - PymvVec4* self = (PymvVec4*)obj; - switch(index) - { - case 0: return Py_BuildValue("f", self->vec4.x); - case 1: return Py_BuildValue("f", self->vec4.y); - case 2: return Py_BuildValue("f", self->vec4.z); - case 3: return Py_BuildValue("f", self->vec4.w); - default: return Py_BuildValue("f", self->vec4.w); - } -} - -int -PymvVec4_setItem(PyObject* obj, Py_ssize_t index, PyObject* value) -{ - PymvVec4* self = (PymvVec4*)obj; - if (index > 3) - return 0; - f32 val = (float)PyFloat_AsDouble(value); - switch(index) - { - case 0: - self->vec4.x = val; - break; - case 1: - self->vec4.y = val; - break; - case 2: - self->vec4.z = val; - break; - case 3: - self->vec4.w = val; - break; - default: break; - } - - return 0; -} - -PyObject* -PymvVec4_add(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvVec4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvVec4, &PymvVec4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvVec4Type); - - PymvVec4* leftVect = (PymvVec4*)left; - PymvVec4* rightVect = (PymvVec4*)right; - - newbufferview->vec4.x = leftVect->vec4.x + rightVect->vec4.x; - newbufferview->vec4.y = leftVect->vec4.y + rightVect->vec4.y; - newbufferview->vec4.z = leftVect->vec4.z + rightVect->vec4.z; - newbufferview->vec4.w = leftVect->vec4.w + rightVect->vec4.w; - - return newbuffer; -} - -PyObject* -PymvVec4_subtract(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvVec4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvVec4, &PymvVec4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvVec4Type); - - PymvVec4* leftVect = (PymvVec4*)left; - PymvVec4* rightVect = (PymvVec4*)right; - - newbufferview->vec4.x = leftVect->vec4.x - rightVect->vec4.x; - newbufferview->vec4.y = leftVect->vec4.y - rightVect->vec4.y; - newbufferview->vec4.z = leftVect->vec4.z - rightVect->vec4.z; - newbufferview->vec4.w = leftVect->vec4.w - rightVect->vec4.w; - - return newbuffer; -} - -PyObject* PymvVec4_multiply(PyObject* left, PyObject* right) -{ - PyObject* newbuffer = nullptr; - PymvVec4* newbufferview = nullptr; - newbufferview = PyObject_New(PymvVec4, &PymvVec4Type); - newbuffer = PyObject_Init((PyObject*)newbufferview, &PymvVec4Type); - - //PymvVec4* leftVect = (PymvVec4*)left; - //PymvVec4* rightVect = (PymvVec4*)right; - - if (isPyObject_Float(left)) - { - float value = ToFloat(left); - PymvVec4* rightVect = (PymvVec4*)right; - - newbufferview->vec4.x = value * rightVect->vec4.x; - newbufferview->vec4.y = value * rightVect->vec4.y; - newbufferview->vec4.z = value * rightVect->vec4.z; - newbufferview->vec4.w = value * rightVect->vec4.w; - } - - else if (isPyObject_Float(right)) - { - float value = ToFloat(right); - PymvVec4* leftVect = (PymvVec4*)left; - - newbufferview->vec4.x = value * leftVect->vec4.x; - newbufferview->vec4.y = value * leftVect->vec4.y; - newbufferview->vec4.z = value * leftVect->vec4.z; - newbufferview->vec4.w = value * leftVect->vec4.w; - } - - else - { - PymvVec4* leftVect = (PymvVec4*)left; - PymvVec4* rightVect = (PymvVec4*)right; - newbufferview->vec4.x = leftVect->vec4.x * rightVect->vec4.x; - newbufferview->vec4.y = leftVect->vec4.y * rightVect->vec4.y; - newbufferview->vec4.z = leftVect->vec4.z * rightVect->vec4.z; - newbufferview->vec4.w = leftVect->vec4.w * rightVect->vec4.w; - } - - return newbuffer; -} - -static void -intialize_mvBuffer(mvBuffer* a, long length) -{ - a->length = length; - a->data = new float[length]; - for (int i = 0; i < length; i++) - a->data[i] = 1.0f; -} - -static void -deallocate_mvBuffer(mvBuffer* a) -{ - delete[] a->data; - a->data = nullptr; -} - -int -PymvBuffer_init(PymvBuffer* self, PyObject* args, PyObject* kwds) -{ - // init may have already been called - if (self->arr.data != nullptr) - deallocate_mvBuffer(&self->arr); - - int length = 0; - static char kw[] = "length"; - static char* kwlist[] = { kw, nullptr }; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, &length)) - return -1; - - if (length < 0) - length = 0; - - intialize_mvBuffer(&self->arr, length); - - return 0; -} - -PyObject* -PymvBuffer_clear_value(PymvBuffer* self, PyObject* args, PyObject* kwds) -{ - - float value = 0.0f; - if (!PyArg_ParseTuple(args, "f", &value)) - Py_RETURN_NONE; - - for (int i = 0; i < self->arr.length; i++) - self->arr.data[i] = value; - - Py_RETURN_NONE; -} - -PyObject* -PymvBuffer_get_width(PymvBuffer* self, PyObject* args, PyObject* kwds) -{ - return ToPyInt(self->arr.width); -} - -PyObject* -PymvBuffer_get_height(PymvBuffer* self, PyObject* args, PyObject* kwds) -{ - return ToPyInt(self->arr.height); -} - -void -PymvBuffer_dealloc(PymvBuffer* self) -{ - deallocate_mvBuffer(&self->arr); - Py_TYPE(self)->tp_free((PyObject*)self); -} - -PyObject* -PymvBuffer_str(PymvBuffer* self) -{ - std::string result = "[ "; - - for (int i = 0; i < 10; i++) - { - if (self->arr.length == i) - break; - - result += std::to_string(self->arr.data[i]) + " "; - } - - result += " ... ]"; - - PyObject* ret = PyUnicode_FromString(result.c_str()); - - return ret; -} - -int -PymvBuffer_getbuffer(PyObject* obj, Py_buffer* view, int flags) -{ - if (view == nullptr) { - PyErr_SetString(PyExc_ValueError, "NULL view in getbuffer"); - return -1; - } - - auto self = (PymvBuffer*)obj; - view->obj = (PyObject*)self; - view->buf = (void*)self->arr.data; - view->len = self->arr.length * sizeof(float); - view->readonly = 0; - view->itemsize = sizeof(float); - //view->format = (char*)(PyBUF_CONTIG_RO | PyBUF_FORMAT); // float - static char format[] = "f"; - view->format = format; // float - view->ndim = 1; - view->shape = (Py_ssize_t*)&self->arr.length; // length-1 sequence of dimensions - view->strides = &view->itemsize; // for the simple case we can do this - view->suboffsets = nullptr; - view->internal = nullptr; - - Py_INCREF(self); // need to increase the reference count - return 0; -} - -Py_ssize_t -PymvBuffer_getLength(PyObject* obj) -{ - auto self = (PymvBuffer*)obj; - return self->arr.length; -} - -PyObject* -PymvBuffer_getItem(PyObject* obj, Py_ssize_t index) -{ - PymvBuffer* self = (PymvBuffer*)obj; - return Py_BuildValue("f", self->arr.data[index]); -} - -int -PymvBuffer_setItem(PyObject* obj, Py_ssize_t index, PyObject* value) -{ - PymvBuffer* self = (PymvBuffer*)obj; - self->arr.data[index] = (float)PyFloat_AsDouble(value); - return 0; -} \ No newline at end of file diff --git a/src/mvCustomTypes.h b/src/mvCustomTypes.h deleted file mode 100644 index 5efd2fdff..000000000 --- a/src/mvCustomTypes.h +++ /dev/null @@ -1,375 +0,0 @@ -#pragma once - -#include -#include "mvMath.h" - -//----------------------------------------------------------------------------- -// mvBuffer -//----------------------------------------------------------------------------- -struct mvBuffer -{ - float* data; - long length; - int width; - int height; -}; - -struct PymvBuffer -{ - PyObject_HEAD - mvBuffer arr; -}; - -// methods -int PymvBuffer_init (PymvBuffer* self, PyObject* args, PyObject* kwds); // __init__ method -PyObject* PymvBuffer_clear_value(PymvBuffer* self, PyObject* args, PyObject* kwds); // clear method -PyObject* PymvBuffer_get_width (PymvBuffer* self, PyObject* args, PyObject* kwds); -PyObject* PymvBuffer_get_height (PymvBuffer* self, PyObject* args, PyObject* kwds); - -void PymvBuffer_dealloc (PymvBuffer* self); // called when deallocated -PyObject* PymvBuffer_str (PymvBuffer* self); // string interface -int PymvBuffer_getbuffer (PyObject* obj, Py_buffer* view, int flags); // buffer interface function -Py_ssize_t PymvBuffer_getLength (PyObject* obj); -PyObject* PymvBuffer_getItem (PyObject* obj, Py_ssize_t index); -int PymvBuffer_setItem (PyObject* obj, Py_ssize_t index, PyObject* value); - -static PyBufferProcs PymvBuffer_as_buffer = { - (getbufferproc)PymvBuffer_getbuffer, - (releasebufferproc)0, -}; - -static PySequenceMethods PymvBuffer_as_sequence = { - (lenfunc)PymvBuffer_getLength, // length - (binaryfunc)0, // concat - (ssizeargfunc)0, // repeat - (ssizeargfunc)PymvBuffer_getItem, // item - (void*)0, // slice - (ssizeobjargproc)PymvBuffer_setItem, // assignment - (void*)0, // assign slice - (objobjproc)0, // contains - (binaryfunc)0, // inplace concat - (ssizeargfunc)0 // inplace repeat -}; - -static PyMethodDef PymvBuffer_methods[] = { - {"clear_value", (PyCFunction)PymvBuffer_clear_value, METH_VARARGS | METH_KEYWORDS, - "clears buffer with specific value." - }, - {"get_width", (PyCFunction)PymvBuffer_get_width, METH_VARARGS | METH_KEYWORDS, - "returns buffer width." - }, - {"get_height", (PyCFunction)PymvBuffer_get_height, METH_VARARGS | METH_KEYWORDS, - "returns buffer height." - }, - - {NULL} /* Sentinel */ -}; - -static PyTypeObject PymvBufferType = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dearpygui.mvBuffer", /* tp_name */ - sizeof(PymvBuffer), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PymvBuffer_dealloc,/* tp_dealloc */ - 0, /* tp_vectorcall_offset, tp_print in 3.6, 3.7 */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_as_async */ - (reprfunc)PymvBuffer_str, /* tp_repr */ - 0, /* tp_as_number */ - &PymvBuffer_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)PymvBuffer_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PymvBuffer_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "mvBuffer object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PymvBuffer_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PymvBuffer_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Free, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weeklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ - 0 /* tp_finalize */ - //0, /* tp_vectorcall */ -}; - -//----------------------------------------------------------------------------- -// mvVec4 -//----------------------------------------------------------------------------- - -struct PymvVec4 -{ - PyObject_HEAD - mvVec4 vec4; -}; - -// methods -int PymvVec4_init (PymvVec4* self, PyObject* args, PyObject* kwds); // __init__ method - -void PymvVec4_dealloc (PymvVec4* self); // called when deallocated -PyObject* PymvVec4_str (PymvVec4* self); // string interface -Py_ssize_t PymvVec4_getLength (PyObject* obj); -PyObject* PymvVec4_getItem (PyObject* obj, Py_ssize_t index); -int PymvVec4_setItem (PyObject* obj, Py_ssize_t index, PyObject* value); - -// math operators -PyObject* PymvVec4_add (PyObject* left, PyObject* right); -PyObject* PymvVec4_subtract(PyObject* left, PyObject* right); -PyObject* PymvVec4_multiply(PyObject* left, PyObject* right); - -static PyNumberMethods PymvVec4_as_number = { - (binaryfunc)PymvVec4_add, // nb_add; - (binaryfunc)PymvVec4_subtract, // nb_subtract; - (binaryfunc)PymvVec4_multiply, // nb_multiply; - (binaryfunc)0, // nb_remainder; - (binaryfunc)0, // nb_divmod; - (ternaryfunc)0, // nb_power; - (unaryfunc)0, // nb_negative; - (unaryfunc)0, // nb_positive; - (unaryfunc)0, // nb_absolute; - (inquiry)0, // nb_bool; - (unaryfunc)0, // nb_invert; - (binaryfunc)0, // nb_lshift; - (binaryfunc)0, // nb_rshift; - (binaryfunc)0, // nb_and; - (binaryfunc)0, // nb_xor; - (binaryfunc)0, // nb_or; - (unaryfunc)0, // nb_int; - (void*)0, // nb_reserved; - (unaryfunc)0, // nb_float; - (binaryfunc)0, // nb_inplace_add; - (binaryfunc)0, // nb_inplace_subtract; - (binaryfunc)0, // nb_inplace_multiply; - (binaryfunc)0, // nb_inplace_remainder; - (ternaryfunc)0, // nb_inplace_power; - (binaryfunc)0, // nb_inplace_lshift; - (binaryfunc)0, // nb_inplace_rshift; - (binaryfunc)0, // nb_inplace_and; - (binaryfunc)0, // nb_inplace_xor; - (binaryfunc)0, // nb_inplace_or; - (binaryfunc)0, // nb_floor_divide; - (binaryfunc)0, // nb_true_divide; - (binaryfunc)0, // nb_inplace_floor_divide; - (binaryfunc)0, // nb_inplace_true_divide; - (unaryfunc)0, // nb_index; - (binaryfunc)0, // nb_matrix_multiply; - (binaryfunc)0 // nb_inplace_matrix_multiply; -}; - -static PySequenceMethods PymvVec4_as_sequence = { - (lenfunc)PymvVec4_getLength, // length - (binaryfunc)0, // concat - (ssizeargfunc)0, // repeat - (ssizeargfunc)PymvVec4_getItem, // item - (void*)0, // slice - (ssizeobjargproc)PymvVec4_setItem, // assignment - (void*)0, // assign slice - (objobjproc)0, // contains - (binaryfunc)0, // inplace concat - (ssizeargfunc)0 // inplace repeat -}; - -static PyTypeObject PymvVec4Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dearpygui.mvVec4", /* tp_name */ - sizeof(PymvVec4), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PymvVec4_dealloc, /* tp_dealloc */ - 0, /* tp_vectorcall_offset, tp_print in 3.6, 3.7 */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_as_async */ - (reprfunc)PymvVec4_str, /* tp_repr */ - &PymvVec4_as_number, /* tp_as_number */ - &PymvVec4_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)PymvVec4_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "mvVec4 object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PymvVec4_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Free, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weeklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ - 0 /* tp_finalize */ - //0, /* tp_vectorcall */ -}; - -//----------------------------------------------------------------------------- -// mvMat4 -//----------------------------------------------------------------------------- - -struct PymvMat4 -{ - PyObject_HEAD - mvMat4 m; -}; - -// methods -int PymvMat4_init (PymvMat4* self, PyObject* args, PyObject* kwds); // __init__ method - -void PymvMat4_dealloc (PymvMat4* self); // called when deallocated -PyObject* PymvMat4_str (PymvMat4* self); // string interface -Py_ssize_t PymvMat4_getLength (PyObject* obj); -PyObject* PymvMat4_getItem (PyObject* obj, Py_ssize_t index); -int PymvMat4_setItem (PyObject* obj, Py_ssize_t index, PyObject* value); - -// math operators -PyObject* PymvMat4_add(PyObject* left, PyObject* right); -PyObject* PymvMat4_subtract(PyObject* left, PyObject* right); -PyObject* PymvMat4_multiply(PyObject* left, PyObject* right); - -static PyNumberMethods PymvMat4_as_number = { - (binaryfunc)PymvMat4_add, // nb_add; - (binaryfunc)PymvMat4_subtract, // nb_subtract; - (binaryfunc)PymvMat4_multiply, // nb_multiply; - (binaryfunc)0, // nb_remainder; - (binaryfunc)0, // nb_divmod; - (ternaryfunc)0, // nb_power; - (unaryfunc)0, // nb_negative; - (unaryfunc)0, // nb_positive; - (unaryfunc)0, // nb_absolute; - (inquiry)0, // nb_bool; - (unaryfunc)0, // nb_invert; - (binaryfunc)0, // nb_lshift; - (binaryfunc)0, // nb_rshift; - (binaryfunc)0, // nb_and; - (binaryfunc)0, // nb_xor; - (binaryfunc)0, // nb_or; - (unaryfunc)0, // nb_int; - (void*)0, // nb_reserved; - (unaryfunc)0, // nb_float; - (binaryfunc)0, // nb_inplace_add; - (binaryfunc)0, // nb_inplace_subtract; - (binaryfunc)0, // nb_inplace_multiply; - (binaryfunc)0, // nb_inplace_remainder; - (ternaryfunc)0, // nb_inplace_power; - (binaryfunc)0, // nb_inplace_lshift; - (binaryfunc)0, // nb_inplace_rshift; - (binaryfunc)0, // nb_inplace_and; - (binaryfunc)0, // nb_inplace_xor; - (binaryfunc)0, // nb_inplace_or; - (binaryfunc)0, // nb_floor_divide; - (binaryfunc)0, // nb_true_divide; - (binaryfunc)0, // nb_inplace_floor_divide; - (binaryfunc)0, // nb_inplace_true_divide; - (unaryfunc)0, // nb_index; - (binaryfunc)0, // nb_matrix_multiply; - (binaryfunc)0 // nb_inplace_matrix_multiply; -}; - -static PySequenceMethods PymvMat4_as_sequence = { - (lenfunc)PymvMat4_getLength, // length - (binaryfunc)0, // concat - (ssizeargfunc)0, // repeat - (ssizeargfunc)PymvMat4_getItem, // item - (void*)0, // slice - (ssizeobjargproc)PymvMat4_setItem, // assignment - (void*)0, // assign slice - (objobjproc)0, // contains - (binaryfunc)0, // inplace concat - (ssizeargfunc)0 // inplace repeat -}; - -static PyTypeObject PymvMat4Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dearpygui.mvMat4", /* tp_name */ - sizeof(PymvMat4), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PymvMat4_dealloc, /* tp_dealloc */ - 0, /* tp_vectorcall_offset, tp_print in 3.6, 3.7 */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_as_async */ - (reprfunc)PymvMat4_str, /* tp_repr */ - &PymvMat4_as_number, /* tp_as_number */ - &PymvMat4_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)PymvMat4_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "mvMat4 object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PymvMat4_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Free, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weeklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ - 0 /* tp_finalize */ - //0, /* tp_vectorcall */ -}; - diff --git a/src/mvDatePicker.cpp b/src/mvDatePicker.cpp deleted file mode 100644 index 611fc0888..000000000 --- a/src/mvDatePicker.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvDatePicker.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvContainers.h" -#include "mvItemHandlers.h" - -#include -#include -#include - -void mvDatePicker::draw(ImDrawList* drawlist, float x, float y) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!config.show) - return; - - // focusing - if (info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (info.dirtyPos) - ImGui::SetCursorPos(state.pos); - - // update widget's position state - state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (config.width != 0) - ImGui::SetNextItemWidth((float)config.width); - - // set indent - if (config.indent > 0.0f) - ImGui::Indent(config.indent); - - // push font if a font object is attached - if (font) - static_cast(font.get())->pushFont(); - - // themes - apply_local_theming(this); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - - ScopedID id(uuid); - - if (ImPlot::ShowDatePicker(info.internalLabel.c_str(), &_level, _imvalue.get(), _imvalue.get())) - { - ImPlot::GetGmtTime(*_imvalue, _value.get()); - { - submitCallback(*_value); - } - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (config.indent > 0.0f) - ImGui::Unindent(config.indent); - - // pop font off stack - if (font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(this); - - if (handlerRegistry) - handlerRegistry->checkEvents(&state); - - // handle drag & drop if used - apply_drag_drop(this); -} - -void mvDatePicker::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "level")) { - _level = ToInt(item); - if (_level > 2) _level = 0; - } -} - -void mvDatePicker::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "level", mvPyObject(ToPyLong((long)_level))); -} - -PyObject* mvDatePicker::getPyValue() -{ - return ToPyTime(*_value); -} - -void mvDatePicker::setPyValue(PyObject* value) -{ - - if (value) - *_value = ToTime(value); - else - _value = {}; - - *_imvalue = ImPlot::MkGmtTime(_value.get()); -} \ No newline at end of file diff --git a/src/mvDatePicker.h b/src/mvDatePicker.h deleted file mode 100644 index 06a664725..000000000 --- a/src/mvDatePicker.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include "mvItemRegistry.h" -// For ImPlotTime -#include - -class mvDatePicker : public mvAppItem -{ - enum class DatePickerLevel { - mvDatePickerLevel_Day = 0L, - mvDatePickerLevel_Month, - mvDatePickerLevel_Year - }; - -public: - - explicit mvDatePicker(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - // values - void* getValue() override { return &_value; } - PyObject* getPyValue() override; - void setPyValue(PyObject* value) override; - -private: - - std::shared_ptr _value = std::make_shared(); - std::shared_ptr _imvalue = std::make_shared(); - int _level = 0; - -}; \ No newline at end of file diff --git a/src/mvDebugWindow.cpp b/src/mvDebugWindow.cpp deleted file mode 100644 index 522936c99..000000000 --- a/src/mvDebugWindow.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include "mvDebugWindow.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "dearpygui.h" - -#include - -mvDebugWindow::mvDebugWindow() -{ - m_windowflags = ImGuiWindowFlags_NoSavedSettings; - - m_width = 700; - m_height = 500; - - for (const auto& item : GetModuleParsers()) - m_commands.emplace_back(item.first, item.second.documentation); -} - -void mvDebugWindow::drawWidgets() -{ - - static std::string commandstring; - - ImGuiIO& io = ImGui::GetIO(); - - static size_t commandselection = 0; - const char* commanddoc = m_commands[commandselection].second.c_str(); - static ImGuiTextFilter filter; - filter.Draw(); - - ImGui::PushItemWidth(-1); - ImGui::BeginChild("CommandsChild##debug", ImVec2(400.0f, 400.0f), ImGuiChildFlags_Borders); - ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 1.0f, 0.0f, 1.0f }); - for (size_t i = 0; i < m_commands.size(); i++) - { - auto& item = m_commands[i]; - - if (filter.PassFilter(item.first.c_str())) - { - if (ImGui::Selectable(item.first.c_str(), i == commandselection)) - commandselection = i; - } - } - ImGui::PopStyleColor(); - ImGui::EndChild(); - ImGui::SameLine(); - ImGui::BeginChild("CommandsDoc##debug", ImVec2(-1.0f, 400.0f), ImGuiChildFlags_Borders); - ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 0.0f, 1.0f, 1.0f }); - ImGui::PushTextWrapPos(500); - ImGui::Text("%s", commanddoc); - ImGui::PopStyleColor(); - ImGui::PopTextWrapPos(); - ImGui::EndChild(); - - ImGui::InputTextMultiline("Command##debug", &commandstring, ImVec2(-1, -50)); - ImGui::PopItemWidth(); - if (ImGui::Button("Run##debug")) - { - std::string command = "from dearpygui.dearpygui import *\nfrom dearpygui.demo import *\n" + commandstring; - mvSubmitCallback([=]() { - PyRun_SimpleString(command.c_str()); - }); - - } - -} \ No newline at end of file diff --git a/src/mvDebugWindow.h b/src/mvDebugWindow.h deleted file mode 100644 index a2b97c81b..000000000 --- a/src/mvDebugWindow.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "mvToolWindow.h" -#include "mvAppItem.h" - -class mvDebugWindow final : public mvToolWindow -{ - -public: - - mvDebugWindow(); - - [[nodiscard]] mvUUID getUUID() const override { return MV_TOOL_DEBUG_UUID; } - [[nodiscard]] const char* getTitle() const override { return "Dear PyGui Debug"; } - -protected: - - void drawWidgets() override; - -private: - - std::vector> m_commands; - -}; \ No newline at end of file diff --git a/src/mvDocWindow.cpp b/src/mvDocWindow.cpp deleted file mode 100644 index be08cb066..000000000 --- a/src/mvDocWindow.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvDocWindow.h" - -#include "dearpygui.h" - -#include - -mvDocWindow::mvDocWindow() -{ - m_windowflags = ImGuiWindowFlags_NoSavedSettings; - m_width = 700; - m_height = 500; - setup(); -} - -void mvDocWindow::setup() -{ - - const std::map& docmap = GetModuleParsers(); - const std::vector>& constants = GetModuleConstants(); - - for (const auto& item : constants) - { - m_constantsValues.emplace_back("Constant with a value of " + std::to_string(item.second)); - m_docCategories["Constants"].push_back(m_constantsValues.back().c_str()); - m_commandCategories["Constants"].push_back(item.first.c_str()); - } - - for (const auto& item : docmap) - { - m_commands.emplace_back(item.first.c_str(), item.second.documentation); - - const std::vector& categories = item.second.category; - - for (const auto& category : categories) - { - bool categoryExists = false; - for (const auto& cat : m_categories) - { - if (cat == category) - { - categoryExists = true; - break; - } - } - - if (!categoryExists) - m_categories.push_back(category.c_str()); - - auto& docCategory = m_docCategories[category]; - docCategory.push_back(item.second.documentation.c_str()); - - auto& commandCategory = m_commandCategories[category]; - commandCategory.push_back(item.first.c_str()); - } - - } - - m_categories.push_back("Constants"); - -} - -void mvDocWindow::drawWidgets() -{ - - if (ImGui::BeginTabBar("Main Tabbar##doc")) - { - if (ImGui::BeginTabItem("Commands##doc")) - { - ImGui::BeginGroup(); - ImGui::SetNextItemWidth(500); - ImGui::ListBox("Category", &categorySelection, m_categories.data(), (int)m_categories.size(), 7); - - ImGui::SetNextItemWidth(500); - ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32(255, 0, 0, 100)); - - static int selection = 0; - const std::string& category = m_categories[categorySelection]; - std::vector& commands = m_commandCategories[category]; - std::vector& docs = m_docCategories[category]; - if (ImGui::ListBox("Commands", &selection, commands.data(), (int)commands.size(), 30)) - m_doc = docs[selection]; - - //else if (categorySelection == 11) - //{ - // static int selection = 0; - // if (ImGui::ListBox("Commands", &selection, m_cconstants.data(), (int)m_cconstants.size(), 30)) - // m_doc = m_constantsValues[selection].c_str(); - //} - - ImGui::PopStyleColor(); - ImGui::EndGroup(); - - ImGui::SameLine(); - ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 255, 100)); - ImGui::BeginChild("DocChild", ImVec2(0, 0), ImGuiChildFlags_Borders); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + 400); - ImGui::Text("%s", m_doc); - ImGui::PopTextWrapPos(); - ImGui::EndChild(); - ImGui::PopStyleColor(); - - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem("Search Commands##doc")) - { - - static size_t commandselection = 0; - const char* commanddoc = m_commands[commandselection].second.c_str(); - static ImGuiTextFilter filter; - filter.Draw(); - - ImGui::PushItemWidth(300); - ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); - ImGui::BeginChild("CommandsChild##debug", ImVec2(500.0f, 0), ImGuiChildFlags_Borders); - - for (size_t i = 0; i < m_commands.size(); i++) - { - auto& item = m_commands[i]; - - if (filter.PassFilter(item.first.c_str())) - { - if (ImGui::Selectable(item.first.c_str(), i == commandselection)) - commandselection = i; - } - } - ImGui::PopStyleColor(); - ImGui::EndChild(); - ImGui::SameLine(); - ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 255, 100)); - ImGui::BeginChild("CommandsDoc##debug", ImVec2(0, 0), ImGuiChildFlags_Borders); - ImGui::PushTextWrapPos(500); - ImGui::Text("%s", commanddoc); - ImGui::PopStyleColor(); - ImGui::PopTextWrapPos(); - ImGui::EndChild(); - ImGui::EndTabItem(); - } - - ImGui::EndTabBar(); - } -} \ No newline at end of file diff --git a/src/mvDocWindow.h b/src/mvDocWindow.h deleted file mode 100644 index 729d1c2a2..000000000 --- a/src/mvDocWindow.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include -#include "mvToolWindow.h" - -class mvDocWindow final : public mvToolWindow -{ - -public: - - mvDocWindow(); - - [[nodiscard]] mvUUID getUUID() const override { return MV_TOOL_DOC_UUID; } - [[nodiscard]] const char* getTitle() const override { return "Internal Documentation"; } - -protected: - - void drawWidgets() override; - -private: - - void setup(); - - int categorySelection = 0; - const char* m_doc = "None"; - - std::vector m_categories; - - std::unordered_map> m_commandCategories; - std::unordered_map> m_docCategories; - - std::vector m_cconstants; - - std::vector> m_commands; - - std::vector m_constantsValues; - -}; \ No newline at end of file diff --git a/src/mvDrawings.cpp b/src/mvDrawings.cpp deleted file mode 100644 index be3dc6232..000000000 --- a/src/mvDrawings.cpp +++ /dev/null @@ -1,1701 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvDrawings.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "mvFontItems.h" -#include "mvItemHandlers.h" -#include "mvTextureItems.h" -#include "mvCustomTypes.h" - -#include -#include - -mvDrawArrow::mvDrawArrow(mvUUID uuid) - : - mvAppItem(uuid) -{ - updatePoints(); -} - -void mvDrawArrow::updatePoints() -{ - float xsi = _p1.x; - float xfi = _p2.x; - float ysi = _p1.y; - float yfi = _p2.y; - - // length of arrow head - double xoffset = _size; - double yoffset = _size; - - // get pointer angle w.r.t +X (in radians) - double angle = 0.0; - if (xsi >= xfi && ysi >= yfi) { - angle = atan((ysi - yfi) / (xsi - xfi)); - } - else if (xsi < xfi && ysi >= yfi) { - angle = M_PI + atan((ysi - yfi) / (xsi - xfi)); - } - else if (xsi < xfi && ysi < yfi) { - angle = -M_PI + atan((ysi - yfi) / (xsi - xfi)); - } - else if (xsi >= xfi && ysi < yfi) { - angle = atan((ysi - yfi) / (xsi - xfi)); - } - - // arrow head points - auto x1 = (float)(xsi - xoffset * cos(angle)); - auto y1 = (float)(ysi - yoffset * sin(angle)); - - _points[0] = { xsi, ysi, 0.0f, 1.0f }; - _points[1] = { (float)(x1 - 0.5 * _size * sin(angle)), (float)(y1 + 0.5 * _size * cos(angle)), 0.0f, 1.0f }; - _points[2] = { (float)(x1 + 0.5 * _size * cos((M_PI / 2.0) - angle)), (float)(y1 - 0.5 * _size * sin((M_PI / 2.0) - angle)), 0.0f, 1.0f }; - -} - -void mvDrawArrow::draw(ImDrawList* drawlist, float x, float y) -{ - - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - - mvVec4 tpp1 = drawInfo->transform * _points[0]; - mvVec4 tpp2 = drawInfo->transform * _points[1]; - mvVec4 tpp3 = drawInfo->transform * _points[2]; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tpp1.x = tpp1.x / tpp1.w; - tpp2.x = tpp2.x / tpp2.w; - tpp3.x = tpp3.x / tpp3.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tpp1.y = tpp1.y / tpp1.w; - tpp2.y = tpp2.y / tpp2.w; - tpp3.y = tpp3.y / tpp3.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tpp1.z = tpp1.z / tpp1.w; - tpp2.z = tpp2.z / tpp2.w; - tpp3.z = tpp3.z / tpp3.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tpp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tpp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tpp3)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddTriangleFilled(ImPlot::PlotToPixels(tpp1), ImPlot::PlotToPixels(tpp2), ImPlot::PlotToPixels(tpp3), _color); - drawlist->AddLine(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), _color, Mx * _thickness); - drawlist->AddTriangle(ImPlot::PlotToPixels(tpp1), ImPlot::PlotToPixels(tpp2), ImPlot::PlotToPixels(tpp3), _color, Mx * _thickness); - } - else - { - mvVec2 start = { x, y }; - drawlist->AddTriangleFilled(tpp1 + start, tpp2 + start, tpp3 + start, _color); - drawlist->AddLine(tp1 + start, tp2 + start, _color, _thickness); - drawlist->AddTriangle(tpp1 + start, tpp2 + start, tpp3 + start, _color, _thickness); - } -} - -void mvDrawArrow::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p1.w = 1.0f; - _p2.w = 1.0f; - - updatePoints(); -} - -void mvDrawArrow::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "size")) _size = ToFloat(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; - - updatePoints(); - -} - -void mvDrawArrow::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - PyDict_SetItemString(dict, "size", mvPyObject(ToPyFloat(_size))); -} - -void mvDrawBezierCubic::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - mvVec4 tp3 = drawInfo->transform * _p3; - mvVec4 tp4 = drawInfo->transform * _p4; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tp3.x = tp3.x / tp3.w; - tp4.x = tp4.x / tp4.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tp3.y = tp3.y / tp3.w; - tp4.y = tp4.y / tp4.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tp3.z = tp3.z / tp3.w; - tp4.z = tp4.z / tp4.w; - } - - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tp3)) return; - if (mvClipPoint(drawInfo->clipViewport, tp4)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddBezierCubic(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), - ImPlot::PlotToPixels(tp4), _color, Mx * _thickness, _segments); - } - else - { - mvVec2 start = { x, y }; - drawlist->AddBezierCubic(tp1 + start, tp2 + start, tp3 + start, tp4 + start, _color, _thickness, _segments); - } -} - -void mvDrawBezierCubic::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p3 = ToVec4(PyTuple_GetItem(dict, 2)); - _p4 = ToVec4(PyTuple_GetItem(dict, 3)); - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; - _p4.w = 1.0f; -} - -void mvDrawBezierCubic::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p3")) _p3 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p4")) _p4 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "segments")) _segments = ToInt(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; - _p4.w = 1.0f; -} - -void mvDrawBezierCubic::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "p3", mvPyObject(ToPyPair(_p3.x, _p3.y))); - PyDict_SetItemString(dict, "p4", mvPyObject(ToPyPair(_p4.x, _p4.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - PyDict_SetItemString(dict, "segments", mvPyObject(ToPyInt(_segments))); -} - -void mvDrawBezierQuadratic::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - mvVec4 tp3 = drawInfo->transform * _p3; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tp3.x = tp3.x / tp3.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tp3.y = tp3.y / tp3.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tp3.z = tp3.z / tp3.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tp3)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddBezierQuadratic(ImPlot::PlotToPixels(tp1), - ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), _color, Mx * _thickness, _segments); - } - else - { - mvVec2 start = { x, y }; - drawlist->AddBezierQuadratic(tp1 + start, tp2 + start, tp3 + start, _color, _thickness, _segments); - } -} - -void mvDrawBezierQuadratic::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p3 = ToVec4(PyTuple_GetItem(dict, 2)); - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; -} - -void mvDrawBezierQuadratic::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p3")) _p3 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "segments")) _segments = ToInt(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; -} - -void mvDrawBezierQuadratic::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "p3", mvPyObject(ToPyPair(_p3.x, _p3.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - PyDict_SetItemString(dict, "segments", mvPyObject(ToPyInt(_segments))); -} - -void mvDrawCircle::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tcenter = drawInfo->transform * _center; - - if (drawInfo->perspectiveDivide) - { - tcenter.x = tcenter.x / tcenter.w; - tcenter.y = tcenter.y / tcenter.w; - tcenter.z = tcenter.z / tcenter.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tcenter)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - if (_fill.r >= 0.0f) - drawlist->AddCircleFilled(ImPlot::PlotToPixels(tcenter), Mx * _radius, _fill, (int)(Mx * _segments)); - drawlist->AddCircle(ImPlot::PlotToPixels(tcenter), Mx * _radius, _color, (int)(Mx * _segments), _thickness); - } - else - { - mvVec2 start = { x, y }; - if (_fill.r >= 0.0f) - drawlist->AddCircleFilled(tcenter + start, _radius, _fill, _segments); - drawlist->AddCircle(tcenter + start, _radius, _color, _segments, _thickness); - } -} - -void mvDrawCircle::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _center = ToVec4(PyTuple_GetItem(dict, 0)); - _center.w = 1.0f; - _radius = ToFloat(PyTuple_GetItem(dict, 1)); -} - -void mvDrawCircle::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - - if (PyObject* item = PyDict_GetItemString(dict, "center")) _center = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "radius")) _radius = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "segments")) _segments = ToInt(item); - - _center.w = 1.0f; -} - -void mvDrawCircle::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "center", mvPyObject(ToPyPair(_center.x, _center.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - PyDict_SetItemString(dict, "radius", mvPyObject(ToPyFloat(_radius))); - PyDict_SetItemString(dict, "segments", mvPyObject(ToPyInt(_segments))); -} - -void mvDrawEllipse::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tpmin = drawInfo->transform * _pmin; - mvVec4 tpmax = drawInfo->transform * _pmax; - - if (drawInfo->perspectiveDivide) - { - tpmin.x = tpmin.x / tpmin.w; - tpmin.y = tpmin.y / tpmin.w; - tpmin.z = tpmin.z / tpmin.w; - - tpmax.x = tpmax.x / tpmax.w; - tpmax.y = tpmax.y / tpmax.w; - tpmax.z = tpmax.z / tpmax.w; - } - - if (_dirty) - { - if (_segments < 3) { _segments = 3; } - const float width = _pmax.x - _pmin.x; - const float height = _pmax.y - _pmin.y; - const float cx = width / 2.0f + _pmin.x; - const float cy = height / 2.0f + _pmin.y; - const float radian_inc = ((float)M_PI * 2.0f) / (float)_segments; - std::vector points; - points.reserve(_segments + 1); - for (int i = 0; i <= _segments; i++) - { - points.push_back(mvVec4{ cx + cosf(i * radian_inc) * width / 2.0f, cy + sinf(i * radian_inc) * height / 2.0f, 0.0f, 1.0f }); - } - _points = std::move(points); - _dirty = false; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tpmin)) return; - if (mvClipPoint(drawInfo->clipViewport, tpmax)) return; - } - - // this is disgusting; we should not be allocating - // every frame. Fix ASAP - std::vector points = _points; - std::vector finalpoints; - finalpoints.reserve(_points.size()); - - for (auto& point : points) - point = drawInfo->transform * point; - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - for (auto& point : points) - { - ImVec2 impoint = ImPlot::PlotToPixels(point); - point.x = impoint.x; - point.y = impoint.y; - finalpoints.push_back(impoint); - } - } - else - { - for (auto& point : points) - { - point.x += x; - point.y += y; - finalpoints.push_back(ImVec2{ point.x, point.y }); - } - } - - if (_fill.r >= 0.0f) - drawlist->AddConvexPolyFilled(finalpoints.data(), (int)finalpoints.size(), _fill); - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddPolyline(finalpoints.data(), (int)finalpoints.size(), _color, false, Mx * _thickness); - } - else - drawlist->AddPolyline(finalpoints.data(), (int)finalpoints.size(), - _color, false, _thickness); -} - -void mvDrawEllipse::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _pmin = ToVec4(PyTuple_GetItem(dict, 0)); - _pmin.w = 1.0f; - _pmax = ToVec4(PyTuple_GetItem(dict, 1)); - _pmax.w = 1.0f; - _dirty = true; -} - -void mvDrawEllipse::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "pmax")) { _pmax = ToVec4(item); _dirty = true; } - if (PyObject* item = PyDict_GetItemString(dict, "pmin")) { _pmin = ToVec4(item); _dirty = true; } - if (PyObject* item = PyDict_GetItemString(dict, "segments")) _segments = ToInt(item); - - _pmin.w = 1.0f; - _pmax.w = 1.0f; -} - -void mvDrawEllipse::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - PyDict_SetItemString(dict, "pmax", mvPyObject(ToPyPair(_pmax.x, _pmax.y))); - PyDict_SetItemString(dict, "pmin", mvPyObject(ToPyPair(_pmin.x, _pmin.y))); - PyDict_SetItemString(dict, "segments", mvPyObject(ToPyInt(_segments))); -} - -void mvDrawImage::draw(ImDrawList* drawlist, float x, float y) -{ - if (_texture && _texture->state.ok) - { - auto type = _texture->type; - if (type != mvAppItemType::mvStaticTexture && - type != mvAppItemType::mvDynamicTexture && - type != mvAppItemType::mvRawTexture) - return; - - ImTextureRef texture = static_cast(_texture.get())->getTexRef(); - - mvVec4 tpmin = drawInfo->transform * _pmin; - mvVec4 tpmax = drawInfo->transform * _pmax; - - if (drawInfo->perspectiveDivide) - { - tpmin.x = tpmin.x / tpmin.w; - tpmax.x = tpmax.x / tpmax.w; - - tpmin.y = tpmin.y / tpmin.w; - tpmax.y = tpmax.y / tpmax.w; - - tpmin.z = tpmin.z / tpmin.w; - tpmax.z = tpmax.z / tpmax.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tpmin)) return; - if (mvClipPoint(drawInfo->clipViewport, tpmax)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - drawlist->AddImage(texture, ImPlot::PlotToPixels(tpmin), ImPlot::PlotToPixels(tpmax), _uv_min, _uv_max, _color); - else - { - mvVec2 start = { x, y }; - drawlist->AddImage(texture, tpmin + start, tpmax + start, _uv_min, _uv_max, _color); - } - } -} - -void mvDrawImage::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - mvUUID _textureUUID = GetIDFromPyObject(PyTuple_GetItem(dict, 0)); - if (_textureUUID == MV_ATLAS_UUID) - { - _texture = std::make_shared(_textureUUID); - } - else - { - _texture = GetRefItem(*GContext->itemRegistry, _textureUUID); - if (!_texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this); - } - - _pmin = ToVec4(PyTuple_GetItem(dict, 1)); - _pmin.w = 1.0f; - _pmax = ToVec4(PyTuple_GetItem(dict, 2)); - _pmax.w = 1.0f; -} - -void mvDrawImage::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "pmax")) _pmax = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "pmin")) _pmin = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) _uv_min = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) _uv_max = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "texture_tag")) - { - mvUUID _textureUUID = GetIDFromPyObject(item); - if (_textureUUID == MV_ATLAS_UUID) - { - _texture = std::make_shared(_textureUUID); - } - else - { - _texture = GetRefItem(*GContext->itemRegistry, _textureUUID); - if (!_texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this); - } - } - - _pmin.w = 1.0f; - _pmax.w = 1.0f; -} - -void mvDrawImage::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "pmax", mvPyObject(ToPyPair(_pmax.x, _pmax.y))); - PyDict_SetItemString(dict, "pmin", mvPyObject(ToPyPair(_pmin.x, _pmin.y))); - PyDict_SetItemString(dict, "uv_min", mvPyObject(ToPyPair(_uv_min.x, _uv_min.y))); - PyDict_SetItemString(dict, "uv_max", mvPyObject(ToPyPair(_uv_max.x, _uv_max.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "texture_tag", mvPyObject(ToPyUUID(_texture.get()))); -} - -void mvDrawImageQuad::draw(ImDrawList* drawlist, float x, float y) -{ - if (_texture && _texture->state.ok) - { - auto type = _texture->type; - if (type != mvAppItemType::mvStaticTexture && - type != mvAppItemType::mvDynamicTexture && - type != mvAppItemType::mvRawTexture) - return; - - ImTextureRef texture = static_cast(_texture.get())->getTexRef(); - - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - mvVec4 tp3 = drawInfo->transform * _p3; - mvVec4 tp4 = drawInfo->transform * _p4; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tp3.x = tp3.x / tp3.w; - tp4.x = tp4.x / tp4.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tp3.y = tp3.y / tp3.w; - tp4.y = tp4.y / tp4.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tp3.z = tp3.z / tp3.w; - tp4.z = tp4.z / tp4.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tp3)) return; - if (mvClipPoint(drawInfo->clipViewport, tp4)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - drawlist->AddImageQuad(texture, ImPlot::PlotToPixels(tp1), - ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), ImPlot::PlotToPixels(tp4), - _uv1, _uv2, _uv3, _uv4, _color); - else - { - mvVec2 start = { x, y }; - drawlist->AddImageQuad(texture, tp1 + start, tp2 + start, tp3 + start, tp4 + start, _uv1, _uv2, _uv3, _uv4, _color); - } - } -} - -void mvDrawImageQuad::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - mvUUID _textureUUID = GetIDFromPyObject(PyTuple_GetItem(dict, 0)); - if (_textureUUID == MV_ATLAS_UUID) - { - _texture = std::make_shared(_textureUUID); - } - else - { - _texture = GetRefItem(*GContext->itemRegistry, _textureUUID); - if (!_texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this); - } - - _p1 = ToVec4(PyTuple_GetItem(dict, 1)); - _p1.w = 1.0f; - _p2 = ToVec4(PyTuple_GetItem(dict, 2)); - _p2.w = 1.0f; - _p3 = ToVec4(PyTuple_GetItem(dict, 3)); - _p3.w = 1.0f; - _p4 = ToVec4(PyTuple_GetItem(dict, 4)); - _p4.w = 1.0f; - -} - -void mvDrawImageQuad::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p3")) _p3 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p4")) _p4 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv1")) _uv1 = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv2")) _uv2 = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv3")) _uv3 = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "uv4")) _uv4 = ToVec2(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "texture_tag")) - { - mvUUID _textureUUID = GetIDFromPyObject(item); - if (_textureUUID == MV_ATLAS_UUID) - { - _texture = std::make_shared(_textureUUID); - } - else - { - _texture = GetRefItem(*GContext->itemRegistry, _textureUUID); - if (!_texture) - mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this); - } - } - - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; - _p4.w = 1.0f; -} - -void mvDrawImageQuad::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "p3", mvPyObject(ToPyPair(_p3.x, _p3.y))); - PyDict_SetItemString(dict, "p4", mvPyObject(ToPyPair(_p4.x, _p4.y))); - PyDict_SetItemString(dict, "uv1", mvPyObject(ToPyPair(_uv1.x, _uv1.y))); - PyDict_SetItemString(dict, "uv2", mvPyObject(ToPyPair(_uv2.x, _uv2.y))); - PyDict_SetItemString(dict, "uv3", mvPyObject(ToPyPair(_uv3.x, _uv3.y))); - PyDict_SetItemString(dict, "uv4", mvPyObject(ToPyPair(_uv4.x, _uv4.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "texture_tag", mvPyObject(ToPyUUID(_texture.get()))); -} - -mvDrawLayer::~mvDrawLayer() -{ -} - -void mvDrawLayer::draw(ImDrawList* drawlist, float x, float y) -{ - - for (auto& item : childslots[2]) - { - // skip item if it's not shown - if (!item->config.show) - continue; - - item->drawInfo->perspectiveDivide = drawInfo->perspectiveDivide; - item->drawInfo->depthClipping = drawInfo->depthClipping; - - item->drawInfo->transform = drawInfo->transform; - - item->drawInfo->cullMode = drawInfo->cullMode; - item->drawInfo->clipViewport[0] = drawInfo->clipViewport[0]; - item->drawInfo->clipViewport[1] = drawInfo->clipViewport[1]; - item->drawInfo->clipViewport[2] = drawInfo->clipViewport[2]; - item->drawInfo->clipViewport[3] = drawInfo->clipViewport[3]; - item->drawInfo->clipViewport[4] = drawInfo->clipViewport[4]; - item->drawInfo->clipViewport[5] = drawInfo->clipViewport[5]; - item->draw(drawlist, x, y); - - UpdateAppItemState(item->state); - } -} - -void mvDrawLayer::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "perspective_divide")) drawInfo->perspectiveDivide = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "depth_clipping")) drawInfo->depthClipping = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "cull_mode")) drawInfo->cullMode = ToInt(item); - -} - -void mvDrawLayer::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - PyDict_SetItemString(dict, "perspective_divide", mvPyObject(ToPyBool(drawInfo->perspectiveDivide))); - PyDict_SetItemString(dict, "depth_clipping", mvPyObject(ToPyBool(drawInfo->depthClipping))); - PyDict_SetItemString(dict, "cull_mode", mvPyObject(ToPyInt(drawInfo->cullMode))); -} - -void mvDrawLine::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddLine(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), _color, Mx * _thickness); - } - else - { - mvVec2 start = { x, y }; - drawlist->AddLine(tp1 + start, tp2 + start, _color, _thickness); - } - -} - -void mvDrawLine::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p1.w = 1.0f; - _p2.w = 1.0f; - -} - -void mvDrawLine::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; -} - -void mvDrawLine::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); -} - -void mvDrawlist::draw(ImDrawList* drawlist, float x, float y) -{ - - if (!config.show) - return; - - _startx = (float)ImGui::GetCursorScreenPos().x; - _starty = (float)ImGui::GetCursorScreenPos().y; - - ImDrawList* internal_drawlist = ImGui::GetWindowDrawList(); - - ImGui::PushClipRect({ _startx, _starty }, { _startx + (float)config.width, _starty + (float)config.height }, true); - - for (auto& item : childslots[2]) - { - // skip item if it's not shown - if (!item->config.show) - continue; - - item->draw(internal_drawlist, _startx, _starty); - - UpdateAppItemState(item->state); - } - - ImGui::PopClipRect(); - - if (ImGui::InvisibleButton(info.internalLabel.c_str(), ImVec2((float)config.width, (float)config.height), ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle | ImGuiButtonFlags_EnableNav)) - { - submitCallback(); - } - - UpdateAppItemState(state); - - if (handlerRegistry) - handlerRegistry->checkEvents(&state); - - if (ImGui::IsItemHovered()) - { - ImVec2 mousepos = ImGui::GetMousePos(); - GContext->input.mouseDrawingPos.x = (int)(mousepos.x - _startx); - GContext->input.mouseDrawingPos.y = (int)(mousepos.y - _starty); - } -} - -void mvDrawlist::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - config.width = ToInt(PyTuple_GetItem(dict, 0)); - config.height = ToInt(PyTuple_GetItem(dict, 1)); -} - -void mvDrawlist::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "width", mvPyObject(ToPyInt(config.width))); - PyDict_SetItemString(dict, "height", mvPyObject(ToPyInt(config.height))); -} - -mvDrawNode::~mvDrawNode() -{ -} - -void mvDrawNode::draw(ImDrawList* drawlist, float x, float y) -{ - - for (auto& item : childslots[2]) - { - // skip item if it's not shown - if (!item->config.show) - continue; - - item->drawInfo->transform = drawInfo->transform * drawInfo->appliedTransform; - - item->drawInfo->perspectiveDivide = drawInfo->perspectiveDivide; - item->drawInfo->depthClipping = drawInfo->depthClipping; - item->drawInfo->cullMode = drawInfo->cullMode; - item->drawInfo->clipViewport[0] = drawInfo->clipViewport[0]; - item->drawInfo->clipViewport[1] = drawInfo->clipViewport[1]; - item->drawInfo->clipViewport[2] = drawInfo->clipViewport[2]; - item->drawInfo->clipViewport[3] = drawInfo->clipViewport[3]; - item->drawInfo->clipViewport[4] = drawInfo->clipViewport[4]; - item->drawInfo->clipViewport[5] = drawInfo->clipViewport[5]; - item->draw(drawlist, x, y); - - UpdateAppItemState(item->state); - } -} - -void mvDrawNode::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - -} - -void mvDrawNode::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; -} - -void mvDrawPolygon::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 start = { x, y }; - - // this is disgusting; we should not be allocating - // every frame. Fix ASAP - std::vector points = _points; - std::vector finalpoints; - finalpoints.reserve(_points.size()); - - for (auto& point : points) - point = drawInfo->transform * point; - - if (drawInfo->perspectiveDivide) - { - - for (auto& point : points) - { - point.x = point.x / point.w; - point.y = point.y / point.w; - point.z = point.z / point.w; - } - } - - if (drawInfo->depthClipping) - { - for (auto& point : points) - if (mvClipPoint(drawInfo->clipViewport, point)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - for (auto& point : points) - { - ImVec2 impoint = ImPlot::PlotToPixels(point); - point.x = impoint.x; - point.y = impoint.y; - finalpoints.push_back(impoint); - } - } - else - { - for (auto& point : points) - { - point = point + start; - finalpoints.push_back(ImVec2{ point.x, point.y }); - } - } - - if (_fill.r >= 0.0f) - { - size_t i; - int y; - int miny, maxy; - int x1, y1; - int x2, y2; - int ind1, ind2; - size_t ints; - size_t n = finalpoints.size(); - int* polyints = new int[n]; - - /* Determine Y maxima */ - miny = (int)finalpoints[0].y; - maxy = (int)finalpoints[0].y; - for (i = 1; i < n; i++) - { - miny = std::min(miny, (int)finalpoints[i].y); - maxy = std::max(maxy, (int)finalpoints[i].y); - } - - /* Draw, scanning y */ - for (y = miny; y < maxy; y++) { - ints = 0; - for (i = 0; (i < n); i++) { - if (!i) - { - ind1 = (int)n - 1; - ind2 = 0; - } - else - { - ind1 = (int)i - 1; - ind2 = (int)i; - } - y1 = (int)finalpoints[ind1].y; - y2 = (int)finalpoints[ind2].y; - if (y1 < y2) - { - x1 = (int)finalpoints[ind1].x; - x2 = (int)finalpoints[ind2].x; - } - else if (y1 > y2) - { - y2 = (int)finalpoints[ind1].y; - y1 = (int)finalpoints[ind2].y; - x2 = (int)finalpoints[ind1].x; - x1 = (int)finalpoints[ind2].x; - } - else - continue; - - if (((y >= y1) && (y < y2)) || ((y == maxy) && (y > y1) && (y <= y2))) - polyints[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; - - } - - auto compare_int = [](const void* a, const void* b) - { - return (*(const int*)a) - (*(const int*)b); - }; - - qsort(polyints, ints, sizeof(int), compare_int); - - for (i = 0; i < ints; i += 2) - { - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddLine(ImPlot::PlotToPixels({ (float)polyints[i], (float)y }), - ImPlot::PlotToPixels({ (float)polyints[i + 1], (float)y }), _fill, Mx * _thickness); - } - else - { - drawlist->AddLine({ (float)polyints[i], (float)y }, - { (float)polyints[i + 1], (float)y }, _fill, _thickness); - } - } - } - delete[] polyints; - } - // TODO: Find a way to store lines and only calc new fill lines when dirty similar to ellipse - drawlist->AddPolyline(finalpoints.data(), (int)finalpoints.size(), _color, false, _thickness); -} - -void mvDrawPolygon::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _points = ToVectVec4(PyTuple_GetItem(dict, 0)); - for (auto& point : _points) - point.w = 1.0f; -} - -void mvDrawPolygon::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "points")) _points = ToVectVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - - for (auto& point : _points) - point.w = 1.0f; - -} - -void mvDrawPolygon::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "points", mvPyObject(ToPyList(_points))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); - -} - -void mvDrawPolyline::draw(ImDrawList* drawlist, float x, float y) -{ - - mvVec4 start = { x, y }; - - std::vector points = _points; - std::vector finalpoints; - finalpoints.reserve(_points.size()); - - for (auto& point : points) - point = drawInfo->transform * point; - - if (drawInfo->perspectiveDivide) - { - - for (auto& point : points) - { - point.x = point.x / point.w; - point.x = point.x / point.w; - point.x = point.x / point.w; - } - } - - if (drawInfo->depthClipping) - { - for (auto& point : points) - if (mvClipPoint(drawInfo->clipViewport, point)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - for (auto& point : points) - { - ImVec2 impoint = ImPlot::PlotToPixels(point); - point.x = impoint.x; - point.y = impoint.y; - finalpoints.push_back(impoint); - } - - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddPolyline(finalpoints.data(), (int)finalpoints.size(), _color, - _closed, Mx * _thickness); - } - else - { - for (auto& point : points) - { - point = point + start; - finalpoints.push_back(ImVec2{ point.x, point.y }); - } - - drawlist->AddPolyline(finalpoints.data(), (int)finalpoints.size(), _color, - _closed, _thickness); - } - - -} - -void mvDrawPolyline::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _points = ToVectVec4(PyTuple_GetItem(dict, 0)); -} - -void mvDrawPolyline::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "points")) _points = ToVectVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "closed")) _closed = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - - for (auto& point : _points) - point.w = 1.0f; -} - -void mvDrawPolyline::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "points", mvPyObject(ToPyList(_points))); - PyDict_SetItemString(dict, "closed", mvPyObject(ToPyBool(_closed))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); -} - -void mvDrawQuad::draw(ImDrawList* drawlist, float x, float y) -{ - - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - mvVec4 tp3 = drawInfo->transform * _p3; - mvVec4 tp4 = drawInfo->transform * _p4; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tp3.x = tp3.x / tp3.w; - tp4.x = tp4.x / tp4.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tp3.y = tp3.y / tp3.w; - tp4.y = tp4.y / tp4.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tp3.z = tp3.z / tp3.w; - tp4.z = tp4.z / tp4.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tp3)) return; - if (mvClipPoint(drawInfo->clipViewport, tp4)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - if (_fill.r >= 0.0f) - drawlist->AddQuadFilled(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), - ImPlot::PlotToPixels(tp4), _fill); - drawlist->AddQuad(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), - ImPlot::PlotToPixels(tp4), _color, Mx * _thickness); - } - else - { - mvVec2 start = { x, y }; - if (_fill.r >= 0.0f) - drawlist->AddQuadFilled(tp1 + start, tp2 + start, tp3 + start, tp4 + start, _fill); - drawlist->AddQuad(tp1 + start, tp2 + start, tp3 + start, tp4 + start, _color, _thickness); - } -} - -void mvDrawQuad::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p3 = ToVec4(PyTuple_GetItem(dict, 2)); - _p4 = ToVec4(PyTuple_GetItem(dict, 3)); - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; - _p4.w = 1.0f; -} - -void mvDrawQuad::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p3")) _p3 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p4")) _p4 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; - _p4.w = 1.0f; - - -} - -void mvDrawQuad::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "p3", mvPyObject(ToPyPair(_p3.x, _p3.y))); - PyDict_SetItemString(dict, "p4", mvPyObject(ToPyPair(_p4.x, _p4.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); -} - -void mvDrawRect::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tpmin = drawInfo->transform * _pmin; - mvVec4 tpmax = drawInfo->transform * _pmax; - - if (drawInfo->perspectiveDivide) - { - tpmin.x = tpmin.x / tpmin.w; - tpmax.x = tpmax.x / tpmax.w; - - tpmin.y = tpmin.y / tpmin.w; - tpmax.y = tpmax.y / tpmax.w; - - tpmin.z = tpmin.z / tpmin.w; - tpmax.z = tpmax.z / tpmax.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tpmin)) return; - if (mvClipPoint(drawInfo->clipViewport, tpmax)) return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - if (_multicolor) - drawlist->AddRectFilledMultiColor(ImPlot::PlotToPixels(tpmin), ImPlot::PlotToPixels(tpmax), _color_bottom_right, _color_bottom_left, _color_upper_left, _color_upper_right); - else if (_fill.r >= 0.0f) - drawlist->AddRectFilled(ImPlot::PlotToPixels(tpmin), ImPlot::PlotToPixels(tpmax), _fill, Mx * _rounding, ImDrawFlags_RoundCornersAll); - drawlist->AddRect(ImPlot::PlotToPixels(tpmin), ImPlot::PlotToPixels(tpmax), _color, Mx * _rounding, ImDrawFlags_RoundCornersAll, Mx * _thickness); - } - else - { - mvVec2 start = { x, y }; - if (_multicolor) - drawlist->AddRectFilledMultiColor(tpmin + start, tpmax + start, _color_bottom_right, _color_bottom_left, _color_upper_left, _color_upper_right); - else if (_fill.r >= 0.0f) - drawlist->AddRectFilled(tpmin + start, tpmax + start, _fill, _rounding, ImDrawFlags_RoundCornersAll); - drawlist->AddRect(tpmin + start, tpmax + start, _color, _rounding, ImDrawFlags_RoundCornersAll, _thickness); - } -} - -void mvDrawRect::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _pmin = ToVec4(PyTuple_GetItem(dict, 0)); - _pmax = ToVec4(PyTuple_GetItem(dict, 1)); - _pmin.w = 1.0f; - _pmax.w = 1.0f; -} - -void mvDrawRect::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "pmax")) _pmax = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "pmin")) _pmin = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "color_upper_left")) _color_upper_left = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "color_upper_right")) _color_upper_right = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "color_bottom_left")) _color_bottom_left = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "color_bottom_right")) _color_bottom_right = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "rounding")) _rounding = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "multicolor")) _multicolor = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "corner_colors")) - { - if (item != Py_None) - { - if (PyTuple_Check(item)) - { - if (PyTuple_Size(item) != 4) - mvThrowPythonError(mvErrorCode::mvNone, "The corner_colors parm on draw_rectangle must contain 4 colors."); - else - { - // Note: the variables are named incorrectly, e.g. _color_bottom_right - // actually controls upper-left corner. That's how old Python parms - // were named so we're keeping the names for a while until we drop the - // old parms altogether (if this ever happens). - // For now, we're just filling them in appropriate order. - _color_bottom_right = ToColor(PyTuple_GetItem(item, 0)); - _color_bottom_left = ToColor(PyTuple_GetItem(item, 1)); - _color_upper_left = ToColor(PyTuple_GetItem(item, 2)); - _color_upper_right = ToColor(PyTuple_GetItem(item, 3)); - } - } - else if (PyList_Check(item)) - { - if (PyList_Size(item) != 4) - mvThrowPythonError(mvErrorCode::mvNone, "The corner_colors parm on draw_rectangle must contain 4 colors."); - else - { - _color_bottom_right = ToColor(PyList_GetItem(item, 0)); - _color_bottom_left = ToColor(PyList_GetItem(item, 1)); - _color_upper_left = ToColor(PyList_GetItem(item, 2)); - _color_upper_right = ToColor(PyList_GetItem(item, 3)); - } - } - } - } - - _pmin.w = 1.0f; - _pmax.w = 1.0f; - - if (_multicolor) - _rounding = 0.0f; -} - -void mvDrawRect::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "pmax", mvPyObject(ToPyPair(_pmax.x, _pmax.y))); - PyDict_SetItemString(dict, "pmin", mvPyObject(ToPyPair(_pmin.x, _pmin.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "rounding", mvPyObject(ToPyFloat(_rounding))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); -} - -void mvDrawText::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tpos = drawInfo->transform * _pos; - - if (drawInfo->perspectiveDivide) - { - tpos.x = tpos.x / tpos.w; - tpos.y = tpos.y / tpos.w; - tpos.z = tpos.z / tpos.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tpos)) return; - } - - ImFont* fontptr = ImGui::GetFont(); - if (font) - fontptr = static_cast(font.get())->getFontPtr(); - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - drawlist->AddText(fontptr, Mx * (float)_size, ImPlot::PlotToPixels(tpos), _color, _text.c_str()); - } - else - { - mvVec2 start = { x, y }; - drawlist->AddText(fontptr, (float)_size, tpos + start, _color, _text.c_str()); - } -} - -void mvDrawText::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _pos = ToVec4(PyTuple_GetItem(dict, 0)); - _pos.w = 1.0f; - _text = ToString(PyTuple_GetItem(dict, 1)); - -} - -void mvDrawText::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "text")) _text = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "pos")) _pos = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "size")) _size = ToFloat(item); - _pos.w = 1.0f; - -} - -void mvDrawText::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "text", mvPyObject(ToPyString(_text))); - PyDict_SetItemString(dict, "pos", mvPyObject(ToPyPair(_pos.x, _pos.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "size", mvPyObject(ToPyFloat(_size))); -} - -void mvDrawTriangle::draw(ImDrawList* drawlist, float x, float y) -{ - mvVec4 tp1 = drawInfo->transform * _p1; - mvVec4 tp2 = drawInfo->transform * _p2; - mvVec4 tp3 = drawInfo->transform * _p3; - - if (drawInfo->perspectiveDivide) - { - tp1.x = tp1.x / tp1.w; - tp2.x = tp2.x / tp2.w; - tp3.x = tp3.x / tp3.w; - - tp1.y = tp1.y / tp1.w; - tp2.y = tp2.y / tp2.w; - tp3.y = tp3.y / tp3.w; - - tp1.z = tp1.z / tp1.w; - tp2.z = tp2.z / tp2.w; - tp3.z = tp3.z / tp3.w; - } - - if (drawInfo->depthClipping) - { - if (mvClipPoint(drawInfo->clipViewport, tp1)) return; - if (mvClipPoint(drawInfo->clipViewport, tp2)) return; - if (mvClipPoint(drawInfo->clipViewport, tp3)) return; - } - - if (drawInfo->cullMode == 1) // backface - { - mvVec3 n = mvCross(tp2 - tp1, tp3 - tp2); - - if (n.z < 0) - return; - } - - else if (drawInfo->cullMode == 2) // frontface - { - mvVec3 n = mvCross(tp2 - tp1, tp3 - tp2); - - if (n.z > 0) - return; - } - - if (ImPlot::GetCurrentContext()->CurrentPlot) - { - float Mx = (float)(ImPlot::GetPlotSize().x / ImPlot::GetPlotLimits().Size().x); - if (_fill.r >= 0.0f) - { - drawlist->AddTriangleFilled(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), - _fill); - } - drawlist->AddTriangle(ImPlot::PlotToPixels(tp1), ImPlot::PlotToPixels(tp2), ImPlot::PlotToPixels(tp3), - _color, Mx * _thickness); - } - else - { - mvVec2 start = { x, y }; - if (_fill.r >= 0.0f) - drawlist->AddTriangleFilled(tp1 + start, tp2 + start, tp3 + start, _fill); - drawlist->AddTriangle(tp1 + start, tp2 + start, tp3 + start, _color, _thickness); - } -} - -void mvDrawTriangle::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _p1 = ToVec4(PyTuple_GetItem(dict, 0)); - _p2 = ToVec4(PyTuple_GetItem(dict, 1)); - _p3 = ToVec4(PyTuple_GetItem(dict, 2)); - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; -} - -void mvDrawTriangle::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "p1")) _p1 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p2")) _p2 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "p3")) _p3 = ToVec4(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "fill")) _fill = ToColor(item); - if (PyObject* item = PyDict_GetItemString(dict, "thickness")) _thickness = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "cull_mode")) drawInfo->cullMode = ToInt(item); - - _p1.w = 1.0f; - _p2.w = 1.0f; - _p3.w = 1.0f; -} - -void mvDrawTriangle::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "p1", mvPyObject(ToPyPair(_p1.x, _p1.y))); - PyDict_SetItemString(dict, "p2", mvPyObject(ToPyPair(_p2.x, _p2.y))); - PyDict_SetItemString(dict, "p3", mvPyObject(ToPyPair(_p3.x, _p3.y))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "fill", mvPyObject(ToPyColor(_fill))); - PyDict_SetItemString(dict, "thickness", mvPyObject(ToPyFloat(_thickness))); -} - -void mvViewportDrawlist::draw(ImDrawList* drawlist, float x, float y) -{ - - ImDrawList* internal_drawlist = _front ? ImGui::GetForegroundDrawList() : ImGui::GetBackgroundDrawList(); - - for (auto& item : childslots[2]) - { - // skip item if it's not shown - if (!item->config.show) - continue; - - item->draw(internal_drawlist, 0.0f, 0.0f); - - UpdateAppItemState(item->state); - } - -} - -void mvViewportDrawlist::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "front")) _front = ToBool(item); - -} - -void mvViewportDrawlist::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "front", mvPyObject(ToPyBool(_front))); -} \ No newline at end of file diff --git a/src/mvDrawings.h b/src/mvDrawings.h deleted file mode 100644 index 8b9c0ef54..000000000 --- a/src/mvDrawings.h +++ /dev/null @@ -1,408 +0,0 @@ -#pragma once - -#include "mvItemRegistry.h" - -class mvViewportDrawlist : public mvAppItem -{ - -public: - - explicit mvViewportDrawlist(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - bool _front = true; - -}; - -class mvDrawlist : public mvAppItem -{ - -public: - - explicit mvDrawlist(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - float _startx = 0.0f; - float _starty = 0.0f; - -}; - -class mvDrawNode : public mvAppItem -{ - -public: - - explicit mvDrawNode(mvUUID uuid) : mvAppItem(uuid) {} - ~mvDrawNode(); - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvDrawLayer : public mvAppItem -{ - -public: - - explicit mvDrawLayer(mvUUID uuid) : mvAppItem(uuid) {} - ~mvDrawLayer(); - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -}; - -class mvDrawArrow : public mvAppItem -{ - -public: - - explicit mvDrawArrow(mvUUID uuid); - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - void updatePoints(); - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color; - float _thickness = 1.0f; - float _size = 4; - mvVec4 _points[3]; - -}; - -class mvDrawBezierCubic : public mvAppItem -{ - -public: - - explicit mvDrawBezierCubic(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p3 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p4 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color; - float _thickness = 0.0f; - int _segments = 0; - -}; - -class mvDrawBezierQuadratic : public mvAppItem -{ - -public: - - explicit mvDrawBezierQuadratic(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p3 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color; - float _thickness = 0.0f; - int _segments = 0; - -}; - -class mvDrawCircle : public mvAppItem -{ - -public: - - explicit mvDrawCircle(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - mvVec4 _center = { 0.0f, 0.0f, 0.0f, 1.0f }; - float _radius = 1.0f; - int _segments = 0; - mvColor _color; - mvColor _fill; - float _thickness = 1.0f; - -}; - -class mvDrawEllipse : public mvAppItem -{ - -public: - - explicit mvDrawEllipse(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - mvVec4 _pmin = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _pmax = { 1.0f, 1.0f, 0.0f, 1.0f }; - int _segments = 0; - mvColor _color; - mvColor _fill; - float _thickness = 1.0f; - std::vector _points; - bool _dirty = true; - -}; - -class mvDrawImage : public mvAppItem -{ - -public: - - explicit mvDrawImage(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - - mvVec4 _pmax = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _pmin = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec2 _uv_min = { 0.0f, 0.0f }; - mvVec2 _uv_max = { 1.0f, 1.0f }; - mvColor _color = mvImGuiCol_Text; - - // pointer to existing item or internal - std::shared_ptr _texture = nullptr; - -}; - -class mvDrawImageQuad : public mvAppItem -{ - -public: - - explicit mvDrawImageQuad(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p3 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p4 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec2 _uv1 = { 0.0f, 0.0f }; - mvVec2 _uv2 = { 1.0f, 0.0f }; - mvVec2 _uv3 = { 1.0f, 1.0f }; - mvVec2 _uv4 = { 0.0f, 1.0f }; - mvColor _color = mvColor(255, 255, 255, 255); - - // pointer to existing item or internal - std::shared_ptr _texture = nullptr; - -}; - -class mvDrawLine : public mvAppItem -{ - -public: - - explicit mvDrawLine(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color = { 1.0f, 1.0f, 1.0f, 1.0f }; - float _thickness = 1.0f; - -}; - -class mvDrawPolygon : public mvAppItem -{ - -public: - - explicit mvDrawPolygon(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - std::vector _points; - mvColor _color; - mvColor _fill; - float _thickness = 1.0f; - -}; - -class mvDrawPolyline : public mvAppItem -{ - -public: - - explicit mvDrawPolyline(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - -private: - - std::vector _points; - mvColor _color; - bool _closed = false; - float _thickness = 1.0f; - -}; - -class mvDrawQuad : public mvAppItem -{ - -public: - - explicit mvDrawQuad(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p3 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p4 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color; - mvColor _fill; - float _thickness = 1.0f; - -}; - -class mvDrawRect : public mvAppItem -{ - -public: - - explicit mvDrawRect(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - mvVec4 _pmax = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _pmin = { 1.0f, 0.0f, 0.0f, 1.0f }; - float _rounding = 0.0f; - mvColor _color; - mvColor _color_upper_left; - mvColor _color_upper_right; - mvColor _color_bottom_left; - mvColor _color_bottom_right; - mvColor _fill; - float _thickness = 1.0f; - bool _multicolor = false; -}; - -class mvDrawText : public mvAppItem -{ - -public: - - explicit mvDrawText(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - mvVec4 _pos = { 0.0f, 0.0f, 0.0f, 1.0f }; - std::string _text; - mvColor _color; - float _size = 1.0f; -}; - -class mvDrawTriangle : public mvAppItem -{ - -public: - - explicit mvDrawTriangle(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - - mvVec4 _p1 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p2 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvVec4 _p3 = { 0.0f, 0.0f, 0.0f, 1.0f }; - mvColor _color; - mvColor _fill; - float _thickness = 1.0f; - -}; \ No newline at end of file diff --git a/src/mvFileDialog.cpp b/src/mvFileDialog.cpp deleted file mode 100644 index 1f238cbbf..000000000 --- a/src/mvFileDialog.cpp +++ /dev/null @@ -1,228 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvFileDialog.h" - -#include "mvFileExtension.h" -#include "mvItemRegistry.h" - -static void Panel(const char* vFilter, IGFDUserDatas vUserDatas, bool* vCantContinue) -{ -static_cast(vUserDatas)->drawPanel(); -*vCantContinue = static_cast(vUserDatas)->getContinueValue(); -} - -mvFileDialog::mvFileDialog(mvUUID uuid) - : - mvAppItem(uuid) -{ - *_value = true; - config.width = 500; - config.height = 500; -} - -ImGuiFileDialog& mvFileDialog::getDialog() -{ - return _instance; -} - -void mvFileDialog::drawPanel() -{ - for (auto& item : childslots[1]) - item->draw(ImGui::GetWindowDrawList(), ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - -} - -void mvFileDialog::draw(ImDrawList* drawlist, float x, float y) -{ - ScopedID id(uuid); - - if (!config.show) - return; - - // extensions - if (_dirtySettings) - { - _filters.clear(); - for (auto& item : childslots[0]) - { - item->draw(drawlist, x, y); - _filters.append(static_cast(item.get())->_extension); - _filters.append(","); - } - - _dirtySettings = false; - } - - // remap selectable to FrameBgActive - ImGuiStyle* style = &ImGui::GetStyle(); - ImGui::PushStyleColor(ImGuiCol_Header, style->Colors[ImGuiCol_FrameBgActive]); - - // without panel - if (childslots[1].empty()) - { - if (_modal) - _instance.OpenModal(info.internalLabel.c_str(), info.internalLabel.c_str(), _directory ? nullptr : _filters.c_str(), _defaultPath, _defaultFilename, _fileCount); - else - _instance.OpenDialog(info.internalLabel.c_str(), info.internalLabel.c_str(), _directory ? nullptr : _filters.c_str(), _defaultPath, _defaultFilename, _fileCount); - } - - // with panel - else - { - - if (_modal) - _instance.OpenModal(info.internalLabel.c_str(), info.internalLabel.c_str(), _directory ? nullptr : _filters.c_str(), _defaultPath, _defaultFilename, - std::bind(&Panel, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), 250.0f, _fileCount, IGFDUserDatas(this)); - else - _instance.OpenDialog(info.internalLabel.c_str(), info.internalLabel.c_str(), _directory ? nullptr : _filters.c_str(), _defaultPath, _defaultFilename, - std::bind(&Panel, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), 250.0f, _fileCount, IGFDUserDatas(this)); - } - - { - //mvFontScope fscope(this); - - if (info.dirtyPos) - { - ImGui::SetNextWindowPos(state.pos); - info.dirtyPos = false; - } - - if (info.dirty_size) - { - ImGui::SetNextWindowSize(ImVec2((float)config.width, (float)config.height)); - info.dirty_size = false; - } - - // display - if (_instance.IsOpened()) - { - state.rectSize = { _instance.windowSizeDPG.x, _instance.windowSizeDPG.y }; - } - - if (_instance.Display(info.internalLabel, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings, _min_size, _max_size)) - { - - // action if OK clicked or if cancel clicked and cancel callback provided - if (_instance.IsOk() || _cancelCallback) - { - submitCallbackEx( - _instance.IsOk()? config.callback : _cancelCallback, - // We're capturing a weak reference to mvFileDialog, so that the dialog can - // be safely deleted even if there's a callback still waiting in the queue. - [weakThis=weak_from_this()] () -> PyObject* - { - auto liveThis = weakThis.lock(); - if (liveThis) - { - mvFileDialog* dlg = static_cast(liveThis.get()); - return dlg->getInfoDict(); - } - return nullptr; - } - ); - } - - // close - _instance.Close(); - config.show = false; - } - } - - ImGui::PopStyleColor(); -} - -PyObject* mvFileDialog::getPyValue() -{ - return ToPyBool(*_value); -} - -void mvFileDialog::setPyValue(PyObject* value) -{ - *_value = ToBool(value); -} - -void mvFileDialog::setDataSource(mvUUID dataSource) -{ - if (dataSource == config.source) return; - config.source = dataSource; - - mvAppItem* item = GetItem((*GContext->itemRegistry), dataSource); - if (!item) - { - mvThrowPythonError(mvErrorCode::mvSourceNotFound, "set_value", - "Source item not found: " + std::to_string(dataSource), this); - return; - } - if (DearPyGui::GetEntityValueType(item->type) != DearPyGui::GetEntityValueType(type)) - { - mvThrowPythonError(mvErrorCode::mvSourceNotCompatible, "set_value", - "Values types do not match: " + std::to_string(dataSource), this); - return; - } - _value = *static_cast*>(item->getValue()); -} - -void mvFileDialog::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "file_count")) _fileCount = ToInt(item); - if (PyObject* item = PyDict_GetItemString(dict, "default_filename")) _defaultFilename = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "default_path")) _defaultPath = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "modal")) _modal = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "directory_selector")) _directory = ToBool(item); - - if (PyObject* item = PyDict_GetItemString(dict, "min_size")) - { - auto min_size = ToIntVect(item); - _min_size = { (float)min_size[0], (float)min_size[1] }; - } - - if (PyObject* item = PyDict_GetItemString(dict, "max_size")) - { - auto max_size = ToIntVect(item); - _max_size = { (float)max_size[0], (float)max_size[1] }; - } - - if (PyObject* item = PyDict_GetItemString(dict, "cancel_callback")) - { - _cancelCallback = mvPyObject(item == Py_None? nullptr : item, true); - } - -} - -void mvFileDialog::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "file_count", mvPyObject(ToPyInt(_fileCount))); - PyDict_SetItemString(dict, "default_filename", mvPyObject(ToPyString(_defaultFilename))); - PyDict_SetItemString(dict, "default_path", mvPyObject(ToPyString(_defaultPath))); - PyDict_SetItemString(dict, "modal", mvPyObject(ToPyBool(_modal))); - PyDict_SetItemString(dict, "directory_selector", mvPyObject(ToPyBool(_directory))); -} - -PyObject* mvFileDialog::getInfoDict() -{ - PyObject* dict = PyDict_New(); - - PyDict_SetItemString(dict, "file_path_name", mvPyObject(ToPyString(_instance.GetFilePathName()))); - PyDict_SetItemString(dict, "file_name", mvPyObject(ToPyString(_instance.GetCurrentFileName()))); - //PyDict_SetItemString(dict, "file_name_buffer", mvPyObject(ToPyString(_instance.FileNameBuffer))); - PyDict_SetItemString(dict, "current_path", mvPyObject(ToPyString(_instance.GetCurrentPath()))); - PyDict_SetItemString(dict, "current_filter", mvPyObject(ToPyString(_instance.GetCurrentFilter()))); - PyDict_SetItemString(dict, "min_size", mvPyObject(ToPyPair(_min_size.x, _min_size.y))); - PyDict_SetItemString(dict, "max_size", mvPyObject(ToPyPair(_max_size.x, _max_size.y))); - - auto selections = _instance.GetSelection(); - - PyObject* sel = PyDict_New(); - for(auto& item : selections) - PyDict_SetItemString(sel, item.first.c_str(), mvPyObject(ToPyString(item.second))); - PyDict_SetItemString(dict, "selections", mvPyObject((sel))); - - return dict; -} diff --git a/src/mvFileDialog.h b/src/mvFileDialog.h deleted file mode 100644 index 547c22021..000000000 --- a/src/mvFileDialog.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include "mvItemRegistry.h" -#include "mvContext.h" -#include "mvItemRegistry.h" - -#pragma warning(push, 0) -#include -#pragma warning(pop) - -class mvFileDialog final : public mvAppItem -{ - -public: - - explicit mvFileDialog(mvUUID uuid); - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - void drawPanel(); - - // values - void setDataSource(mvUUID dataSource) override; - void* getValue() override { return &_value; } - PyObject* getPyValue() override; - void setPyValue(PyObject* value) override; - - ImGuiFileDialog& getDialog(); - void markDirty() { _dirtySettings = true; } - PyObject* getInfoDict(); - bool getContinueValue() const { return *_value; } - -public: - - std::shared_ptr _value = std::make_shared(false); - bool _disabled_value = false; - ImGuiFileDialog _instance; - bool _dirtySettings = true; - std::string _filters; - std::string _defaultPath; - std::string _defaultFilename = "."; - int _fileCount = 0; - bool _modal = false; - bool _directory = false; - mvVec2 _min_size = { 100.0f, 100.0f }; - mvVec2 _max_size = { 30000.0f, 30000.0f }; - mvPyObject _cancelCallback = nullptr; -}; \ No newline at end of file diff --git a/src/mvFileExtension.cpp b/src/mvFileExtension.cpp deleted file mode 100644 index 547a381ba..000000000 --- a/src/mvFileExtension.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvFileExtension.h" - -#include "mvFileDialog.h" -#include "mvItemRegistry.h" - -void mvFileExtension::draw(ImDrawList* drawlist, float x, float y) -{ - IGFD::FileExtentionInfos info; - info.icon = _customText; - if (_color.r >= 0) - info.color = _color.toVec4(); - else - info.color = { 1.0f, 1.0f, 1.0f, 1.0f }; - static_cast(this->info.parentPtr)->getDialog().SetExtentionInfos(_extension.c_str(), info); -} - -void mvFileExtension::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - _extension = ToString(PyTuple_GetItem(dict, 0)); - -} - -void mvFileExtension::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "custom_text"))_customText = ToString(item); - if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item); - - if (info.parentPtr) - static_cast(info.parentPtr)->markDirty(); -} - -void mvFileExtension::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "custom_text", mvPyObject(ToPyString(_customText))); - PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color))); - PyDict_SetItemString(dict, "extension", mvPyObject(ToPyString(_extension)) ); - -} \ No newline at end of file diff --git a/src/mvFileExtension.h b/src/mvFileExtension.h deleted file mode 100644 index 1a6c54be0..000000000 --- a/src/mvFileExtension.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "mvAppItem.h" -#include "mvContext.h" -#include "mvItemRegistry.h" - -class mvFileExtension : public mvAppItem -{ - -public: - - explicit mvFileExtension(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* args) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - - const std::string& getFilter() { return _extension; } - -public: - - std::string _extension; - std::string _customText; - mvColor _color = {-1.0f, 0.0f, 0.0f, 1.0f}; -}; \ No newline at end of file diff --git a/src/mvFontItems.cpp b/src/mvFontItems.cpp deleted file mode 100644 index d38d863ff..000000000 --- a/src/mvFontItems.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvFontItems.h" - -#include "mvTextureItems.h" - -void mvFontRegistry::customAction(void* data) -{ - if (!_dirty || !config.show) - return; - - for (auto& item : childslots[1]) - item->customAction(nullptr); - - _dirty = false; -} - -void mvFontRegistry::draw(ImDrawList* drawlist, float x, float y) -{ - for (auto& item : childslots[1]) - { - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - } -} - -void mvCharRemap::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _source = ToInt(PyTuple_GetItem(dict, 0)); - _target = ToInt(PyTuple_GetItem(dict, 1)); -} - -mvFont::~mvFont() -{ - if (_fontPtr) - { - mvSubmitTask([=]() { - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->RemoveFont(_fontPtr); - }, true); - } -} - -void mvFont::customAction(void* data) -{ - // If add_font arguments are bad, quit. - if (!state.ok) - return; - // If the font has been already loaded, nothing to do here. - if (_fontPtr) - return; - - ImGuiIO& io = ImGui::GetIO(); - - ImFontConfig cfg; - cfg.PixelSnapH = _pixelSnapH; - cfg.PixelSnapV = _pixelSnapV; - _fontPtr = io.Fonts->AddFontFromFileTTF(_file.c_str(), _size, &cfg); - - if (_fontPtr == nullptr) - { - state.ok = false; - mvThrowPythonError(mvErrorCode::mvNone, "Font file could not be found"); - return; - } - - // check ranges - for (const auto& range : childslots[1]) - { - - if (range->type == mvAppItemType::mvCharRemap) - { - const auto rangePtr = static_cast(range.get()); - - _fontPtr->AddRemapChar(rangePtr->getSourceChar(), rangePtr->getTargetChar()); - } - - } -} - -void mvFont::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _file = ToString(PyTuple_GetItem(dict, 0)); - std::ifstream ifile; - ifile.open(_file); - if (ifile) - ifile.close(); - else - { - state.ok = false; - mvThrowPythonError(mvErrorCode::mvNone, "Font file could not be found"); - } - - _size = ToFloat(PyTuple_GetItem(dict, 1)); - -} - -void mvFont::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "size")) _size = ToFloat(item); - if (PyObject* item = PyDict_GetItemString(dict, "pixel_snapH")) _pixelSnapH = ToBool(item); - if (PyObject* item = PyDict_GetItemString(dict, "pixel_snapV")) _pixelSnapV = ToBool(item); -} - -void mvFont::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "file", mvPyObject(ToPyString(_file))); - PyDict_SetItemString(dict, "size", mvPyObject(ToPyFloat(_size))); - PyDict_SetItemString(dict, "pixel_snapH", mvPyObject(ToPyBool(_pixelSnapH))); - PyDict_SetItemString(dict, "pixel_snapV", mvPyObject(ToPyBool(_pixelSnapV))); -} diff --git a/src/mvFontItems.h b/src/mvFontItems.h deleted file mode 100644 index 3406fbe11..000000000 --- a/src/mvFontItems.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include -#include "mvItemRegistry.h" - -class mvFontRegistry : public mvAppItem -{ - -public: - - explicit mvFontRegistry(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override; - void customAction(void* data = nullptr) override; - void onChildAdd(std::shared_ptr item) { _dirty = true; } - -private: - - bool _dirty = true; - -}; - -class mvCharRemap : public mvAppItem -{ - -public: - - explicit mvCharRemap(mvUUID uuid) : mvAppItem(uuid) {} - - void draw(ImDrawList* drawlist, float x, float y) override {} - void handleSpecificRequiredArgs(PyObject* dict) override; - int getSourceChar() const { return _source; } - int getTargetChar() const { return _target; } - -private: - - int _source = 0; - int _target = 0; - -}; - -class mvFont : public mvAppItem -{ - -public: - - explicit mvFont(mvUUID uuid) : mvAppItem(uuid) {} - ~mvFont(); - - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - void handleSpecificRequiredArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - ImFont* getFontPtr() { return _fontPtr; } - float getSize() { return _size; } - void pushFont() { ImGui::PushFont(_fontPtr, _size); } - -public: - - // config - std::string _file; - float _size = 13.0f; - bool _pixelSnapH = false; - bool _pixelSnapV = false; - - // finalized - ImFont* _fontPtr = nullptr; - -}; diff --git a/src/mvFontManager.cpp b/src/mvFontManager.cpp deleted file mode 100644 index b4e0fea4f..000000000 --- a/src/mvFontManager.cpp +++ /dev/null @@ -1,256 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvFontManager.h" - -#include "mvFontItems.h" -#include "mvContext.h" -#include "mvAppItem.h" -#include "mvCore.h" -#include "mvItemRegistry.h" -#include "mvViewport.h" -#include "mvTextureItems.h" - -#include -#include -#include -#include -#include -#include -#include - -#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) -#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) - -// Helper to display a little (?) mark which shows a tooltip when hovered. -// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) -static void -HelpMarker(const char* desc) -{ -ImGui::TextDisabled("(?)"); -if (ImGui::IsItemHovered()) -{ - if(ImGui::BeginTooltip()) { - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); - ImGui::TextUnformatted(desc); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } -} -} - -mvFontManager::mvFontManager() -{ - m_windowflags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_HorizontalScrollbar; -} - -// [Internal] Display details for a single font, called by ShowStyleEditor(). -void -mvFontManager::drawFontNode(ImFont* font) -{ - ImGuiContext& g = *GImGui; - ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; - ImFontAtlas* atlas = font->OwnerAtlas; - bool opened = ImGui::TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size); - - // Display preview text - if (!opened) - ImGui::Indent(); - ImGui::Indent(); - if (cfg->ShowFontPreview) - { - ImGui::PushFont(font, 0.0f); - ImGui::Text("The quick brown fox jumps over the lazy dog"); - ImGui::PopFont(); - } - if (!opened) - { - ImGui::Unindent(); - ImGui::Unindent(); - return; - } - if (ImGui::SmallButton("Set as default")) - { - _updateDefault = false; - _defaultFont.reset(); - ImGui::GetIO().FontDefault = font; - } - ImGui::SameLine(); - if (ImGui::SmallButton("Clear bakes")) - ImFontAtlasFontDiscardBakes(atlas, font, 0); - ImGui::SameLine(); - if (ImGui::SmallButton("Clear unused")) - ImFontAtlasFontDiscardBakes(atlas, font, 2); - - // Display details - char c_str[5]; - ImTextCharToUtf8(c_str, font->FallbackChar); - ImGui::Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar); - ImTextCharToUtf8(c_str, font->EllipsisChar); - ImGui::Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar); - - for (int src_n = 0; src_n < font->Sources.Size; src_n++) - { - ImFontConfig* src = font->Sources[src_n]; - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (ImGui::TreeNodeEx(src, ImGuiTreeNodeFlags_Leaf|ImGuiTreeNodeFlags_Bullet, - "Input %d: \'%s\' [%d], Loader: '%s',\nOversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", - src_n, src->Name, src->FontNo, loader->Name ? loader->Name : "N/A", - src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) - { - ImGui::TreePop(); - } - } - - // TODO: add Glyphs Overlap Detection tool in future - - // Display all glyphs of the fonts in separate pages of 256 characters - for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) - { - ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; - if (baked->OwnerFont != font) - continue; - ImGui::PushID(baked_n); - if (ImGui::TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) - { - if (ImGui::SmallButton("Load all")) - for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) - baked->FindGlyph((ImWchar)base); - - const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface); - ImGui::Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent); - ImGui::Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt); - for (int src_n = 0; src_n < font->Sources.Size; src_n++) - { - ImFontConfig* src = font->Sources[src_n]; - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); - ImGui::BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", - src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); - } - - ImGui::DebugNodeFontGlyphesForSrcMask(font, baked, ~0); - ImGui::TreePop(); - } - ImGui::PopID(); - } - ImGui::TreePop(); - ImGui::Unindent(); -} - -// Demo helper function to select among loaded fonts. -// Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one. -void -mvFontManager::drawFontSelector(const char* label) -{ -ImGuiIO& io = ImGui::GetIO(); -ImFont* font_current = ImGui::GetFont(); -if (ImGui::BeginCombo(label, font_current->GetDebugName())) -{ - for (int n = 0; n < io.Fonts->Fonts.Size; n++) - { - ImFont* font = io.Fonts->Fonts[n]; - ImGui::PushID((void*)font); - if (ImGui::Selectable(font->GetDebugName(), font == font_current)) - { - _updateDefault = false; - _defaultFont.reset(); - io.FontDefault = font; - } - ImGui::PopID(); - } - ImGui::EndCombo(); -} -} - -void -mvFontManager::updateAtlas() -{ - ImGuiIO& io = ImGui::GetIO(); - - // See if the built-in ProggyClean font is already there. We need it just in case - // all the DPG fonts (mvFont) are deleted and ImGui needs to render a frame. - if (io.Fonts->Sources.Size == 0) - io.Fonts->AddFontDefault(); - - for (auto& root : GContext->itemRegistry->fontRegistryRoots) - { - // Tell the font registry to update any fonts that need it - root->customAction(nullptr); - } - - // Reset the current font so that NewFrame can pick up changes immediately - if (_updateDefault) - { - ImGuiContext& g = *GImGui; - auto item = _defaultFont.lock(); - IM_ASSERT(item->type == mvAppItemType::mvFont && "The default font must be a mvFont."); - if (item) - { - auto font = static_cast(item.get()); - io.FontDefault = font->getFontPtr(); - g.Style.FontSizeBase = font->getSize(); - } - else - { - io.FontDefault = nullptr; - g.Style.FontSizeBase = 0; - } - } -} - -void -mvFontManager::drawWidgets() -{ - - drawFontSelector("Fonts##Selector"); - - ImGuiIO& io = ImGui::GetIO(); - ImFontAtlas* atlas = io.Fonts; - ImGui::PushItemWidth(120); - for (int i = 0; i < atlas->Fonts.Size; i++) - { - ImFont* font = atlas->Fonts[i]; - ImGui::PushID(font); - drawFontNode(font); - ImGui::PopID(); - } - if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexData->Width, atlas->TexData->Height)) - { - if (ImGui::Button("Compact")) - atlas->CompactCache(); - ImGui::SameLine(); - if (ImGui::Button("Grow")) - ImFontAtlasTextureGrow(atlas); - ImGui::SameLine(); - if (ImGui::Button("Clear All")) - ImFontAtlasBuildClear(atlas); - ImGui::SetItemTooltip("Destroy cache and custom rectangles."); - - ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); - ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f); - ImGui::PushStyleColor(ImGuiCol_Border, border_col); - ImGui::ImageWithBg(atlas->TexRef, ImVec2((float)atlas->TexData->Width, (float)atlas->TexData->Height), ImVec2(0, 0), ImVec2(1, 1), ImVec4(0, 0, 0, 0), tint_col); - ImGui::PopStyleColor(); - ImGui::PopStyleVar(); - ImGui::TreePop(); - } - - // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. - // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). - // As of ImGui 1.92, things start to change. There's still a global scale factor and we expose it, - // but DPI handling is different. - const float MIN_SCALE = 0.3f; - const float MAX_SCALE = 2.0f; - if (ImGui::DragFloat("global scale", &getGlobalFontScale(), 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything - getGlobalFontScale() = IM_MAX(getGlobalFontScale(), MIN_SCALE); - ImGui::PopItemWidth(); - -} - -void -mvFontManager::setGlobalFontScale(float scale) -{ - _globalFontScale = scale; -} \ No newline at end of file diff --git a/src/mvFontManager.h b/src/mvFontManager.h deleted file mode 100644 index a0f72ece2..000000000 --- a/src/mvFontManager.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include -#include "mvContext.h" -#include "mvToolWindow.h" - -class mvFontManager : public mvToolWindow -{ - -public: - mvFontManager(); - - void updateAtlas(); - float& getGlobalFontScale() { return _globalFontScale; } - void setGlobalFontScale(float scale); - bool isDefaultFont(const std::shared_ptr& item) - { - return (_defaultFont.lock() == item); - } - void setDefaultFont(const std::shared_ptr& font) - { - _defaultFont = font; - _updateDefault = true; - } - void clearDefaultFont() - { - _defaultFont.reset(); - _updateDefault = true; - } - - mvUUID getUUID() const override { return MV_TOOL_FONT_UUID; } - const char* getTitle() const override { return "Font Manager"; } - -protected: - - void drawWidgets() override; - void drawFontNode(ImFont* font); - void drawFontSelector(const char* label); - -public: - - // Must be a mvFont (or empty) - std::weak_ptr _defaultFont; - // The only reason we need this _updateDefault flag is for "Set as default" - // buttons work in Font Manager window and in ImGui Style Editor. If not for those - // buttons, we could set the default font every frame all the time. - // Updates are blocked whenever the user clicks one of those "Set as default" buttons. - bool _updateDefault = true; - float _globalFontScale = 1.0f; - -}; \ No newline at end of file diff --git a/src/mvGlobalHandlers.cpp b/src/mvGlobalHandlers.cpp deleted file mode 100644 index c450c80b1..000000000 --- a/src/mvGlobalHandlers.cpp +++ /dev/null @@ -1,480 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvGlobalHandlers.h" -#include - -void mvHandlerRegistry::draw(ImDrawList* drawlist, float x, float y) -{ - - for (auto& item : childslots[1]) - item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY()); - -} - -void mvKeyDownHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_key == ImGuiKey_None) - { - for (int i = ImGuiKey_NamedKey_BEGIN; i < ImGuiKey_NamedKey_END; i++) - { - auto key = ImGui::GetKeyData(static_cast(i)); - if (key->Down) - { - submitCallbackEx([=]() { return ToPyMPair(i, key->DownDuration); }); - } - } - } - - else if (ImGui::IsKeyDown(_key)) - { - submitCallbackEx([=]() { return ToPyMPair(_key, ImGui::GetKeyData(_key)->DownDuration); }); - } -} - -void mvKeyDownHandler::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _key = (ImGuiKey)ToInt(PyTuple_GetItem(dict, 0)); -} - -void mvKeyDownHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "key")) _key = (ImGuiKey)ToInt(item); -} - -void mvKeyDownHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "key", mvPyObject(ToPyInt(_key))); -} - -void mvKeyPressHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_key == ImGuiKey_None) - { - for (int i = ImGuiKey_NamedKey_BEGIN; i < ImGuiKey_NamedKey_END; i++) - { - if (ImGui::IsKeyPressed(static_cast(i))) - { - submitCallback(i); - } - } - } - - else if (ImGui::IsKeyPressed(_key)) - { - submitCallback(_key); - } -} - -void mvKeyPressHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _key = (ImGuiKey)ToInt(item); - break; - - default: - break; - } - } -} - -void mvKeyPressHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "key")) _key = (ImGuiKey)ToInt(item); -} - -void mvKeyPressHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "key", mvPyObject(ToPyInt(_key))); -} - -void mvKeyReleaseHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_key == ImGuiKey_None) - { - for (int i = ImGuiKey_NamedKey_BEGIN; i < ImGuiKey_NamedKey_END; i++) - { - if (ImGui::IsKeyReleased(static_cast(i))) - { - submitCallback(i); - } - } - } - - else if (ImGui::IsKeyReleased(_key)) - { - submitCallback(_key); - } -} - -void mvKeyReleaseHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _key = (ImGuiKey)ToInt(item); - break; - - default: - break; - } - } -} - -void mvKeyReleaseHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "key")) _key = (ImGuiKey)ToInt(item); -} - -void mvKeyReleaseHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "key", mvPyObject(ToPyInt(_key))); -} - -void mvMouseClickHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_button == -1) - { - for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - if (ImGui::IsMouseClicked(i)) - { - submitCallback(i); - } - } - } - - else if (ImGui::IsMouseClicked(_button)) - { - submitCallback(_button); - } -} - -void mvMouseClickHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _button = ToInt(item); - break; - - default: - break; - } - } -} - -void mvMouseClickHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvMouseClickHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvMouseDoubleClickHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_button == -1) - { - for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - if (ImGui::IsMouseDoubleClicked(i)) - { - submitCallback(i); - } - } - } - - else if (ImGui::IsMouseDoubleClicked(_button)) - { - submitCallback(_button); - } -} - -void mvMouseDoubleClickHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _button = ToInt(item); - break; - - default: - break; - } - } -} - -void mvMouseDoubleClickHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvMouseDoubleClickHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvMouseDownHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_button == -1) - { - for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - if (ImGui::GetIO().MouseDown[i]) - { - submitCallbackEx([=]() { return ToPyMPair(i, ImGui::GetIO().MouseDownDuration[i]); }); - } - } - } - - else if (ImGui::GetIO().MouseDown[_button]) - { - submitCallbackEx([=]() { return ToPyMPair(_button, ImGui::GetIO().MouseDownDuration[_button]); }); - } -} - -void mvMouseDownHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _button = ToInt(item); - break; - - default: - break; - } - } -} - -void mvMouseDownHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvMouseDownHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvMouseDragHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_button == -1) - { - for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - if (ImGui::IsMouseReleased(i)) - ImGui::ResetMouseDragDelta(i); - - if (ImGui::IsMouseDragging(i, _threshold)) - { - submitCallbackEx([=]() { return ToPyMTrip(i, ImGui::GetMouseDragDelta(i).x, ImGui::GetMouseDragDelta(i).y); }); - } - } - } - - else if (ImGui::IsMouseDragging(_button, _threshold)) - { - if (ImGui::IsMouseReleased(_button)) - ImGui::ResetMouseDragDelta(_button); - - submitCallbackEx([=]() { return ToPyMTrip(_button, ImGui::GetMouseDragDelta(_button).x, ImGui::GetMouseDragDelta(_button).y); }); - } -} - -void mvMouseDragHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _button = ToInt(item); - break; - case 1: - _threshold = ToFloat(item); - break; - - default: - break; - } - } -} - -void mvMouseDragHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); - if (PyObject* item = PyDict_GetItemString(dict, "threshold")) _threshold = ToFloat(item); -} - -void mvMouseDragHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); - PyDict_SetItemString(dict, "threshold", mvPyObject(ToPyFloat(_threshold))); -} - - -void mvMouseMoveHandler::draw(ImDrawList* drawlist, float x, float y) -{ - - // update mouse - // mouse move event - ImVec2 mousepos = ImGui::GetMousePos(); - if (ImGui::IsMousePosValid(&mousepos)) - { - if (_oldPos.x != mousepos.x || _oldPos.y != mousepos.y) - { - _oldPos = mousepos; - - submitCallback(mousepos); - } - } -} - -void mvMouseReleaseHandler::draw(ImDrawList* drawlist, float x, float y) -{ - if (_button == -1) - { - for (int i = 0; i < IM_ARRAYSIZE(ImGui::GetIO().MouseDown); i++) - { - if (ImGui::IsMouseReleased(i)) - { - submitCallback(i); - } - } - } - - else if (ImGui::IsMouseReleased(_button)) - { - submitCallback(_button); - } -} - -void mvMouseReleaseHandler::handleSpecificPositionalArgs(PyObject* dict) -{ - if (!VerifyPositionalArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - for (int i = 0; i < PyTuple_Size(dict); i++) - { - PyObject* item = PyTuple_GetItem(dict, i); - switch (i) - { - case 0: - _button = ToInt(item); - break; - - default: - break; - } - } -} - -void mvMouseReleaseHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvMouseReleaseHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvMouseWheelHandler::draw(ImDrawList* drawlist, float x, float y) -{ - int wheel = (int)ImGui::GetIO().MouseWheel; - if (wheel) - { - submitCallback(wheel); - } -} \ No newline at end of file diff --git a/src/mvGlobalHandlers.h b/src/mvGlobalHandlers.h deleted file mode 100644 index 039c97e7b..000000000 --- a/src/mvGlobalHandlers.h +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once - -#include "mvAppItem.h" -#include "mvItemRegistry.h" -#include - -class mvHandlerRegistry : public mvAppItem -{ -public: - explicit mvHandlerRegistry(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; -}; - -class mvKeyDownHandler : public mvAppItem -{ -public: - ImGuiKey _key = ImGuiKey_None; - explicit mvKeyDownHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificRequiredArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvKeyPressHandler : public mvAppItem -{ -public: - ImGuiKey _key = ImGuiKey_None; - explicit mvKeyPressHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvKeyReleaseHandler : public mvAppItem -{ -public: - ImGuiKey _key = ImGuiKey_None; - explicit mvKeyReleaseHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseClickHandler : public mvAppItem -{ -public: - int _button = -1; - explicit mvMouseClickHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseDoubleClickHandler : public mvAppItem -{ -public: - int _button = -1; - explicit mvMouseDoubleClickHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseDownHandler : public mvAppItem -{ -public: - int _button = -1; - explicit mvMouseDownHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseDragHandler : public mvAppItem -{ -public: - int _button = -1; - float _threshold = 10.0f; - explicit mvMouseDragHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseMoveHandler : public mvAppItem -{ -public: - ImVec2 _oldPos = {}; - explicit mvMouseMoveHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; -}; - -class mvMouseReleaseHandler : public mvAppItem -{ -public: - int _button = -1; - explicit mvMouseReleaseHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; - void handleSpecificPositionalArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvMouseWheelHandler : public mvAppItem -{ -public: - explicit mvMouseWheelHandler(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override; -}; \ No newline at end of file diff --git a/src/mvGraphics.h b/src/mvGraphics.h deleted file mode 100644 index 85bf906db..000000000 --- a/src/mvGraphics.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "mvCore.h" -#include "mvTextures.h" - -// forward declarations -struct mvGraphics; -struct mvViewport; - -mvGraphics setup_graphics(mvViewport& viewport); -void resize_swapchain(mvGraphics& graphics, int width, int height); -void cleanup_graphics(mvGraphics& graphics); -void present(mvGraphics& graphics, mvColor& clearColor, bool vsync); - -struct mvGraphics -{ - bool ok = false; - void* backendSpecifics = nullptr; -}; \ No newline at end of file diff --git a/src/mvGraphics_apple.mm b/src/mvGraphics_apple.mm deleted file mode 100644 index b6ce2f135..000000000 --- a/src/mvGraphics_apple.mm +++ /dev/null @@ -1,52 +0,0 @@ -#include "mvGraphics.h" - -#include "mvAppleSpecifics.h" - -#include "mvViewport.h" - -#include "imgui_impl_glfw.h" -#include "imgui_impl_metal.h" - -mvGraphics -setup_graphics(mvViewport &viewport) -{ - mvGraphics graphics{}; - graphics.backendSpecifics = new mvGraphics_Metal(); - - auto viewportData = (mvViewportData*)viewport.platformSpecifics; - auto graphicsData = (mvGraphics_Metal*)graphics.backendSpecifics; - - graphicsData->device = MTLCreateSystemDefaultDevice(); - graphicsData->commandQueue = [graphicsData->device newCommandQueue]; - - ImGui_ImplMetal_Init(graphicsData->device); - - NSWindow *nswin = glfwGetCocoaWindow(viewportData->handle); - viewportData->layer = [CAMetalLayer layer]; - viewportData->layer.device = graphicsData->device; - viewportData->layer.pixelFormat = MTLPixelFormatBGRA8Unorm; - nswin.contentView.layer = viewportData->layer; - nswin.contentView.wantsLayer = YES; - - graphicsData->renderPassDescriptor = [MTLRenderPassDescriptor new]; - - return graphics; -} - -void -resize_swapchain(mvGraphics &graphics, int width, int height) -{ - -} - -void -cleanup_graphics(mvGraphics &graphics) -{ - -} - -void -present(mvGraphics &graphics, mvColor &clearColor, bool vsync) -{ - -} \ No newline at end of file diff --git a/src/mvGraphics_linux.cpp b/src/mvGraphics_linux.cpp deleted file mode 100644 index 63f1a0bbc..000000000 --- a/src/mvGraphics_linux.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "mvGraphics.h" - -#include "mvLinuxSpecifics.h" - -#include "mvViewport.h" -#include "mvProfiler.h" - -#include "imgui_impl_glfw.h" -#include "imgui_impl_opengl3.h" - -mvGraphics -setup_graphics(mvViewport& viewport) -{ - mvGraphics graphics{}; - auto viewportData = (mvViewportData*)viewport.platformSpecifics; - const char* glsl_version = "#version 130"; - ImGui_ImplOpenGL3_Init(glsl_version); - return graphics; -} - -void -resize_swapchain(mvGraphics& graphics, int width, int height) -{ - -} - -void -cleanup_graphics(mvGraphics& graphics) -{ - -} - -void -present(mvGraphics& graphics, mvColor& clearColor, bool vsync) -{ - MV_PROFILE_SCOPE("Presentation") - - mvViewport* viewport = GContext->viewport; - auto viewportData = (mvViewportData*)viewport->platformSpecifics; - - glfwGetWindowPos(viewportData->handle, &viewport->xpos, &viewport->ypos); - - glfwSwapInterval(viewport->vsync ? 1 : 0); // Enable vsync - - // Rendering - ImGui::Render(); - int display_w, display_h; - glfwGetFramebufferSize(viewportData->handle, &display_w, &display_h); - - glViewport(0, 0, display_w, display_h); - glClearColor(viewport->clearColor.r, viewport->clearColor.g, viewport->clearColor.b, viewport->clearColor.a); - glClear(GL_COLOR_BUFFER_BIT); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - - glfwSwapBuffers(viewportData->handle); -} \ No newline at end of file diff --git a/src/mvGraphics_win32.cpp b/src/mvGraphics_win32.cpp deleted file mode 100644 index 24da2ec19..000000000 --- a/src/mvGraphics_win32.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include "mvGraphics.h" - -#include "mvWindowsSpecifics.h" - -static std::vector -EnumerateAdapters() -{ - IDXGIAdapter* pAdapter; - std::vector vAdapters; - IDXGIFactory* pFactory = NULL; - - // Create a DXGIFactory object. - if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&pFactory))) - { - return vAdapters; - } - - - for (UINT i = 0; - pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; - ++i) - { - vAdapters.push_back(pAdapter); - } - - - if (pFactory) - { - pFactory->Release(); - } - - return vAdapters; - -} - -mvGraphics -setup_graphics(mvViewport& viewport) -{ - mvGraphics graphics{}; - graphics.backendSpecifics = new mvGraphics_D3D11(); - - mvViewportData* viewportData = (mvViewportData*)viewport.platformSpecifics; - mvGraphics_D3D11* graphicsData = (mvGraphics_D3D11*)graphics.backendSpecifics; - - // Setup swap chain - DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory(&sd, sizeof(sd)); - sd.BufferCount = 2; - sd.BufferDesc.Width = 0; - sd.BufferDesc.Height = 0; - sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - sd.BufferDesc.RefreshRate.Numerator = 60; - sd.BufferDesc.RefreshRate.Denominator = 1; - sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd.OutputWindow = viewportData->handle; - sd.SampleDesc.Count = 1; - sd.SampleDesc.Quality = 0; - sd.Windowed = TRUE; - sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - - auto adapters = EnumerateAdapters(); - - UINT createDeviceFlags = 0; - D3D_FEATURE_LEVEL featureLevel; - const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - - // use default adapter - if (GContext->IO.info_auto_device) - { - - int index = 0; - SIZE_T adapterMemory = 0; - - for (int i = 0; i < adapters.size(); i++) - { - DXGI_ADAPTER_DESC adpdesc; - adapters[i]->GetDesc(&adpdesc); - if (adpdesc.DedicatedVideoMemory > adapterMemory) - { - adapterMemory = adpdesc.DedicatedVideoMemory; - index = i; - } - - } - - if (D3D11CreateDeviceAndSwapChain(adapters[index], D3D_DRIVER_TYPE_UNKNOWN, nullptr, - createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &graphicsData->swapChain, - &graphicsData->device, &featureLevel, &graphicsData->deviceContext) != S_OK) - return graphics; - } - else if (GContext->IO.info_device == -1) - { - if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, - createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &graphicsData->swapChain, - &graphicsData->device, &featureLevel, &graphicsData->deviceContext) != S_OK) - return graphics; - } - else - { - - if (D3D11CreateDeviceAndSwapChain(adapters[GContext->IO.info_device], D3D_DRIVER_TYPE_UNKNOWN, nullptr, - createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &graphicsData->swapChain, - &graphicsData->device, &featureLevel, &graphicsData->deviceContext) != S_OK) - return graphics; - } - - if (!GContext->IO.altEnterFullscreen) - { - // Disable DXGI's default Alt+Enter fullscreen behavior. - IDXGIFactory* pSwapChainFactory = nullptr; - if (SUCCEEDED(graphicsData->swapChain->GetParent(IID_PPV_ARGS(&pSwapChainFactory)))) - { - pSwapChainFactory->MakeWindowAssociation(viewportData->handle, DXGI_MWA_NO_ALT_ENTER); - pSwapChainFactory->Release(); - } - } - - // create render target - graphicsData->swapChain->GetBuffer(0, IID_PPV_ARGS(&graphicsData->backBuffer)); - graphicsData->device->CreateRenderTargetView(graphicsData->backBuffer, nullptr, &graphicsData->target); - - graphics.ok = true; - - ImGui_ImplDX11_Init(graphicsData->device, graphicsData->deviceContext); - - return graphics; -} - -void -cleanup_graphics(mvGraphics& graphics) -{ - mvGraphics_D3D11* graphicsData = (mvGraphics_D3D11*)graphics.backendSpecifics; - - ImGui_ImplDX11_Shutdown(); - - if (graphicsData->target) - { - graphicsData->target->Release(); - graphicsData->target = nullptr; - } - - if (graphicsData->backBuffer) - { - graphicsData->backBuffer->Release(); - graphicsData->backBuffer = nullptr; - } - - if (graphicsData->swapChain) - { - graphicsData->swapChain->Release(); - graphicsData->swapChain = nullptr; - } - - if (graphicsData->deviceContext) - { - graphicsData->deviceContext->Release(); - graphicsData->deviceContext = nullptr; - } - - if (graphicsData->device) - { - graphicsData->device->Release(); - graphicsData->device = nullptr; - } - - delete graphicsData; - graphicsData = nullptr; - -} - -void -resize_swapchain(mvGraphics& graphics, int width, int height) -{ - mvGraphics_D3D11* graphicsData = (mvGraphics_D3D11*)graphics.backendSpecifics; - - - if (graphicsData->target) - { - graphicsData->target->Release(); - graphicsData->target = nullptr; - } - - if (graphicsData->backBuffer) - { - graphicsData->backBuffer->Release(); - graphicsData->backBuffer = nullptr; - } - - graphicsData->swapChain->ResizeBuffers(0, (UINT)width, (UINT)height, DXGI_FORMAT_UNKNOWN, 0); - - // recreate render target - graphicsData->swapChain->GetBuffer(0, IID_PPV_ARGS(&graphicsData->backBuffer)); - graphicsData->device->CreateRenderTargetView(graphicsData->backBuffer, nullptr, &graphicsData->target); -} - -void -present(mvGraphics& graphics, mvColor& clearColor, bool vsync) -{ - MV_PROFILE_SCOPE("Presentation") - - mvGraphics_D3D11* graphicsData = (mvGraphics_D3D11*)graphics.backendSpecifics; - - // Rendering - ImGui::Render(); - graphicsData->deviceContext->OMSetRenderTargets(1, &graphicsData->target, nullptr); - graphicsData->deviceContext->ClearRenderTargetView(graphicsData->target, clearColor); - ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); - - static UINT presentFlags = 0; - if (graphicsData->swapChain->Present(vsync ? 1 : 0, presentFlags) == DXGI_STATUS_OCCLUDED) - { - presentFlags = DXGI_PRESENT_TEST; - Sleep(20); - } - else - presentFlags = 0; -} \ No newline at end of file diff --git a/src/mvImGuiConfig_apple.h b/src/mvImGuiConfig_apple.h deleted file mode 100644 index 63ec0786f..000000000 --- a/src/mvImGuiConfig_apple.h +++ /dev/null @@ -1,17 +0,0 @@ -//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. -// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). -// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. -// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. -#define ImDrawIdx unsigned int - -#define IMGUI_USE_WCHAR32 - -// Note: ImTextureID underlying type is backend-specific and is therefore different on different platforms! -// Leaving it defined as void* until we figure out how to declare it properly (like, id?). -// At least void* has been working fine for years. -#define ImTextureID void* - -// We need these operators somewhere, but starting with ImGui 1.89.4, we can't arbitrarily -// enable them before imgui_internal.h - we need to do this before imgui.h itself - or here. -// Taking precompiled headers into account, we'll be better off defining this globally. -#define IMGUI_DEFINE_MATH_OPERATORS diff --git a/src/mvImGuiConfig_linux.h b/src/mvImGuiConfig_linux.h deleted file mode 100644 index 315487b25..000000000 --- a/src/mvImGuiConfig_linux.h +++ /dev/null @@ -1,16 +0,0 @@ -//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. -// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). -// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. -// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. -#define ImDrawIdx unsigned int - -#define IMGUI_USE_WCHAR32 - -// Note: ImTextureID underlying type is backend-specific and is therefore different on different platforms! -// We don't define ImTextureID here so that it uses the default ImUI64, which is good for -// passing GLuint around (in Linux world, we need a GLuint for texture ID). - -// We need these operators somewhere, but starting with ImGui 1.89.4, we can't arbitrarily -// enable them before imgui_internal.h - we need to do this before imgui.h itself - or here. -// Taking precompiled headers into account, we'll be better off defining this globally. -#define IMGUI_DEFINE_MATH_OPERATORS diff --git a/src/mvImGuiConfig_win32.h b/src/mvImGuiConfig_win32.h deleted file mode 100644 index b8c52f9d3..000000000 --- a/src/mvImGuiConfig_win32.h +++ /dev/null @@ -1,21 +0,0 @@ -//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) -#define IMGUI_ENABLE_FREETYPE - -//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. -// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). -// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. -// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. -#define ImDrawIdx unsigned int - -#define IMGUI_USE_WCHAR32 - -// Note: ImTextureID underlying type is backend-specific and is therefore different on different platforms! -// We're using void* so that we can pass ID3D11ShaderResourceView* here. While we could -// define ImTextureID as ID3D11ShaderResourceView* right here, we'd like to avoid including -// the entire d3d11.h (and windows.h) into this header because it is in turn included into imgui.h. -#define ImTextureID void* - -// We need these operators somewhere, but starting with ImGui 1.89.4, we can't arbitrarily -// enable them before imgui_internal.h - we need to do this before imgui.h itself - or here. -// Taking precompiled headers into account, we'll be better off defining this globally. -#define IMGUI_DEFINE_MATH_OPERATORS diff --git a/src/mvItemHandlers.cpp b/src/mvItemHandlers.cpp deleted file mode 100644 index 2b0d0408f..000000000 --- a/src/mvItemHandlers.cpp +++ /dev/null @@ -1,417 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvItemHandlers.h" - -void mvItemHandlerRegistry::checkEvents(void* data) -{ - - for (auto& item : childslots[1]) - { - if (item->config.show) - item->customAction(data); - } - -} - -void mvItemHandlerRegistry::onBind(mvAppItem* item) -{ - - auto applicableState = DearPyGui::GetApplicableState(item->type); - - for (auto& handler : childslots[1]) - { - switch (handler->type) - { - - case mvAppItemType::mvActivatedHandler: - { - if (!(applicableState & MV_STATE_ACTIVATED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvActivatedHandler", item); - break; - } - - case mvAppItemType::mvActiveHandler: - { - if (!(applicableState & MV_STATE_ACTIVE)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvActiveHandler", item); - break; - } - - case mvAppItemType::mvClickedHandler: - { - if (!(applicableState & MV_STATE_CLICKED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvClickedHandler", item); - break; - } - - case mvAppItemType::mvDoubleClickedHandler: - { - // if an item can be clicked, it can be double clicked as well - if (!(applicableState & MV_STATE_CLICKED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvDoubleClickedHandler", item); - break; - } - - case mvAppItemType::mvDeactivatedAfterEditHandler: - { - if (!(applicableState & MV_STATE_DEACTIVATEDAE)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvDeactivatedAfterEditHandler", item); - break; - } - - case mvAppItemType::mvDeactivatedHandler: - { - if (!(applicableState & MV_STATE_DEACTIVATED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvDeactivatedHandler", item); - break; - } - - case mvAppItemType::mvEditedHandler: - { - if (!(applicableState & MV_STATE_EDITED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvEditedHandler", item); - break; - } - - case mvAppItemType::mvFocusHandler: - { - if (!(applicableState & MV_STATE_FOCUSED)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvFocusHandler", item); - break; - } - - case mvAppItemType::mvHoverHandler: - { - if (!(applicableState & MV_STATE_HOVER)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvHoverHandler", item); - break; - } - - case mvAppItemType::mvResizeHandler: - { - if (!(applicableState & MV_STATE_RECT_SIZE)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvResizeHandler", item); - break; - } - - case mvAppItemType::mvToggledOpenHandler: - { - if (!(applicableState & MV_STATE_TOGGLED_OPEN)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvToggledOpenHandler", item); - break; - } - - case mvAppItemType::mvVisibleHandler: - { - if (!(applicableState & MV_STATE_VISIBLE)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvVisibleHandler", item); - break; - } - - case mvAppItemType::mvScrollHandler: - { - if (!(applicableState & ~MV_STATE_SCROLL)) - mvThrowPythonError(mvErrorCode::mvNone, "bind_item_handler_registry", - "Item Handler Registry includes inapplicable handler: mvScrollHandler", item); - break; - } - - default: break; - } - } -} - -void mvItemHandler::submitHandler(mvAppItem* parent) -{ - submitCallbackEx([uuid=parent->uuid, alias=parent->config.alias] () { - return ToPyUUID(uuid, alias); - }); -} - -void mvBoolStateHandler::checkEvent(bool curState, bool prevState, mvAppItem* parent) -{ - mvEventType eventType = curState? - (prevState? mvEventType_On : mvEventType_EnterAndOn) : - (prevState? mvEventType_LeaveAndOff : mvEventType_Off); - - if (trackedEventType & eventType) - { - // We do not pass eventType to callback yet in order to keep it compatible - // with the old version. - submitHandler(parent); - } -} - -void mvBoolStateHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "event_type")) - { - if (item != Py_None) - trackedEventType = static_cast(ToInt(item)); - } -} - -void mvBoolStateHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "event_type", mvPyObject(ToPyInt(trackedEventType))); -} - -void mvActivatedHandler::customAction(void* data) -{ - - mvAppItemState* state = static_cast(data); - if (state->activated) - { - submitHandler(state->parent); - } -} - -void mvActiveHandler::customAction(void* data) -{ - - mvAppItemState* state = static_cast(data); - if (state->active) - { - submitHandler(state->parent); - } -} - -void mvClickedHandler::customAction(void* data) -{ - - mvAppItemState* state = static_cast(data); - - b8 clicked[] = {state->leftclicked, state->rightclicked, state->middleclicked}; - - int i = (_button < 0)? 0 : _button ; - int end = (_button < 0)? (int)std::size(clicked) : (i + 1); - - for (; i < end; i++) - { - if (clicked[i]) - { - mvAppItem* parent = state->parent; - submitCallbackEx([i, uuid=parent->uuid, alias=parent->config.alias] () { - PyObject* app_data = PyTuple_New(2); - PyTuple_SetItem(app_data, 0, ToPyInt(i)); - PyTuple_SetItem(app_data, 1, ToPyUUID(uuid, alias)); - return app_data; - }); - } - } -} - -void mvClickedHandler::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _button = ToInt(PyTuple_GetItem(dict, 0)); -} - -void mvClickedHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvClickedHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvDoubleClickedHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - - int i = (_button < 0)? 0 : _button ; - int end = (_button < 0)? state->doubleclicked.size() : (i + 1); - - for (; i < end; i++) - { - if (state->doubleclicked[i]) - { - mvAppItem* parent = state->parent; - submitCallbackEx([i, uuid=parent->uuid, alias=parent->config.alias] () { - PyObject* app_data = PyTuple_New(2); - PyTuple_SetItem(app_data, 0, ToPyInt(i)); - PyTuple_SetItem(app_data, 1, ToPyUUID(uuid, alias)); - return app_data; - }); - } - } -} - -void mvDoubleClickedHandler::handleSpecificRequiredArgs(PyObject* dict) -{ - if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict)) - return; - - _button = ToInt(PyTuple_GetItem(dict, 0)); -} - -void mvDoubleClickedHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "button")) _button = ToInt(item); -} - -void mvDoubleClickedHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "button", mvPyObject(ToPyInt(_button))); -} - -void mvDeactivatedAfterEditHandler::customAction(void* data) -{ - - mvAppItemState* state = static_cast(data); - if (state->deactivatedAfterEdit) - { - submitHandler(state->parent); - } -} - -void mvDeactivatedHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - if (state->deactivated) - { - submitHandler(state->parent); - } -} - -void mvEditedHandler::customAction(void* data) -{ - - mvAppItemState* state = static_cast(data); - if (state->edited) - { - submitHandler(state->parent); - } -} - -void mvFocusHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - checkEvent(state->focused, state->prevFocused, state->parent); -} - -void mvHoverHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - checkEvent(state->hovered, state->prevHovered, state->parent); -} - -void mvResizeHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - if (state->mvRectSizeResized) - { - submitHandler(state->parent); - } -} - -void mvToggledOpenHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - if (state->toggledOpen || twoWay && state->toggledOpenPure) - { - submitHandler(state->parent); - } -} - -void mvToggledOpenHandler::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "two_way")) twoWay = ToBool(item); -} - -void mvToggledOpenHandler::getSpecificConfiguration(PyObject* dict) -{ - if (dict == nullptr) - return; - - PyDict_SetItemString(dict, "two_way", mvPyObject(ToPyBool(twoWay))); -} - -void mvVisibleHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - if (static_cast(data)->visible) - { - submitHandler(state->parent); - } -} - -PyObject* mvScrollHandler::makeAppData(mvUUID uuid, const std::string& alias, mvScrollDirection dir, bool isScrolling, float pos, float max) -{ - PyObject* app_data = PyTuple_New(5); - PyTuple_SetItem(app_data, 0, ToPyUUID(uuid, alias)); - PyTuple_SetItem(app_data, 1, ToPyInt(dir)); - PyTuple_SetItem(app_data, 2, ToPyFloat(pos)); - PyTuple_SetItem(app_data, 3, ToPyFloat(max)); - PyTuple_SetItem(app_data, 4, ToPyBool(isScrolling)); - return app_data; -} - -void mvScrollHandler::customAction(void* data) -{ - mvAppItemState* state = static_cast(data); - mvAppItem* parent = state->parent; - if (state->scrolledX) - { - submitCallbackEx([=, - uuid=parent->uuid, - alias=parent->config.alias, - isScrolling=state->isScrollingX, - pos=state->scrollPos.x, - max=state->scrollMax.x] () - { - return makeAppData(uuid, alias, mvScrollDirection_XAxis, isScrolling, pos, max); - }); - } - - if (state->scrolledY) - { - submitCallbackEx([=, - uuid=parent->uuid, - alias=parent->config.alias, - isScrolling=state->isScrollingY, - pos=state->scrollPos.y, - max=state->scrollMax.y] () - { - return makeAppData(uuid, alias, mvScrollDirection_YAxis, isScrolling, pos, max); - }); - } -} diff --git a/src/mvItemHandlers.h b/src/mvItemHandlers.h deleted file mode 100644 index dd6ae0811..000000000 --- a/src/mvItemHandlers.h +++ /dev/null @@ -1,185 +0,0 @@ -#pragma once - -#include "mvAppItem.h" -#include "mvItemRegistry.h" - -class mvItemHandlerRegistry : public mvAppItem -{ - -public: - explicit mvItemHandlerRegistry(mvUUID uuid) : mvAppItem(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void checkEvents(void* data = nullptr); - void onBind(mvAppItem* item); -}; - -class mvItemHandler : public mvAppItem -{ -public: - explicit mvItemHandler(mvUUID uuid) : mvAppItem(uuid) {} - -protected: - void submitHandler(mvAppItem* parent); -}; - -enum mvEventType -{ - // These constants can be used as a combination of flags - mvEventType_None = 0, - mvEventType_Off = 1 << 1, - mvEventType_Enter = 1 << 2, - mvEventType_On = 1 << 3, - mvEventType_Leave = 1 << 4, - // When the state changes, we observe two events in a single frame: - // both "enter" and "on" or both "leave" and "off". We need to define - // these flags here so that they can be used as a mask later on. - mvEventType_EnterAndOn = mvEventType_Enter | mvEventType_On, - mvEventType_LeaveAndOff = mvEventType_Leave | mvEventType_Off, - // This is the state the handler will react to by default - mvEventType_Default = mvEventType_On -}; - -// This is a base class for handlers that monitor a single bool variable -// that can switch on or off and reflects the item state, like "focused" -// or "hovered". -class mvBoolStateHandler : public mvItemHandler -{ -public: - explicit mvBoolStateHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void checkEvent(bool curState, bool prevState, mvAppItem* parent); - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -protected: - mvEventType trackedEventType = mvEventType_Default; -}; - -class mvActivatedHandler : public mvItemHandler -{ -public: - explicit mvActivatedHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - -}; - -class mvActiveHandler : public mvItemHandler -{ -public: - explicit mvActiveHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - -}; - -class mvClickedHandler : public mvItemHandler -{ -public: - int _button = -1; - explicit mvClickedHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - void handleSpecificRequiredArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvDoubleClickedHandler : public mvItemHandler -{ -public: - int _button = -1; - explicit mvDoubleClickedHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - void handleSpecificRequiredArgs(PyObject* dict) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; -}; - -class mvDeactivatedAfterEditHandler : public mvItemHandler -{ -public: - explicit mvDeactivatedAfterEditHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; -}; - -class mvDeactivatedHandler : public mvItemHandler -{ -public: - explicit mvDeactivatedHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; -}; - -class mvEditedHandler : public mvItemHandler -{ -public: - explicit mvEditedHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; -}; - -class mvFocusHandler : public mvBoolStateHandler -{ -public: - explicit mvFocusHandler(mvUUID uuid) : mvBoolStateHandler(uuid) {} - void customAction(void* data = nullptr) override; -}; - -class mvHoverHandler : public mvBoolStateHandler -{ -public: - explicit mvHoverHandler(mvUUID uuid) : mvBoolStateHandler(uuid) {} - void customAction(void* data = nullptr) override; -}; - -class mvResizeHandler : public mvItemHandler -{ -public: - explicit mvResizeHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; -}; - -class mvToggledOpenHandler : public mvItemHandler -{ -public: - explicit mvToggledOpenHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - void handleSpecificKeywordArgs(PyObject* dict) override; - void getSpecificConfiguration(PyObject* dict) override; - -private: - bool twoWay = false; -}; - -class mvVisibleHandler : public mvItemHandler -{ -public: - explicit mvVisibleHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; -}; - -enum mvScrollDirection -{ - // These constants can be used as a combination of flags - mvScrollDirection_XAxis = 1, - mvScrollDirection_Horizontal = 1, - mvScrollDirection_YAxis = 2, - mvScrollDirection_Vertical = 2, -}; - -class mvScrollHandler : public mvItemHandler -{ -public: - explicit mvScrollHandler(mvUUID uuid) : mvItemHandler(uuid) {} - void draw(ImDrawList* drawlist, float x, float y) override {} - void customAction(void* data = nullptr) override; - -private: - static PyObject* makeAppData(mvUUID uuid, const std::string& alias, mvScrollDirection dir, bool isScrolling, float pos, float max); -}; diff --git a/src/mvItemRegistry.cpp b/src/mvItemRegistry.cpp deleted file mode 100644 index 60e24de5f..000000000 --- a/src/mvItemRegistry.cpp +++ /dev/null @@ -1,973 +0,0 @@ -#include "mvPyUtils.h" -#pragma hdrstop - -#include "mvItemRegistry.h" - -#include "mvContext.h" -#include "mvThemes.h" -#include "mvToolManager.h" -#include "mvFontManager.h" -#include "mvContainers.h" -#include "mvTables.h" - -#include "mvProfiler.h" - -thread_local mvThreadContext mvItemRegistry::threadContext; - -mvItemRegistry::mvItemRegistry() -{ - // We seldom need to do a GetItem(0), and an explicit check for uuid == 0 in GetItem - // slows it down. Instead of this, we add a fake entry to the allItems map, - // mapping 0 to nullptr. This entry will never go away because map items are only - // removed in the mvAppItem destructor. - allItems[0] = nullptr; -} - -static b8 -DoesAliasExist(mvItemRegistry& registry, const std::string& alias) -{ - if (registry.aliases.count(alias) != 0) - return true; - return false; -} - -static void -DebugItem(const char* label, const char* item) { - ImGui::Text("%s", label); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%s", item); -} - -static mvAppItem* -TopParent(mvItemRegistry& registry) -{ - auto& containers = mvItemRegistry::threadContext.containers; - if (!containers.empty()) - return containers.top().get(); - return nullptr; -} - -static void -UpdateChildLocations(std::vector>* children, i32 slots) -{ - for (i32 i = 0; i < slots; i++) - { - i32 index = 0; - for (auto& child : children[i]) - { - if (child) - { - child->info.location = index; - index++; - } - } - } -} - -static b8 -AddRuntimeChild(mvAppItem* rootitem, mvUUID before, std::shared_ptr item) -{ - if (before == 0) - { - i32 targetSlot = DearPyGui::GetEntityTargetSlot(item->type); - item->info.location = (i32)rootitem->childslots[targetSlot].size(); - rootitem->childslots[targetSlot].push_back(item); - item->info.parentPtr = rootitem; - item->config.parent = rootitem->uuid; - DearPyGui::OnChildAdded(rootitem, item); - return true; - } - else - { - for (auto& childslot : rootitem->childslots) - { - for (auto it = childslot.begin(); it != childslot.end(); ++it) - { - auto child = *it; - if (!child) - continue; - - if (child->uuid == before) - { - childslot.insert(it, item); - item->info.parentPtr = rootitem; - item->config.parent = rootitem->uuid; - // TODO: this one can be optimized by updating locations in the tail - // of the `childslot` only - UpdateChildLocations(&childslot, 1); - DearPyGui::OnChildAdded(rootitem, item); - return true; - } - } - } - } - IM_ASSERT(false && "We could not find `before` in its parent's childslots."); - return false; -} - -static b8 -AddItemAfter(mvItemRegistry& registry, mvUUID prev, std::shared_ptr item) -{ - - mvAppItem* prevItem = GetItem(registry, prev); - if (!prevItem) - { - IM_ASSERT(false && "AddItemAfter could not find prev."); - return false; - } - - mvAppItem* parent = prevItem->info.parentPtr; - if (parent) - { - for (auto& childset : parent->childslots) - { - for (auto it = childset.begin(); it != childset.end(); ++it) - { - if (it->get() == prevItem) - { - ++it; - childset.insert(it, item); - item->info.parentPtr = parent; - item->config.parent = parent->uuid; - UpdateChildLocations(&childset, 1); - DearPyGui::OnChildAdded(parent, item); - return true; - } - } - } - // This must never happen - IM_ASSERT(false && "Could not find item in parent's childslots."); - return false; - } - - assert(false); - return false; -} - -static std::vector>& -GetRootsList(mvItemRegistry& registry, mvAppItemType type) -{ - switch (type) - { - case mvAppItemType::mvWindowAppItem: return registry.windowRoots; - case mvAppItemType::mvColorMapRegistry: return registry.colormapRoots; - case mvAppItemType::mvFileDialog: return registry.filedialogRoots; - case mvAppItemType::mvStage: return registry.stagingRoots; - case mvAppItemType::mvViewportMenuBar: return registry.viewportMenubarRoots; - case mvAppItemType::mvFontRegistry: return registry.fontRegistryRoots; - case mvAppItemType::mvHandlerRegistry: return registry.handlerRegistryRoots; - case mvAppItemType::mvTextureRegistry: return registry.textureRegistryRoots; - case mvAppItemType::mvValueRegistry: return registry.valueRegistryRoots; - case mvAppItemType::mvTheme: return registry.themeRegistryRoots; - case mvAppItemType::mvTemplateRegistry: return registry.itemTemplatesRoots; - case mvAppItemType::mvItemHandlerRegistry: return registry.itemHandlerRegistryRoots; - case mvAppItemType::mvViewportDrawlist: return registry.viewportDrawlistRoots; - default: - // Nothing to do here, this is just to calm down the compiler that will - // otherwise warn about unused enum values. - break; - } - // We must never end up here - IM_ASSERT(false && "A root container does not have a corresponding list in GetRootsList."); - return registry.windowRoots; -} - -static void -AddRoot(mvItemRegistry& registry, std::shared_ptr item) -{ - auto& roots = GetRootsList(registry, item->type); - roots.push_back(item); -} - -static void -RemoveDebugWindow(mvItemRegistry& registry, mvUUID uuid) -{ - // check if debug window exists - b8 exists = false; - for (const auto& debug : registry.debugWindows) - { - if (debug->uuid == uuid) - { - exists = true; - break; - } - } - - // not found - if (!exists) - return; - - std::vector> oldWindows = registry.debugWindows; - registry.debugWindows.clear(); - - for (auto& debug : oldWindows) - { - if (debug->uuid != uuid) - registry.debugWindows.push_back(debug); - } -} - -mvUUID -GetIDFromPyObject(PyObject* item) -{ - - if (item == nullptr) - return 0; - - if (isPyObject_Int(item)) - return ToUUID(item); - else if (isPyObject_String(item)) - { - std::string alias = ToString(item); - return GetIdFromAlias(*GContext->itemRegistry, alias); - } - return 0; -} - -mvAppItem* -GetItemRoot(mvItemRegistry& registry, mvUUID uuid) -{ - mvAppItem* item = GetItem(registry, uuid); - if (item) - { - if (item->info.parentPtr) - { - mvAppItem* currentAncestor = item->info.parentPtr; - while (!(DearPyGui::GetEntityDesciptionFlags(currentAncestor->type) & MV_ITEM_DESC_ROOT)) - currentAncestor = currentAncestor->info.parentPtr; - - return currentAncestor; - } - } - return nullptr; -} - -// Disconnects the item from its parent by removing it from the parent's childslot. -// For root items, removes it from the "parent" list of roots. -// When called on an item that's in the tree, must never return false. The return -// value is only intended to catch internal errors when the item registry is broken. -// Note: it does *not* reset item->info.parentPtr! -static bool -RemoveItemFromTree(mvItemRegistry& registry, mvAppItem* item) -{ - mvAppItem* parent = item->info.parentPtr; - if (parent) - { - for (auto& childset : parent->childslots) - { - for (auto it = childset.begin(); it != childset.end(); ++it) - { - if (it->get() == item) - { - auto child = *it; - childset.erase(it); - // TODO: this one can be optimized by updating locations in the tail - // of the `childset` only - UpdateChildLocations(&childset, 1); - DearPyGui::OnChildRemoved(parent, child); - return true; - } - } - } - // This must never happen - IM_ASSERT(false && "Could not find item in parent's childslots."); - return false; - } - - // Now this is a root item - IM_ASSERT((DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_ROOT) && "Item is neither a child nor a root."); - - auto& roots = GetRootsList(registry, item->type); - for (auto it = roots.begin(); it != roots.end(); ++it) - { - if (it->get() == item) - { - roots.erase(it); - return true; - } - } - - // This must never happen - IM_ASSERT(false && "Could not find a root item in the corresponding roots list."); - return false; -} - -b8 -DeleteItem(mvItemRegistry& registry, mvUUID uuid, b8 childrenOnly, i32 slot) -{ - mvAppItem* item = GetItem(registry, uuid); - if (!item) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "delete_item", - "Item not found: " + std::to_string(uuid), nullptr); - return false; - } - - // delete item's children only - if (childrenOnly) - { - if (slot > -1 && slot < 4) - { - item->childslots[slot].clear(); - } - else - { - for(size_t i = 0; i < 4; i++) - { - item->childslots[i].clear(); - } - } - - if(item->type == mvAppItemType::mvTable) - static_cast(item)->onChildrenRemoved(); - - return true; - } - - // See if it is the captured item - auto& capturedItem = mvItemRegistry::threadContext.capturedItem; - if (capturedItem && capturedItem.get() == item) - { - capturedItem = nullptr; - return true; - } - - // Now this is just a regular item in the tree - RemoveDebugWindow(registry, uuid); - if (!RemoveItemFromTree(registry, item)) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "delete_item", - "Unable to delete item: " + std::to_string(uuid), item); - return false; - } - - return true; -} - -b8 -MoveItem(mvItemRegistry& registry, mvUUID uuid, mvUUID parent, mvUUID before) -{ - - std::shared_ptr child = nullptr; - - auto& capturedItem = mvItemRegistry::threadContext.capturedItem; - if (capturedItem && capturedItem->uuid == uuid) - { - child = capturedItem; - capturedItem = nullptr; - } - else - { - child = GetRefItem(registry, uuid); - if (child == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item", - "Item not found: " + std::to_string(uuid), nullptr); - return false; - } - // Remove it from its current location in the tree - RemoveItemFromTree(registry, child.get()); - } - - // Resetting parent item or otherwise AddItemWithRuntimeChecks might fall back - // to the previously stored value. - child->config.parent = 0; - - // TODO: AddItemWithRuntimeChecks will refuse to add items with state.ok == false, - // which includes fonts and textures that failed to load. Fix this. - return AddItemWithRuntimeChecks(registry, child, parent, before); -} - -b8 -MoveItemUp(mvItemRegistry& registry, mvUUID uuid) -{ - mvAppItem* item = GetItem(registry, uuid); - if (!item) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_up", - "Item not found: " + std::to_string(uuid), nullptr); - return false; - } - - mvAppItem* parent = item->info.parentPtr; - if (parent) - { - for (auto& childset : parent->childslots) - { - for (auto it = childset.begin(), prev_it = childset.begin(); it != childset.end(); ++it) - { - if (it->get() == item) - { - if (it != childset.begin()) - { - // Swapping locations so that we don't need to recalculate them on all children - std::swap((*prev_it)->info.location, (*it)->info.location); - // Now swap the child items themselves - std::iter_swap(prev_it, it); - } - return true; - } - prev_it = it; - } - } - // This must never happen - IM_ASSERT(false && "Could not find item in parent's childslots."); - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_up", - "Unable to move item: " + std::to_string(uuid), item); - return false; - } - - // This is probably a root item, but we don't support moving roots up/down. - // It has never worked on roots, and actually has little sense. - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_up", - "move_item_up for root items is not supported", item); - return false; -} - -b8 -MoveItemDown(mvItemRegistry& registry, mvUUID uuid) -{ - mvAppItem* item = GetItem(registry, uuid); - if (!item) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_down", - "Item not found: " + std::to_string(uuid), nullptr); - return false; - } - - mvAppItem* parent = item->info.parentPtr; - if (parent) - { - for (auto& childset : parent->childslots) - { - for (auto it = childset.begin(); it != childset.end(); ++it) - { - if (it->get() == item) - { - auto next_it = std::next(it); - if (next_it != childset.end()) - { - // Swapping locations so that we don't need to recalculate them on all children - std::swap((*it)->info.location, (*next_it)->info.location); - // Now swap the child items themselves - std::iter_swap(it, next_it); - } - return true; - } - } - } - // This must never happen - IM_ASSERT(false && "Could not find item in parent's childslots."); - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_down", - "Unable to move item: " + std::to_string(uuid), item); - return false; - } - - // This is probably a root item, but we don't support moving roots up/down. - // It has never worked on roots, and actually has little sense. - mvThrowPythonError(mvErrorCode::mvItemNotFound, "move_item_down", - "move_item_down for root items is not supported", item); - return false; -} - -b8 -ReorderChildren(mvItemRegistry& registry, mvUUID parent, i32 slot, const std::vector& new_order) -{ - mvAppItem* parentItem = GetItem(registry, parent); - if (parentItem == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "reorder_items", - "Item not found: " + std::to_string(parent), nullptr); - return false; - } - - std::vector>& children = parentItem->childslots[slot]; - - std::vector> newchildren; - newchildren.reserve(children.size()); - - // todo: better sorting algorithm - for (const auto& item : new_order) - { - for (auto& child : children) - { - if (child->uuid == item) - { - newchildren.emplace_back(child); - break; - } - } - } - children = newchildren; - UpdateChildLocations(&children, 1); - return true; -} - -void -RenderItemRegistry(mvItemRegistry& registry) -{ - MV_PROFILE_SCOPE("Rendering") - - if(registry.showImGuiDebug) - ImGui::ShowDemoWindow(®istry.showImGuiDebug); - if(registry.showImPlotDebug) - ImPlot::ShowDemoWindow(®istry.showImPlotDebug); - - for (auto& root : registry.fontRegistryRoots) - { - if (root->config.show) - root->draw(nullptr, 0.0f, 0.0f); - } - - for (auto& root : registry.handlerRegistryRoots) - { - if (root->config.show) - root->draw(nullptr, 0.0f, 0.0f); - } - - for (auto& root : registry.textureRegistryRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.themeRegistryRoots) - { - if(root->config.show) - ((mvTheme*)root.get())->push_theme_components(); - } - - for (auto& root : registry.filedialogRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.colormapRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.windowRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.viewportMenubarRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.viewportDrawlistRoots) - root->draw(nullptr, 0.0f, 0.0f); - - for (auto& root : registry.themeRegistryRoots) - { - if (root->config.show) - ((mvTheme*)root.get())->pop_theme_components(); - } - - for (auto& root : registry.debugWindows) - { - ImGui::SetNextWindowSize(ImVec2(500.0f, 500.0f), ImGuiCond_FirstUseEver); - - if (!ImGui::Begin(root->config.specifiedLabel.c_str(), &root->info.showDebug)) - { - ImGui::End(); - - if (!root->info.showDebug) - RemoveDebugWindow(*GContext->itemRegistry, root->uuid); - return; - } - - static char ts[6] = "True"; - static char fs[6] = "False"; - - std::string width = std::to_string(root->config.width); - std::string height = std::to_string(root->config.height); - - std::string sizex = std::to_string(root->state.rectSize.x); - std::string sizey = std::to_string(root->state.rectSize.y); - - ImGui::PushID(root.get()); - DebugItem("Label:", root->config.specifiedLabel.c_str()); - DebugItem("ID:", std::to_string(root->uuid).c_str()); - DebugItem("Alias:", root->config.alias.c_str()); - DebugItem("Type:", DearPyGui::GetEntityTypeString(root->type)); - DebugItem("Filter:", root->config.filter.c_str()); - DebugItem("Payload Type:", root->config.payloadType.c_str()); - DebugItem("Location:", std::to_string(root->info.location).c_str()); - DebugItem("Track Offset:", std::to_string(root->config.trackOffset).c_str()); - DebugItem("Container:", DearPyGui::GetEntityDesciptionFlags(root->type) & MV_ITEM_DESC_CONTAINER ? ts : fs); - DebugItem("Width:", width.c_str()); - DebugItem("Height:", height.c_str()); - DebugItem("Size x:", sizex.c_str()); - DebugItem("Size y:", sizey.c_str()); - DebugItem("Show:", root->config.show ? ts : fs); - DebugItem("Enabled:", root->config.enabled ? ts : fs); - DebugItem("Tracked:", root->config.tracked ? ts : fs); - DebugItem("Callback:", root->config.callback ? ts : fs); - DebugItem("User Data:", *(root->config.user_data) ? ts : fs); - DebugItem("Drop Callback:", root->config.dropCallback ? ts : fs); - DebugItem("Drag Callback:", root->config.dragCallback ? ts : fs); - - ImGui::Spacing(); - ImGui::Spacing(); - ImGui::Spacing(); - ImGui::Text("Bindings"); - ImGui::Separator(); - DebugItem("Theme Bound:", root->theme ? ts : fs); - DebugItem("Font Bound:", root->font ? ts : fs); - DebugItem("Handlers Bound:", root->handlerRegistry ? ts : fs); - - i32 applicableState = DearPyGui::GetApplicableState(root->type); - ImGui::Spacing(); - ImGui::Spacing(); - ImGui::Spacing(); - ImGui::Text("State"); - ImGui::Separator(); - if (applicableState & MV_STATE_VISIBLE) DebugItem("Item Visible:", IsItemVisible(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_HOVER) DebugItem("Item Hovered:", IsItemHovered(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_ACTIVE) DebugItem("Item Active:", IsItemActive(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_FOCUSED) DebugItem("Item Focused:", IsItemFocused(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_CLICKED) - { - DebugItem("Item Left Clicked:", IsItemLeftClicked(root->state, 1) ? ts : fs); - DebugItem("Item Right Clicked:", IsItemRightClicked(root->state, 1) ? ts : fs); - DebugItem("Item Middle Clicked:", IsItemMiddleClicked(root->state, 1) ? ts : fs); - } - if (applicableState & MV_STATE_EDITED) DebugItem("Item Edited:", IsItemEdited(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_ACTIVATED) DebugItem("Item Activated:", IsItemActivated(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_DEACTIVATED) DebugItem("Item Deactivated:", IsItemDeactivated(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_DEACTIVATEDAE) DebugItem("Item DeactivatedAfterEdit:", IsItemDeactivatedAfterEdit(root->state, 1) ? ts : fs); - if (applicableState & MV_STATE_TOGGLED_OPEN) DebugItem("Item ToggledOpen:", IsItemToogledOpen(root->state, 1) ? ts : fs); - - ImGui::PopID(); - - ImGui::End(); - - if (!root->info.showDebug) - RemoveDebugWindow(*GContext->itemRegistry, root->uuid); - } - -} - -void -ResetTheme(mvItemRegistry& registry) -{ - for (auto& root : registry.themeRegistryRoots) - root->config.show = false; -} - -mvAppItem* -GetItem(mvItemRegistry& registry, mvUUID uuid) -{ - // check captured - auto& capturedItem = mvItemRegistry::threadContext.capturedItem; - if (capturedItem && capturedItem->uuid == uuid) - return capturedItem.get(); - - auto found = registry.allItems.find(uuid); - return found != registry.allItems.end()? found->second : nullptr; -} - -std::shared_ptr -GetRefItem(mvItemRegistry& registry, mvUUID uuid) -{ - mvAppItem* item = GetItem(registry, uuid); - return item? item->shared_from_this() : nullptr; -} - -mvWindowAppItem* -GetWindow(mvItemRegistry& registry, mvUUID uuid) -{ - - mvAppItem* item = GetItem(registry, uuid); - if (item == nullptr) - { - assert(false && "Window not found."); - return nullptr; - } - - if (item->type == mvAppItemType::mvWindowAppItem) - return static_cast(item); - - assert(false && "Item is not a window."); - return nullptr; -} - -void -ClearItemRegistry(mvItemRegistry& registry) -{ - registry.colormapRoots.clear(); - registry.filedialogRoots.clear(); - registry.stagingRoots.clear(); - registry.viewportMenubarRoots.clear(); - registry.windowRoots.clear(); - registry.fontRegistryRoots.clear(); - registry.handlerRegistryRoots.clear(); - registry.textureRegistryRoots.clear(); - registry.valueRegistryRoots.clear(); - registry.themeRegistryRoots.clear(); - registry.itemTemplatesRoots.clear(); - registry.itemHandlerRegistryRoots.clear(); - registry.viewportDrawlistRoots.clear(); -} - -b8 -AddItemWithRuntimeChecks(mvItemRegistry& registry, std::shared_ptr item, mvUUID parent, mvUUID before) -{ - - auto& threadContext = mvItemRegistry::threadContext; - - if (threadContext.captureCallback) - { - - // this is a unique situation in that the caller always has the GIL - threadContext.capturedItem = item; - // resetting captureCallback in advance in order to avoid recursion (if the callback - // attempts to add another item or move an item) - mvPyObject captureCallback(std::move(threadContext.captureCallback)); - threadContext.captureCallback = nullptr; - mvRunCallback(captureCallback, nullptr, threadContext.capturedItem->uuid); - return true; - } - - if (item == nullptr) - return false; - - // check if item is ok - if (!item->state.ok) - return false; - - mvPySafeLockGuard lk(GContext->mutex); - - //--------------------------------------------------------------------------- - // STEP 0: update "last" information - //--------------------------------------------------------------------------- - if (DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_ROOT) - { - threadContext.lastRootAdded = item->uuid; - threadContext.lastContainerAdded = item->uuid; - } - else if (DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_CONTAINER) - threadContext.lastContainerAdded = item->uuid; - - threadContext.lastItemAdded = item->uuid; - - //--------------------------------------------------------------------------- - // STEP 1: check if an item with this name exists (NO LONGER NEEDED) - //--------------------------------------------------------------------------- - //if (getItem(item->uuid)) - //{ - // mvThrowPythonEr1ror(mvErrorCode::mvNon1e, "Item must have a unique name."); - // MV_ITEM_REGISTRY_WARN("Item must have a unique name."); - // assert(false); - // return false; - //} - - //--------------------------------------------------------------------------- - // STEP 2: handle root case - //--------------------------------------------------------------------------- - if (DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_ROOT) - { - AddRoot(registry, item); - return true; - } - - //--------------------------------------------------------------------------- - // STEP 3: attempt to deduce parent - //--------------------------------------------------------------------------- - if (item->type == mvAppItemType::mvTooltip && parent == 0) - parent = item->config.parent; - - mvAppItem* parentPtr = nullptr; - if (before > 0) - { - // Adding it before the "before" item - let's find it! - mvAppItem* beforeItem = GetItem(registry, before); - if (beforeItem == nullptr) - { - mvThrowPythonError(mvErrorCode::mvItemNotFound, "add_*", "Item not found: " + std::to_string(before), nullptr); - IM_ASSERT(false && "The 'before' item could not be found."); - return false; - } - // We'll need the parent anyway in order to check compatibility - parentPtr = beforeItem->info.parentPtr; - } - - else if (parent >= MV_START_UUID) - { - // Append to children of the specified parent - parentPtr = GetItem(registry, parent); - } - - else if (parent == 0) - { - // Take the parent from stack and add to the end - parentPtr = TopParent(registry); - } - - // reserved uuid case - else - { - parentPtr = GetItem(registry, parent); - if (!parentPtr) - { - // revert to stack operation (reserved uuid not used) - parentPtr = TopParent(registry); - } - } - - //--------------------------------------------------------------------------- - // STEP 4: check if parent was deduced - //--------------------------------------------------------------------------- - if (parentPtr == nullptr) - { - mvThrowPythonError(mvErrorCode::mvParentNotDeduced, "add_*", "Parent could not be deduced.", item.get()); - IM_ASSERT(false && "Parent could not be deduced."); - return false; - } - - //--------------------------------------------------------------------------- - // STEP 5: check if parent is a compatible type - //--------------------------------------------------------------------------- - b8 isParentCompatible = false; - const std::vector>* allowableParents = &DearPyGui::GetAllowableParents(item->type); - - std::string acceptableParentTypes; - - for (const auto& compatibleParent : *allowableParents) - { - acceptableParentTypes.append(compatibleParent.first + "\n"); - if ((i32)parentPtr->type == compatibleParent.second) - { - isParentCompatible = true; - break; - } - } - - if (!isParentCompatible) - { - if (allowableParents->empty()) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleParent, GetEntityCommand(item->type), - "Incompatible parent. Item does can not have a parent.", item.get()); - return false; - } - - if ((*allowableParents)[0].second != (i32) mvAppItemType::All) - { - - mvThrowPythonError(mvErrorCode::mvIncompatibleParent, GetEntityCommand(item->type), - "Incompatible parent. Acceptable parents include:\t" + acceptableParentTypes, item.get()); - - IM_ASSERT(false && "Incompatible parent."); - return false; - } - } - - //--------------------------------------------------------------------------- - // STEP 6: check if parent accepts our item (this isn't duplicate STEP 3) - //--------------------------------------------------------------------------- - b8 amICompatible = false; - const std::vector>* allowableChildren = &DearPyGui::GetAllowableChildren(parentPtr->type); - - std::string acceptableChildTypes; - - for (const auto& compatibleChildren : *allowableChildren) - { - acceptableChildTypes.append(compatibleChildren.first + "\n"); - if ((i32)item->type == compatibleChildren.second) - { - amICompatible = true; - break; - } - } - - if (!amICompatible) - { - if (allowableChildren->empty()) - { - mvThrowPythonError(mvErrorCode::mvIncompatibleChild, GetEntityCommand(parentPtr->type), - "Incompatible child. Item does not accept children.", parentPtr); - return false; - } - - if ((*allowableChildren)[0].second != (i32)mvAppItemType::All) - { - - mvThrowPythonError(mvErrorCode::mvIncompatibleChild, GetEntityCommand(parentPtr->type), - "Incompatible child. Acceptable children include:\t" + acceptableChildTypes, parentPtr); - - IM_ASSERT(false && "Incompatible child."); - return false; - } - } - - //--------------------------------------------------------------------------- - // STEP 7: add items who require "after" adding (tooltip) - //--------------------------------------------------------------------------- - if (item->type == mvAppItemType::mvTooltip) - { - mvAppItem* prevItemParent = parentPtr->info.parentPtr; - if (prevItemParent && prevItemParent->type == mvAppItemType::mvTable) - { - prevItemParent->childslots[2][parentPtr->info.location] = item; - return true; - } - else - { - return AddItemAfter(registry, parent, item); - } - } - - //--------------------------------------------------------------------------- - // STEP 8: Either append it to parent's children or insert before the "before" - //--------------------------------------------------------------------------- - return AddRuntimeChild(parentPtr, before, item); -} - -void -AddAlias(mvItemRegistry& registry, const std::string& alias, mvUUID id) -{ - if (!GContext->IO.allowAliasOverwrites) - { - if (DoesAliasExist(registry, alias)) - { - mvThrowPythonError(mvErrorCode::mvNone, "add alias", - "Alias already exists", nullptr); - return; - } - } - - registry.aliases[alias] = id; - - mvAppItem* item = GetItem(registry, id); - if (item) - item->config.alias = alias; -} - -void -RemoveAlias(mvItemRegistry& registry, const std::string& alias, b8 itemTriggered) -{ - - if (alias.empty()) - return; - - if (!DoesAliasExist(registry, alias)) - { - mvThrowPythonError(mvErrorCode::mvNone, "remove alias", - "Alias does not exists", nullptr); - return; - } - - mvAppItem* item = GetItem(registry, registry.aliases[alias]); - if (item) - item->config.alias.clear(); - - if (itemTriggered) - { - if (!GContext->IO.manualAliasManagement) - registry.aliases.erase(alias); - } - else - registry.aliases.erase(alias); - -} - -mvUUID -GetIdFromAlias(mvItemRegistry& registry, const std::string& alias) -{ - if (DoesAliasExist(registry, alias)) - return registry.aliases[alias]; - return 0; -} \ No newline at end of file diff --git a/src/mvItemRegistry.h b/src/mvItemRegistry.h deleted file mode 100644 index df2fc657e..000000000 --- a/src/mvItemRegistry.h +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "mvAppItem.h" -#include "mvPyUtils.h" - -//----------------------------------------------------------------------------- -// forward declarations -//----------------------------------------------------------------------------- -struct mvItemRegistry; -class mvWindowAppItem; - -//----------------------------------------------------------------------------- -// public API -//----------------------------------------------------------------------------- - -void RenderItemRegistry(mvItemRegistry& registry); - -// cleanup -void ClearItemRegistry(mvItemRegistry& registry); -b8 DeleteItem (mvItemRegistry& registry, mvUUID uuid, b8 childrenOnly = false, i32 slot = -1); - -// aliases -void AddAlias (mvItemRegistry& registry, const std::string& alias, mvUUID id); -void RemoveAlias (mvItemRegistry& registry, const std::string& alias, b8 itemTriggered = false); -mvUUID GetIdFromAlias(mvItemRegistry& registry, const std::string& alias); - -// item movement -b8 MoveItem (mvItemRegistry& registry, mvUUID uuid, mvUUID parent, mvUUID before); -b8 MoveItemUp (mvItemRegistry& registry, mvUUID uuid); -b8 MoveItemDown(mvItemRegistry& registry, mvUUID uuid); - -// item retrieval -mvUUID GetIDFromPyObject(PyObject* item); -// Note: this function is *not* threadsafe and must be called with mvContext::mutex locked -mvAppItem* GetItem (mvItemRegistry& registry, mvUUID uuid); -// Note: this function is *not* threadsafe and must be called with mvContext::mutex locked -std::shared_ptr GetRefItem (mvItemRegistry& registry, mvUUID uuid); -mvWindowAppItem* GetWindow (mvItemRegistry& registry, mvUUID uuid); -mvAppItem* GetItemRoot (mvItemRegistry& registry, mvUUID uuid); - -// item operations -b8 AddItemWithRuntimeChecks(mvItemRegistry& registry, std::shared_ptr item, mvUUID parent, mvUUID before); -void ResetTheme (mvItemRegistry& registry); -b8 ReorderChildren (mvItemRegistry& registry, mvUUID parent, i32 slot, const std::vector& new_order); - -//----------------------------------------------------------------------------- -// mvThreadContext -// - Holds thread-local data used together with mvItemRegistry -//----------------------------------------------------------------------------- - -struct mvThreadContext -{ - // "last item" state - mvUUID lastItemAdded = 0; - mvUUID lastContainerAdded = 0; - mvUUID lastRootAdded = 0; - - std::stack> containers; // parent stack, top of stack becomes widget's parent - - std::shared_ptr capturedItem = nullptr; - mvPyObject captureCallback = nullptr; - mvPyObject captureCallbackUserData = nullptr; -}; - -//----------------------------------------------------------------------------- -// mvItemRegistry -// - Responsibilities: -// * holds widget hierarchy roots (windows) -// * keeping up with the active window -// * managing the parent deduction system (parent stack) -// * acts as the interface for accessing widgets -// * creates the "standard" windows on startup (debug, about, etc.) -//----------------------------------------------------------------------------- - -struct mvItemRegistry -{ - - // misc - std::unordered_map aliases; - std::unordered_map allItems; // used for quick access to items by UUID - - static thread_local mvThreadContext threadContext; - - // debug items - b8 showImGuiDebug = false; - b8 showImPlotDebug = false; - std::vector> debugWindows; - - // roots - std::vector> colormapRoots; - std::vector> filedialogRoots; - std::vector> stagingRoots; - std::vector> viewportMenubarRoots; - std::vector> windowRoots; - std::vector> fontRegistryRoots; - std::vector> handlerRegistryRoots; - std::vector> itemHandlerRegistryRoots; - std::vector> textureRegistryRoots; - std::vector> valueRegistryRoots; - std::vector> themeRegistryRoots; - std::vector> itemTemplatesRoots; - std::vector> viewportDrawlistRoots; - - mvItemRegistry(); -}; \ No newline at end of file diff --git a/src/mvLayoutWindow.cpp b/src/mvLayoutWindow.cpp deleted file mode 100644 index 6092fe227..000000000 --- a/src/mvLayoutWindow.cpp +++ /dev/null @@ -1,857 +0,0 @@ -#include "mvLayoutWindow.h" - -#include "mvContext.h" -#include "mvItemRegistry.h" -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvToolManager.h" -#include "mvFontManager.h" - -#include -#include -#include - -static void -DebugItem(const char* label, const char* item) { - ImGui::Text("%s", label); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%s", item); -} - -static void -DebugItem(const char* label, float value) { - ImGui::Text("%s", label); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "%g", value); -} - -static void -DebugItem(const char* label, mvVec2 value) { - ImGui::Text("%s", label); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "(%g, %g)", value.x, value.y); -} - -static void -DebugItem(const char* label, bool value) { - DebugItem(label, value? "True" : "False"); -} - -static void InfoHeader(const char* label) { - ImGui::NewLine(); - ImGui::Text("%s", label); - ImGui::Separator(); -} - -mvLayoutWindow::mvLayoutWindow() -{ - m_windowflags = ImGuiWindowFlags_NoSavedSettings; -} - -void mvLayoutWindow::renderRootCategory(const char* category, std::vector>& roots) -{ - - const auto node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | (roots.empty() ? ImGuiTreeNodeFlags_Leaf : 0); - - ImGui::PushID(&roots); - - if (_expandToSelected) - { - for (auto& root : roots) - { - if (root->uuid == m_selectedItem || _itemsToExpand.count(root->uuid) > 0) - { - ImGui::SetNextItemOpen(true); - break; - } - } - } - - const auto expanded = ImGui::TreeNodeEx(category, node_flags); - - if (!roots.empty()) - { - ImGui::SameLine(); - ImGui::TextColored({0.7f, 0.7f, 0.7f, 1.0f}, "(%zd)", roots.size()); - } - - if (expanded) - { - for (auto& root : roots) - renderTreeNode(root); - ImGui::TreePop(); - } - - ImGui::PopID(); -} - -void mvLayoutWindow::renderTreeNode(std::shared_ptr& item) -{ - - // build up flags for current node - const auto node_flags = ImGuiTreeNodeFlags_OpenOnArrow - | ImGuiTreeNodeFlags_OpenOnDoubleClick - | ((item->uuid == m_selectedItem) ? ImGuiTreeNodeFlags_Selected : 0) - | (DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_CONTAINER ? 0 : ImGuiTreeNodeFlags_Leaf); - - // render this node - ImGui::PushID(item.get()); - std::string labelToShow; - // Remember whether we have a custom name for this item, like a label or a tag. - // Otherwise we'll have to show its type name instead, which is not as descriptive. - bool is_labeled = true; - if (!item->config.alias.empty()) - labelToShow = item->config.alias; - else if (!item->config.specifiedLabel.empty()) - labelToShow = item->config.specifiedLabel; - else - { - is_labeled = false; - labelToShow = DearPyGui::GetEntityTypeString(item->type); - constexpr const char* prefix = "mvAppItemType::"; - // This is a cumbersome way to get string length, but it's the only way - // that provides a constexpr (note: strlen() is not a constexpr). - // Well, we could also do a `sizeof(prefix) - 1`... - constexpr size_t prefix_len = std::char_traits::length(prefix); - if (labelToShow.compare(0, prefix_len, prefix) == 0) - labelToShow.erase(0, prefix_len); - } - - - if (!_imguiFilter.PassFilter(labelToShow.c_str()) && _startFiltering) - { - ImGui::PopID(); - return; - } - - bool expandThisNode = (_expandToSelected && _itemsToExpand.count(item->uuid) > 0); - if (expandThisNode) - { - ImGui::SetNextItemOpen(true); - } - - // TODO: add a flag to GetEntityDescriptionFlags for this - bool is_bindable = (item->type == mvAppItemType::mvTheme || - item->type == mvAppItemType::mvItemHandlerRegistry || - item->type == mvAppItemType::mvFont ); - - // An unused/orhpaned bindable? (note that we might be holding 1 ref to item) - bool is_lonely = (is_bindable && item.use_count() <= (1 + (item == _itemref? 1 : 0))); - - // An extra check for some elements that can have global refs *not* shared - // via shared_ptr. - // - the global theme is the only one that has config.show == true - // - the global font is stored in mvFontManager and the font manager knows how to check this - if (is_lonely && ( - (item->type == mvAppItemType::mvTheme && item->config.show) || - (item->type == mvAppItemType::mvFont && mvToolManager::GetFontManager().isDefaultFont(item)))) - { - // It's bound as a global entity and therefore is not lonely - is_lonely = false; - } - - if (is_lonely) - { - ImGui::PushStyleColor(ImGuiCol_Text, {1.0f, 1.0f, 1.0f, 0.5f}); - } - - if (is_labeled) - { - // We're keeping alpha because some sub-trees might be translucent - auto alpha = ImGui::GetStyleColorVec4(ImGuiCol_Text).w; - ImGui::PushStyleColor(ImGuiCol_Text, {0.7f, 0.7f, 1.0f, alpha}); - } - - // Render the node itself - const auto expanded = ImGui::TreeNodeEx(labelToShow.c_str(), node_flags); - - if (expandThisNode) - { - ImGui::SetScrollHereX(); - ImGui::SetScrollHereY(); - } - - if (is_labeled) - ImGui::PopStyleColor(); - - if (ImGui::IsItemHovered()) - highlightItemRect(item.get()); - - if (item->uuid == m_selectedItem) - _startFiltering = true; - - // processing for selecting node - if (ImGui::IsItemClicked()) - { - m_selectedItem = item->uuid; - _itemref = item; - } - - if (is_lonely) - { - ImGui::SameLine(); - ImGui::Text("(not bound)"); - } - - if (!(DearPyGui::GetEntityDesciptionFlags(item->type) & MV_ITEM_DESC_CONTAINER)) - { - if (is_lonely) - ImGui::PopStyleColor(); - if(expanded) - ImGui::TreePop(); - ImGui::PopID(); - if (item->uuid == m_selectedItem) - _startFiltering = false; - return; - } - - if (expanded) - { - - int i = 0; - for (auto& childrenSet : item->childslots) - { - if (_slots) - { - std::string title = "Child Slot: " + std::to_string(i++); - // Only expand a slot if there's something more to expand within it - if (expandThisNode) - { - for (auto& child : childrenSet) - { - if (child && _itemsToExpand.count(child->uuid) > 0) - { - ImGui::SetNextItemOpen(true); - break; - } - } - } - - ImGui::PushStyleColor(ImGuiCol_Text, {0.7f, 0.7f, 0.7f, 1.0f}); - const auto slot_expanded = ImGui::TreeNodeEx(title.c_str(), childrenSet.empty() ? ImGuiTreeNodeFlags_Leaf : 0); - ImGui::PopStyleColor(); - if (slot_expanded) - { - for (auto& children : childrenSet) - if(children) - renderTreeNode(children); - ImGui::TreePop(); - } - } - else - { - for (auto& children : childrenSet) - if(children) - renderTreeNode(children); - } - } - ImGui::TreePop(); - } - - if (is_lonely) - ImGui::PopStyleColor(); - - ImGui::PopID(); - - if (item->uuid == m_selectedItem) - _startFiltering = false; - -} - -void mvLayoutWindow::drawWidgets() -{ - - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; - - bool pickerEnabled = _picker; - if (pickerEnabled) - { - ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_ButtonHovered)); - } - if (ImGui::Button("Pick...")) - { - _picker = !_picker; - } - if (pickerEnabled) - { - ImGui::PopStyleColor(); - } - if (_picker) - { - mvUUID hoveredItem = getHoveredItem(); - if (hoveredItem) - highlightItemRect(GetItem(*GContext->itemRegistry, hoveredItem)); - - // When picker is enabled, swallow the first click we get, and look at - // what is hovered - but don't abuse our own window. - if (ImGui::IsMouseClicked(0) && !ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) - { - // Pretend that nothing happened :) - g.IO.MouseDownDuration[0] = g.IO.MouseDownDurationPrev[0] = -1.0f; - g.IO.MouseDown[0] = g.IO.MouseClicked[0] = false; - // Show that hovered item - jumpToItem(hoveredItem); - _picker = false; - } - - } - - ImGui::SameLine(); - - if (ImGui::Button("Focused")) - { - if (!jumpToItem(GContext->focusedItem)) - showError("No focused item."); - } - - ImGui::SameLine(); - - const char* hint = "tag or uuid"; - ImVec2 hint_size = ImGui::CalcTextSize(hint); - ImGui::SetNextItemWidth(hint_size.x + 2*style.FramePadding.x); - // This input, while it doesn't need a label, *must* use a non-empty ID due to ImGui - // restrictions. That's why we put an explicit ID here. - if (ImGui::InputTextWithHint("###uuid-search", hint, &_search_tag, ImGuiInputTextFlags_AutoSelectAll|ImGuiInputTextFlags_EnterReturnsTrue) - && _search_tag.find_first_not_of(' ') != std::string::npos) - { - mvUUID uuid = GetIdFromAlias(*GContext->itemRegistry, _search_tag); - if (!uuid) - { - try - { - size_t converted = 0; - uuid = std::stoull(_search_tag, &converted); - // Make sure we've used all non-whitespace chars, i.e. the input is a valid - // number and not something like "123die" - if (_search_tag.find_first_not_of(' ', converted) != std::string::npos) - { - // Invalid input - reset it back to 0 - uuid = 0; - } - } - catch (...) - { - uuid = 0; - } - } - if (!jumpToItem(uuid)) - showError("Item not found."); - } - - ImGui::SameLine(); - ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); - ImGui::SameLine(); - - if (_itemref == nullptr) - { - ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); - ImGui::PushStyleColor(ImGuiCol_Text, {1.0f, 1.0f, 1.0f, 0.5f}); - } - - if (ImGui::ArrowButton("Move Up", ImGuiDir_Up)) - { - mvSubmitCallback([&]() - { - mvPySafeLockGuard lk(GContext->mutex); - MoveItemUp(*GContext->itemRegistry, m_selectedItem); - }); - } - - ImGui::SameLine(); - if (ImGui::ArrowButton("Move Down", ImGuiDir_Down)) - { - mvSubmitCallback([&]() - { - mvPySafeLockGuard lk(GContext->mutex); - MoveItemDown(*GContext->itemRegistry, m_selectedItem); - }); - } - ImGui::SameLine(); - if (ImGui::Button("Delete")) - { - mvSubmitCallback([&]() - { - mvPySafeLockGuard lk(GContext->mutex); - DeleteItem(*GContext->itemRegistry, m_selectedItem, false); - m_selectedItem = 0; - resetSelectedItem(); - }); - } - ImGui::SameLine(); - if (ImGui::Button("Show") && _itemref != nullptr) - { - _itemref->config.show = true; - _itemref->info.shownLastFrame = true; - } - ImGui::SameLine(); - if (ImGui::Button("Hide") && _itemref != nullptr) - { - _itemref->config.show = false; - _itemref->info.hiddenLastFrame = true; - } - - if (_itemref == nullptr) - { - ImGui::PopStyleColor(); - ImGui::PopItemFlag(); - } - - ImGui::SameLine(); - ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); - ImGui::SameLine(); - - ImGui::SameLine(); - ImGui::Checkbox("Show Slots###layout", &_slots); - - ImGui::Separator(); - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(4, 0)); - if (ImGui::BeginTable("", 2, ImGuiTableFlags_Resizable|ImGuiTableFlags_NoSavedSettings|ImGuiTableFlags_BordersInnerV|ImGuiTableFlags_SizingFixedFit|ImGuiTableFlags_NoKeepColumnsVisible)) - { - ImGui::TableSetupColumn(""); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 1.0f); - - ImGui::TableNextRow(); - // left side - ImGui::TableNextColumn(); - - // We want the left side to initially be no narrower than this line - ImVec2 spacer_size = ImGui::CalcTextSize("Type:mvAppItemType::mvWindowAppItem"); - // The left size will initially have a scrollbar, so let's add some space; - // let's also account for item spacing between "type:" and its value (item spacing x), - // and add more padding on the right (let's use frame padding for now). - spacer_size.x += style.ScrollbarSize + style.ItemSpacing.x + style.FramePadding.x; - // No need for vertical offset - spacer_size.y = 0; - // Adding some fake contents that the table will use for auto-fitting - // 1st column (note that the child window below is not used for fitting: - // it itself inherits width from the column). - ImGui::Dummy(spacer_size); - - // We only render item details if there's a selected item OR if - // we've been able to select another item (i.e. there's at least - // something available in the item tree). - if (_itemref != nullptr || resetSelectedItem()) - { - ImGui::BeginChild("###layoutwindow", ImVec2(0, 0)); - static char ts[6] = "True"; - static char fs[6] = "False"; - - std::string width = std::to_string(_itemref->config.width); - std::string height = std::to_string(_itemref->config.height); - - ImGui::PushID(_itemref.get()); - DebugItem("Label:", _itemref->config.specifiedLabel.c_str()); - DebugItem("ID:", std::to_string(_itemref->uuid).c_str()); - DebugItem("Alias:", _itemref->config.alias.c_str()); - DebugItem("Type:", DearPyGui::GetEntityTypeString(_itemref->type)); - - ImGui::Spacing(); - ImGui::Spacing(); - - DebugItem("Show:", _itemref->config.show); - DebugItem("Enabled:", _itemref->config.enabled); - - DebugItem("Pos:", _itemref->state.pos); - DebugItem("Width:", width.c_str()); - DebugItem("Height:", height.c_str()); - - DebugItem("Rect:", _itemref->state.rectMin); - ImGui::SameLine(); - DebugItem("-", _itemref->state.rectMax); - DebugItem("Size:", _itemref->state.rectSize); - - ImGui::Spacing(); - ImGui::Spacing(); - - DebugItem("Container:", DearPyGui::GetEntityDesciptionFlags(_itemref->type) & MV_ITEM_DESC_CONTAINER ? ts : fs); - DebugItem("Location:", std::to_string(_itemref->info.location).c_str()); - DebugItem("Filter:", _itemref->config.filter.c_str()); - - DebugItem("Tracked:", _itemref->config.tracked); - DebugItem("Track Offset:", _itemref->config.trackOffset); - - ImGui::Spacing(); - ImGui::Spacing(); - - DebugItem("Callback:", _itemref->config.callback ? ts : fs); - DebugItem("User Data:", *(_itemref->config.user_data) ? ts : fs); - DebugItem("Drop Callback:", _itemref->config.dropCallback ? ts : fs); - DebugItem("Drag Callback:", _itemref->config.dragCallback ? ts : fs); - DebugItem("Payload Type:", _itemref->config.payloadType.c_str()); - - renderTypeSpecificInfo(); - - InfoHeader("Bindings"); - // TODO: make it a hyperlink to the theme - DebugItem("Theme Bound:", _itemref->theme ? ts : fs); - // TODO: make it a hyperlink to the font - DebugItem("Font Bound:", _itemref->font ? ts : fs); - // TODO: make it a hyperlink to the handlers - DebugItem("Handlers Bound:", _itemref->handlerRegistry ? ts : fs); - - int applicableState = DearPyGui::GetApplicableState(_itemref->type); - InfoHeader("State"); - if (applicableState & MV_STATE_VISIBLE) DebugItem("Item Visible:", IsItemVisible(_itemref->state, 1)); - if (applicableState & MV_STATE_HOVER) DebugItem("Item Hovered:", IsItemHovered(_itemref->state, 1)); - if (applicableState & MV_STATE_ACTIVE) DebugItem("Item Active:", IsItemActive(_itemref->state, 1)); - if (applicableState & MV_STATE_FOCUSED) DebugItem("Item Focused:", IsItemFocused(_itemref->state, 1)); - if (applicableState & MV_STATE_CLICKED) - { - DebugItem("Item Left Clicked:", IsItemLeftClicked(_itemref->state, 1)); - DebugItem("Item Right Clicked:", IsItemRightClicked(_itemref->state, 1)); - DebugItem("Item Middle Clicked:", IsItemMiddleClicked(_itemref->state, 1)); - } - if (applicableState & MV_STATE_EDITED) DebugItem("Item Edited:", IsItemEdited(_itemref->state, 1)); - if (applicableState & MV_STATE_ACTIVATED) DebugItem("Item Activated:", IsItemActivated(_itemref->state, 1)); - if (applicableState & MV_STATE_DEACTIVATED) DebugItem("Item Deactivated:", IsItemDeactivated(_itemref->state, 1)); - if (applicableState & MV_STATE_DEACTIVATEDAE) DebugItem("Item DeactivatedAfterEdit:", IsItemDeactivatedAfterEdit(_itemref->state, 1)); - if (applicableState & MV_STATE_TOGGLED_OPEN) DebugItem("Item ToggledOpen:", IsItemToogledOpen(_itemref->state, 1)); - - ImGui::PopID(); - ImGui::EndChild(); - } - - // right side - ImGui::TableNextColumn(); - _imguiFilter.Draw(); - _startFiltering = false; - - if (_expandToSelected) - { - mvAppItem* parent = _itemref->info.parentPtr; - while (parent) - { - _itemsToExpand.insert(parent->uuid); - parent = parent->info.parentPtr; - } - } - - ImGui::BeginChild("TreeChild", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); - renderRootCategory("Windows", GContext->itemRegistry->windowRoots); - renderRootCategory("Themes", GContext->itemRegistry->themeRegistryRoots); - renderRootCategory("Template Registries", GContext->itemRegistry->itemTemplatesRoots); - renderRootCategory("Staging Containers", GContext->itemRegistry->stagingRoots); - renderRootCategory("Texture Registries", GContext->itemRegistry->textureRegistryRoots); - renderRootCategory("Font Registries", GContext->itemRegistry->fontRegistryRoots); - renderRootCategory("Item Handler Registries", GContext->itemRegistry->itemHandlerRegistryRoots); - renderRootCategory("Handler Registries", GContext->itemRegistry->handlerRegistryRoots); - renderRootCategory("Value Registries", GContext->itemRegistry->valueRegistryRoots); - renderRootCategory("Colormap Registries", GContext->itemRegistry->colormapRoots); - renderRootCategory("File Dialogs", GContext->itemRegistry->filedialogRoots); - renderRootCategory("Viewport Menubars", GContext->itemRegistry->viewportMenubarRoots); - renderRootCategory("Viewport Drawlists", GContext->itemRegistry->viewportDrawlistRoots); - ImGui::EndChild(); - - // No longer need to expand the tree - _expandToSelected = false; - _itemsToExpand.clear(); - - ImGui::EndTable(); - } - - ImGui::PopStyleVar(); - renderErrorMessage(); -} - -void mvLayoutWindow::renderThemeComponentInfo(mvAppItem* item) -{ - if (!item || item->type != mvAppItemType::mvThemeComponent) - return; - auto comp = static_cast(item); - DebugItem("Enabled State:", comp->_specificEnabled); - mvAppItemType target_type = (mvAppItemType)comp->_specificType; - DebugItem("Applies to:", (target_type == mvAppItemType::All)? "All item types" : DearPyGui::GetEntityTypeString(target_type)); -} - -void mvLayoutWindow::renderBindCount() -{ - auto count_str = std::to_string(_itemref.use_count() - 2); - DebugItem("Bound to:", count_str.c_str()); - ImGui::SameLine(); - ImGui::Text("items"); -} - -void mvLayoutWindow::renderTypeSpecificInfo() -{ - switch (_itemref->type) - { - case mvAppItemType::mvTheme: - { - InfoHeader("Theme"); - // Most themes will have False here, so let's not clutter the UI for them - if (_itemref->config.show) - { - DebugItem("Global Theme:", true); - } - renderBindCount(); - } - break; - - case mvAppItemType::mvThemeComponent: - { - InfoHeader("Theme"); - renderThemeComponentInfo(_itemref.get()); - } - break; - - case mvAppItemType::mvThemeColor: - { - InfoHeader("Theme"); - auto item = static_cast(_itemref.get()); - renderThemeComponentInfo(item->info.parentPtr); - - // TODO: add accessors for lib type and color index - // switch (item->_libType) - - // OMG. This is horrible. We might be better off having a typed - // accessor for this, too. - auto color = *static_cast>*>(item->getValue()); - - ImGui::AlignTextToFramePadding(); - ImGui::Text("Color:"); - ImGui::SameLine(); - - // Making it fixed-width so that prefixes do not show up - they look - // messy in that little space the layout window typically has. - float text_width = ImGui::CalcTextSize("255").x; - const ImGuiStyle& style = ImGui::GetStyle(); - float total_width = (text_width <= 0.0f)? -1.0f : 4*(text_width + 2*style.FramePadding.x + style.ItemInnerSpacing.x) + ImGui::GetFrameHeight(); - ImGui::SetNextItemWidth(total_width); - - ImGui::PushStyleColor(ImGuiCol_Text, {1.0f, 0.0f, 1.0f, 1.0f}); - ImGui::ColorEdit4("##color", &(*color)[0], ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoBorder | ImGuiColorEditFlags_NoLabel); - ImGui::PopStyleColor(); - } - break; - - case mvAppItemType::mvThemeStyle: - { - InfoHeader("Theme"); - auto item = static_cast(_itemref.get()); - renderThemeComponentInfo(item->info.parentPtr); - - // TODO: add accessors for lib type and style index - // switch (item->_libType) - - // OMG. This is horrible. We might be better off having a typed - // accessor for this, too. - auto value = *static_cast>*>(item->getValue()); - - ImGui::AlignTextToFramePadding(); - ImGui::Text("Value:"); - ImGui::SameLine(); - ImGui::PushStyleColor(ImGuiCol_Text, {1.0f, 0.0f, 1.0f, 1.0f}); - float value_buf[2] = {(*value)[0], (*value)[1]}; - if (ImGui::DragFloat2("##style", value_buf, 1.0f, 0.0f, 100.0f, "%g")) - { - (*value)[0] = value_buf[0]; - (*value)[1] = value_buf[1]; - } - ImGui::PopStyleColor(); - } - break; - - case mvAppItemType::mvItemHandlerRegistry: - { - InfoHeader("Handler Registry"); - renderBindCount(); - } - break; - - case mvAppItemType::mvFont: - { - InfoHeader("Font"); - renderBindCount(); - } - break; - - default: - // Nothing to do here, this is just to calm down the compiler that will - // otherwise warn about unused enum values. - break; - } -} - -void mvLayoutWindow::highlightItemRect(mvAppItem* item) -{ - auto rectMin = item->state.rectMin; - auto rectMax = item->state.rectMax; - if (rectMin.x == 0.0f && rectMin.y == 0.0f && rectMax.x == 0.0f && rectMax.y == 0.0f) - { - // This only works for items positioned relative to the viewport, such as - // windows and popups. Some other items, like table columns or child windows, - // will get into this branch too. - - auto pos = item->state.pos; - - // Going through the container chain, adjusting `pos` according to window positions - // that we find across the way to the root window. - mvAppItem* parent = item->info.parentPtr; - while (parent) { - // TODO: if mvTable ever starts saving its position, add it here as well. - // Item positions are relative to the table when scrolling in the table is - // enabled, because in that case it creates an internal child window. - if (parent->type == mvAppItemType::mvWindowAppItem || parent->type == mvAppItemType::mvChildWindow) - pos = pos + parent->state.pos - parent->state.scrollPos; - - parent = parent->info.parentPtr; - } - - ImGui::GetForegroundDrawList()->AddRect(pos, pos + item->state.rectSize, IM_COL32(255, 0, 0, 255)); - } - else - { - // Regular widgets that have rectMin/rectMax go here - ImGui::GetForegroundDrawList()->AddRect(rectMin, rectMax, IM_COL32(255, 255, 0, 255)); - } -} - -bool mvLayoutWindow::jumpToItem(mvUUID item) -{ - auto itemRef = GetRefItem(*GContext->itemRegistry, item); - if (!itemRef) - return false; - m_selectedItem = item; - _itemref = itemRef; - _expandToSelected = (item != 0); - return true; -} - -mvUUID mvLayoutWindow::getHoveredItem() -{ - // Surely this should belong to mvItemRegistry, but let it live here for the moment. - // The layout window will probably be the only user of this function. - - // For simplicity, we'll only check those registries that can actually capture - // hovered state. Note that they are listed here in the reverse order of their - // rendering - this way we'll get the last item that got hovered; see notes in - // findHoveredInSubTree for more info. - std::vector>* categories[] = { - &GContext->itemRegistry->viewportDrawlistRoots, - &GContext->itemRegistry->viewportMenubarRoots, - &GContext->itemRegistry->windowRoots, - &GContext->itemRegistry->filedialogRoots, - }; - for (auto category : categories) - { - mvUUID hoveredItem = findHoveredInCategory(*category); - if (hoveredItem) - return hoveredItem; - } - return 0; -} - -mvUUID mvLayoutWindow::findHoveredInCategory(std::vector>& roots) -{ - for (auto& root : roots) - { - mvUUID hoveredItem = findHoveredInSubTree(root.get()); - if (hoveredItem) - return hoveredItem; - } - return 0; -} - -mvUUID mvLayoutWindow::findHoveredInSubTree(mvAppItem* parent) -{ - // Sometimes there might be null pointers in the widgets tree. - if (!parent) - return 0; - - // Since mvLayoutWindow is rendered at the beginning of a frame, we only - // retain items state from the previous frame, therefore it's already - // 1 frame old - telling IsItemHovered to look back that far. - bool hovered = IsItemHovered(parent->state, 1); - - // If item is hoverable but not hovered, it's definitely not in the chain of hovered - // items. Let's drop the rest of sub-tree. - // - // Note: the way DPG tests for hovered state of windows - not specifying ImGuiHoveredFlags_ChildWindows - - // as soon as a child window is hovered, its parent is reported as "not hovered". - // That's why we can't skip non-hovered windows at all, otherwise we'll miss the - // beginning of the hovered chain. - if (!hovered && (DearPyGui::GetApplicableState(parent->type) & MV_STATE_HOVER) && - parent->type != mvAppItemType::mvWindowAppItem && parent->type != mvAppItemType::mvChildWindow) - return 0; - - // Now, we have three possible cases: - // - // - The item is not hoverable. It may still contain some hovered items in - // its subtree, so we check the children; worst case we'll return 0. - // - // - The item is hoverable (and therefore hovered - see the check above), - // and there's a hovered child inside. We'll search deeper because the - // current item is somewhere in the middle of the chain. - // - // - The item is hovered and it has no hovered children. This means it's - // finally the leaf, that end of the hovered chain that we're looking for. - - // Since slots and children are typicaly rendered in the first-to-last order, - // we're mainly interested in the *last* child that got the hovered status. - // This means we have to do reverse iteration, and have to resort to ugly - // iterators instead of a typical range-for loop. - for (auto itChildSet = std::crbegin(parent->childslots); itChildSet != std::crend(parent->childslots); ++itChildSet) - { - for (auto itChild = std::crbegin(*itChildSet); itChild != std::crend(*itChildSet); ++itChild) - { - mvUUID hoveredItem = findHoveredInSubTree(itChild->get()); - if (hoveredItem) - return hoveredItem; - } - } - // Finally this is the deepest item - or else something totally not hoverable. - return hovered? parent->uuid : 0; -} - -bool mvLayoutWindow::resetSelectedItem() -{ - std::array registries { - &GContext->itemRegistry->windowRoots, - &GContext->itemRegistry->themeRegistryRoots, - &GContext->itemRegistry->itemTemplatesRoots, - &GContext->itemRegistry->stagingRoots, - &GContext->itemRegistry->textureRegistryRoots, - &GContext->itemRegistry->fontRegistryRoots, - &GContext->itemRegistry->itemHandlerRegistryRoots, - &GContext->itemRegistry->handlerRegistryRoots, - &GContext->itemRegistry->valueRegistryRoots, - &GContext->itemRegistry->colormapRoots, - &GContext->itemRegistry->filedialogRoots, - &GContext->itemRegistry->viewportMenubarRoots, - &GContext->itemRegistry->viewportDrawlistRoots, - }; - - for (auto registry : registries) - { - if (!registry->empty()) - { - _itemref = (*registry)[0]; - m_selectedItem = _itemref->uuid; - _expandToSelected = true; - return true; - } - } - - // Just in case it's still holding a ref to an item that no longer exists - // (and thus keeping the item object from deletion). - _itemref = nullptr; - m_selectedItem = 0; - return false; -} - -void mvLayoutWindow::showError(const char* message) -{ - _error_message = message; - ImGui::OpenPopup("error"); -} - -void mvLayoutWindow::renderErrorMessage() -{ - if (ImGui::BeginPopup("error")) - { - ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "%s", _error_message.c_str()); - ImGui::EndPopup(); - } -} diff --git a/src/mvLayoutWindow.h b/src/mvLayoutWindow.h deleted file mode 100644 index 295e31cbc..000000000 --- a/src/mvLayoutWindow.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include -#include "mvToolWindow.h" - -class mvAppItem; - -class mvLayoutWindow final : public mvToolWindow -{ - -public: - - mvLayoutWindow(); - - [[nodiscard]] mvUUID getUUID() const override { return MV_TOOL_ITEM_REGISTRY_UUID; } - [[nodiscard]] const char* getTitle() const override { return "Item Registry"; } - -protected: - - void drawWidgets() override; - -public: - - void renderTreeNode(std::shared_ptr& item); - void renderRootCategory(const char* category, std::vector>& roots); - void highlightItemRect(mvAppItem* item); - bool jumpToItem(mvUUID item); - void showError(const char* message); - mvUUID getHoveredItem(); - mvUUID findHoveredInSubTree(mvAppItem* parent); - mvUUID findHoveredInCategory(std::vector>& roots); - // Sets _itemref to whatever item it can find, like the first window or - // some other root (e.g. if there are no windows). Returns true if _itemref - // is valid (non-null). Can only return false if there are no any items at all. - bool resetSelectedItem(); - void renderTypeSpecificInfo(); - void renderThemeComponentInfo(mvAppItem* item); - void renderBindCount(); - void renderErrorMessage(); - - std::shared_ptr _itemref = nullptr; - mvUUID m_selectedItem = 0; - bool _expandToSelected = false; - std::unordered_set _itemsToExpand; - ImGuiTextFilter _imguiFilter; - bool _startFiltering = false; - bool _slots = false; - bool _picker = false; - std::string _search_tag; - std::string _error_message; -}; \ No newline at end of file diff --git a/src/mvLinuxSpecifics.h b/src/mvLinuxSpecifics.h deleted file mode 100644 index 83f113faf..000000000 --- a/src/mvLinuxSpecifics.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include -#include - -struct mvViewportData -{ - GLFWwindow* handle = nullptr; -}; diff --git a/src/mvLoadingIndicator.cpp b/src/mvLoadingIndicator.cpp deleted file mode 100644 index 61f593d19..000000000 --- a/src/mvLoadingIndicator.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include "mvLoadingIndicator.h" - -#include "mvLoadingIndicatorCustom.h" -#include "mvFontItems.h" -#include "mvThemes.h" -#include "mvContainers.h" -#include "mvItemHandlers.h" - -void mvLoadingIndicator::draw(ImDrawList* drawlist, float x, float y) -{ - - //----------------------------------------------------------------------------- - // pre draw - //----------------------------------------------------------------------------- - - // show/hide - if (!config.show) - return; - - // focusing - if (info.focusNextFrame) - { - ImGui::SetKeyboardFocusHere(); - info.focusNextFrame = false; - } - - // cache old cursor position - ImVec2 previousCursorPos = ImGui::GetCursorPos(); - - // set cursor position if user set - if (info.dirtyPos) - ImGui::SetCursorPos(state.pos); - - // update widget's position state - state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; - - // set item width - if (config.width != 0) - ImGui::SetNextItemWidth((float)config.width); - - // set indent - if (config.indent > 0.0f) - ImGui::Indent(config.indent); - - // push font if a font object is attached - if (font) - static_cast(font.get())->pushFont(); - - // themes - apply_local_theming(this); - - //----------------------------------------------------------------------------- - // draw - //----------------------------------------------------------------------------- - { - ScopedID id(uuid); - - switch (_style) - { - case Style_OldDottedCircle: - LoadingIndicatorCircle(config.specifiedLabel.c_str(), _radius, _mainColor, _optionalColor, _circleCount, _speed); - break; - case Style_OldRing: - LoadingIndicatorCircle2(config.specifiedLabel.c_str(), _radius, _thickness, _mainColor); - break; - case Style_DottedCircle: - // This is to align the indicator body to text rather than to framed rect - // (can be useful with radius=1). - ImGui::AlignTextToFramePadding(); - LoadingIndicatorCircle(config.specifiedLabel.c_str(), _radius, _mainColor, _optionalColor, _circleCount, _speed); - break; - case Style_Ring: - { - const float pixSize = (_radius > 0? _radius : 1.f) * ImGui::GetTextLineHeight(); - // `thickness=1` corresponds to line thickness being 1/4 of the ring radius, - // i.e. 1/8 of the diameter (pixSize). - const float pixThickness = (_thickness > 0? _thickness : 1.f) * pixSize * 0.125f; - // This is to align the indicator body to text rather than to framed rect - // (can be useful with radius=1). - ImGui::AlignTextToFramePadding(); - LoadingIndicatorRing(config.specifiedLabel.c_str(), pixSize, pixThickness, _speed, _mainColor); - } - break; - } - } - - //----------------------------------------------------------------------------- - // update state - //----------------------------------------------------------------------------- - UpdateAppItemState(state); - - //----------------------------------------------------------------------------- - // post draw - //----------------------------------------------------------------------------- - - // set cursor position to cached position - if (info.dirtyPos) - DearPyGui::RestoreImGuiCursor(previousCursorPos); - - if (config.indent > 0.0f) - ImGui::Unindent(config.indent); - - // pop font off stack - if (font) - ImGui::PopFont(); - - // handle popping themes - cleanup_local_theming(this); - - if (handlerRegistry) - handlerRegistry->checkEvents(&state); - - // handle drag & drop if used - apply_drag_drop(this); -} - -void mvLoadingIndicator::handleSpecificKeywordArgs(PyObject* dict) -{ - if (dict == nullptr) - return; - - if (PyObject* item = PyDict_GetItemString(dict, "style")) _style = static_cast