Giter Site home page Giter Site logo

pyimgui / pyimgui Goto Github PK

View Code? Open in Web Editor NEW
1.3K 1.3K 179.0 1.73 MB

Cython-based Python bindings for dear imgui

Home Page: https://pyimgui.readthedocs.io

License: BSD 3-Clause "New" or "Revised" License

Python 19.76% Makefile 0.23% C++ 3.23% C 0.20% Batchfile 0.20% Shell 0.27% Cython 76.11%
cython dear-imgui gamedev opengl python python-bindings

pyimgui's Introduction

completion Documentation Status Build status

pyimgui

Python bindings for the amazing dear imgui C++ library - a Bloat-free Immediate Mode Graphical User Interface.

Documentation: pyimgui.readthedocs.io

Notes for contributions:

  • We have a fixes branch
  • Please, read the last section of this file

Installation

pyimgui is available on PyPI so you can easily install it with pip:

pip install imgui[full]

Above command will install imgui package with additional dependencies for all built-in rendering backend integrations (pygame, cocos2d, etc.). If you don't want to install all additional dependencies you can always use bare pip install imgui command or select a specific set of extra requirements:

  • for pygame backend use pip install imgui[pygame]
  • for GLFW3 backend use pip install imgui[glfw]
  • for SDL2 backend use pip install imgui[sdl2]
  • for Cocos2d backend use pip install imgui[cocos2d]
  • for pyglet backend use pip install imgui[pyglet]

Package is distributed in form of built wheels so it does not require compilation on most operating systems. For more details about compatibility with diffferent OSes and Python versions see the Project ditribution section of this documentation page.

Project status

The imgui package provides support for the majority of core DearImGui 1.82 widgets and functionalities. Some low-level API elements and complex widgets (like plots) may be missing. We are working hard to provide 100% feature mapping of the core ImGui library. The completion badge shows up-to-date status of that goal.

Project distribution

This project has a working build pipeline on Appveyor. It builds succesfully for all major operating systems with different architectures:

  • Windows (32bit & 64bit)
  • Linux (32bit & 64bit)
  • OS X (universal build)

Right now we are ready shipping the built wheels for these three systems (even for Linux using manylinux1 wheels). The build pipeline covers multiple Python versions:

  • py36
  • py37, pp37
  • py38, pp38
  • py39, pp39
  • py310
  • py311

Note: We dropped support for py27, py33, py34, and py35 starting from release 2.0. Those were supported until release 1.4.0. Pypy is only supported since release 2.0.

If none of these wheels work in your environment you can install the imgui package by compiling it directly from sdist distribution using one of following commands:

# will install Cython as extra dependency and compile from Cython sources
pip install imgui[Cython] --no-binary imgui

# will compile from pre-generated C++ sources
pip install imgui --no-binary imgui

pyimgui provides documentation with multiple visual examples. Thanks to custom Sphinx extensions, we are able to render GUI examples off-screen directly from docstring snippets. These examples work also as automated functional tests. Documentation is hosted on pyimgui.readthedocs.io.

Contributing

Contributions are welcomed. If you want to help us by fixing bugs, mapping functions, or adding new features, please feel free to do so and propose a pull request.

Development tips and information for developers are given in HACKING.md.

pyimgui's People

Contributors

aforren1 avatar billsix avatar branpk avatar cammm avatar connorjak avatar frosenek avatar godzil avatar jamesmurphy-mc avatar jeremyherbert avatar keymaster- avatar kinoxklark avatar learn-more avatar lubieowoce avatar luminouslizard avatar matthewturk avatar oliver-1-1 avatar pbuckner avatar pconerly avatar pthom avatar red-pheonix avatar rp-bot avatar scotty007 avatar stuaxo avatar supudo avatar swistakm avatar techstudent10 avatar tim-rex avatar ttimo avatar wiatrogon avatar willy-jl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyimgui's Issues

Support Python 3.7

Looks like the newer version of Python isn't supported, which causes issues similar to what's described in #79.

Thanks!

refactor impl subpackage

Classes in the impl subpackage are currently very inconsistent and duplicate a lot of code. Also it is not clear how they shoud be used/created/extended. We should definitely improve this before the first release because they are the entry point to the pyimgui library.

Things to do:

  • create documentation page that explains how to use classes from impl subpackage
  • create a guide that explains how to create new implementation classes and how to extend the existing ones
  • define naming conventions for existing impl classes and decide how to handle extra dependencies for them (using extra_requires?)
  • rewrite the examples of code in doc/examples
  • create an abstract base class that will ensure the completeness of new impl classes and also stabilise their API
  • create new OpenGL-only base class to reduce code duplication between GLFW and PySDL2 implementation
  • resolve all the existing issues with text inputs and time measurements
  • lay the foundation for supporting different fonts as this is partially the responsibility of impl classes

Parallel projects

You know, I have started hating Github's announcing style on web search engines. If I had found your project before, I wouldn't wasted my time starting my own. Check here. Maybe you can integrate the SDL2 part to increase the completion of your project, or just check it out or whatever. If you are willing to keep being the PyImgui dev, I'm just dropping my version right know (no need for two of the same). Good work and good luck! ☺️ πŸ‘

How to install the pre-release version?

Hey,

I'm trying to install the pre-release version here https://pypi.org/project/imgui/1.0.0a1/ to get is_mouse_clicked. I first uninstalled the version I had in my virtualenv, and then:

pip install imgui==1.0.0a1
pip install --pre imgui
pip install --pre imgui==1.0.0a1

Any ideas?

//edit I'm on OSX El Capitan 10.11.4. I'm looking at the files, and it looks like there's just macosx_10_12. When I download that macosx wheel and install I get:

$ pip install files/imgui-1.0.0a1-cp36-cp36m-macosx_10_12_x86_64.whl 
imgui-1.0.0a1-cp36-cp36m-macosx_10_12_x86_64.whl is not a supported wheel on this platform.

But when I look at https://pypi.org/project/imgui/0.1.0/#files it has the same mac version.

Could you add the source .tar.gz that 0.1.0 has to the pre-release? Maybe my pip installs via that?

SDL2 example crashes

After fixing the typos described in #70, I ran into the following error when running the SDL2 example (Windows 10, latest SDL2.dll):

Traceback (most recent call last):
  File "C:/Users/admin/PycharmProjects/BotW-World-Editor/main.py", line 103, in <module>
    main()
  File "C:/Users/admin/PycharmProjects/BotW-World-Editor/main.py", line 12, in main
    renderer = SDL2Renderer(window)
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\sdl2.py", line 17, in __init__
    super(SDL2Renderer, self).__init__()
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 90, in __init__
    super(ProgrammablePipelineRenderer, self).__init__()
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 18, in __init__
    self._create_device_objects()
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\imgui\integrations\opengl.py", line 115, in _create_device_objects
    last_array_buffer = gl.glGetIntegerv(gl.GL_ARRAY_BUFFER_BINDING)
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\latebind.py", line 41, in __call__
    return self._finalCall( *args, **named )
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\wrapper.py", line 664, in wrapperCall
    raise err
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\wrapper.py", line 657, in wrapperCall
    result = wrappedOperation( *cArguments )
  File "C:\Users\admin\PycharmProjects\botwenv\lib\site-packages\OpenGL\error.py", line 232, in glCheckError
    baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
	err = 1280,
	description = b'invalid enumerant',
	baseOperation = glGetIntegerv,
	pyArgs = (
		GL_ARRAY_BUFFER_BINDING,
		<object object at 0x000001E27D030110>,
	),
	cArgs = (
		GL_ARRAY_BUFFER_BINDING,
		<OpenGL.arrays.ctypesarrays.c_long_Array_1 object at 0x000001E27FA6C7C8>,
	),
	cArguments = (
		GL_ARRAY_BUFFER_BINDING,
		<OpenGL.arrays.ctypesarrays.c_long_Array_1 object at 0x000001E27FA6C7C8>,
	)
)

Process finished with exit code 1

Document how to change imgui theme

Hello. I want to know if anyone can tell me how can I change the colors from the default theme to create a different skin?
Thank You.

Set column width not implemented

It seems it wasn't implemented in the version of imgui that is in this repo. Can we update that version and implement some of the new functions?

Crash on OSX

Hi,

I just tried to run this on OSX yosemite, and it crashed almost immediately. LLDB traceback is below:

$ lldb python
(lldb) target create "python"
Current executable set to 'python' (x86_64).
(lldb) r
Process 33324 launched: '/Users/jeremy/anaconda/bin/python' (x86_64)
Python 3.5.2 |Anaconda 4.0.0 (x86_64)| (default, Jul  2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imgui
>>> def do():
...  imgui.begin("my window")
...  imgui.end()
...
>>> do()
libc++abi.dylib: terminating with uncaught exception of type char const*
Process 33324 stopped
* thread #1: tid = 0xd6592b, 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill:
->  0x7fff81be0286 <+10>: jae    0x7fff81be0290            ; <+20>
    0x7fff81be0288 <+12>: movq   %rax, %rdi
    0x7fff81be028b <+15>: jmp    0x7fff81bdbc53            ; cerror_nocancel
    0x7fff81be0290 <+20>: retq
(lldb) bt
* thread #1: tid = 0xd6592b, 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x00007fff81be0286 libsystem_kernel.dylib`__pthread_kill + 10
    frame #1: 0x00007fff89ba49f9 libsystem_pthread.dylib`pthread_kill + 90
    frame #2: 0x00007fff89d6b9a3 libsystem_c.dylib`abort + 129
    frame #3: 0x00007fff82bafa21 libc++abi.dylib`abort_message + 257
    frame #4: 0x00007fff82bd79d1 libc++abi.dylib`default_terminate_handler() + 267
    frame #5: 0x00007fff85c817eb libobjc.A.dylib`_objc_terminate() + 124
    frame #6: 0x00007fff82bd50a1 libc++abi.dylib`std::__terminate(void (*)()) + 8
    frame #7: 0x00007fff82bd4b30 libc++abi.dylib`__cxa_throw + 121
    frame #8: 0x0000000101b3abd9 core.cpython-35m-darwin.so`__py_assert(msg=<unavailable>) + 57 at py_imconfig.cpp:26
    frame #9: 0x0000000101af86bd core.cpython-35m-darwin.so`ImGui::Begin(name="my window", p_open=0x0000000000000000, size_on_first_use=0x00007fff5bfff1f8, bg_alpha=-1, flags=0) + 93 at imgui.cpp:3780
    frame #10: 0x0000000101af319b core.cpython-35m-darwin.so`ImGui::Begin(name=<unavailable>, p_open=<unavailable>, flags=<unavailable>) + 43 at imgui.cpp:3772
    frame #11: 0x0000000101abea72 core.cpython-35m-darwin.so`__pyx_pw_5imgui_4core_19begin(_object*, _object*, _object*) [inlined] __pyx_pf_5imgui_4core_18begin(_object*, _object*, _object*, int) + 11 at core.cpp:14846
    frame #12: 0x0000000101abea67 core.cpython-35m-darwin.so`__pyx_pw_5imgui_4core_19begin(__pyx_self=<unavailable>, __pyx_args=<unavailable>, __pyx_kwds=<unavailable>) + 423 at core.cpp:14797
    frame #13: 0x000000010004fe5c libpython3.5m.dylib`PyCFunction_Call + 60
    frame #14: 0x00000001000bd2df libpython3.5m.dylib`PyEval_EvalFrameEx + 22431
    frame #15: 0x00000001000c192f libpython3.5m.dylib`fast_function + 207
    frame #16: 0x00000001000bd434 libpython3.5m.dylib`PyEval_EvalFrameEx + 22772
    frame #17: 0x00000001000c10c3 libpython3.5m.dylib`_PyEval_EvalCodeWithName + 1779
    frame #18: 0x00000001000b7ac1 libpython3.5m.dylib`PyEval_EvalCode + 81
    frame #19: 0x00000001000e642c libpython3.5m.dylib`PyRun_InteractiveOneObject + 588
    frame #20: 0x00000001000e5d5e libpython3.5m.dylib`PyRun_InteractiveLoopFlags + 206
    frame #21: 0x00000001000e5c5c libpython3.5m.dylib`PyRun_AnyFileExFlags + 60
    frame #22: 0x00000001000fcd47 libpython3.5m.dylib`Py_Main + 3591
    frame #23: 0x0000000100000dc7 python`main + 215
    frame #24: 0x0000000100000ce4 python`start + 52
(lldb)

Figure out the reliable solution to distribute proper long_description markup for new package versions

We use Markdown for the README and convert it dynamically during distribution of the package.

The problem is: locally we can build only sdist. Other packages are collected as semi-artifacts from Travis CI and AppVeyor. It means that we cannot expect yet that Markdown will be properly converted to rst during builds in these systems. If we upload all package wheels and sdist in bunch then the version metadata will be taken from first uploaded distribution. If it is a wheel built without pypandoc the long description will not be rendered properly (see version 0.0.1). I have used to just re-upload package metadata for given version in other projects but this is not possible anymore (see pypi/warehouse#2170).

Right now we can upload rst-converted sdist first and only then upload the rest of distributions. Unfortunately, once we do a mistake there is only one solution: version bump and another upload. This of course isn't a long term solution as it leads to unjustified version inflation.

Here are my first ideas:

  1. Script all of that in special Makefile target: If we ensure that sdist is uploaded before wheels we have solved the problem.
  2. Make sure pandoc and pypandoc are available on all build environments: this may be tricky, especially in Docker environment for manylinux1 builds on Travis.
  3. Simply dump Markdown and use restructured text.
  4. Create a tool that will modify wheels in place in order to convert long description markup just before upload.
  5. Wait till pypi/warehouse#2170 gets resolved positively.

Cython 0.28.* compatibility

Project does not build on Cython==0.28.* probably due to some changes in typing:

$ pip install -e .
Obtaining file:///Users/swistakm/dev/pyimgui
    Complete output from command python setup.py egg_info:
    
    Error compiling Cython file:
    ------------------------------------------------------------
    ...
        """
        cimgui.EndMenu()
    
    
    def menu_item(
        str name, str shortcut=None, cimgui.bool selected=None, enabled=True
                                                         ^
    ------------------------------------------------------------
    
    imgui/core.pyx:2029:54: Cannot assign None to bool
    Compiling imgui/core.pyx because it depends on /Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Includes/libcpp/__init__.pxd.
    [1/1] Cythonizing imgui/core.pyx
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/Users/swistakm/dev/pyimgui/setup.py", line 146, in <module>
        compiler_directives=compiler_directives, **cythonize_opts
      File "/Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 1026, in cythonize
        cythonize_one(*args)
      File "/Users/swistakm/.envs/pyimgui/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 1146, in cythonize_one
        raise CompileError(None, pyx_file)
    Cython.Compiler.Errors.CompileError: imgui/core.pyx
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /Users/swistakm/dev/pyimgui/

It fortunately still builds on previous releases (till 0.27.3). pyimgui is mostly distributed as a built wheel so the problem isn't that critical but it would be nice to fix it soon.

Write a Todo app for doc/examples

One of the classic example apps for GUI frameworks are todo apps. Let's write one in pyimgui! (Extends from #45 )

It'd be cool if we could write the todo app in a way that the user could choose which backend. Like:

> python doc/examples/todo_app.py
# runs with pygame by default
> python doc/examples/todo_app.py --backend=sdl2
# runs with pysdl2

Docs/Build pipeline: add badge that will automatically tell how much of core API is mapped

General idea is to:

  1. do some text processing in order to estimate level of completion (initial work done in make completion)
  2. download a custom shield from shields.io using information from previous step
  3. store that shield as new artifact in appveyor build
  4. link this badge in README.md to latest artifact of named build on master

Pretty dirty but should work!

Note: If we store badge as badges/completion.svg the url will be:

https://ci.appveyor.com/api/projects/swistakm/pyimgui/artifacts/badges/completion.svg?branch=master&job=Environment%3A%20PYTHON%3DC%3A%5CPython27%2C%20PYTHON_ARCH%3D32%2C%20MSVC_VERSION%3DVisual%20Studio%2010

Create a better examples and instead of using built-in demo window

As suggested by @ccanepa on Cocos2d mailing group:

while the example does a good job showing the wide offering, it exposes something that is entirely built on the other side of the bind. An additional, much simpler but non trivial example built in the python side would help to grasp how to compose the window.

Problem on installing integrations in zsh

Hello,

I had a problem when running any variant of pip install integrations with zsh:

pip install imgui[pygame]
zsh: no matches found: imgui[pygame]

With good old bash is working fine. For zsh, you need to escape the brackets:

pip install imgui\[pygame\]

Was a bit tricky to find this, so I tough about sharing.

pyimgui for opencv / numpy

Hello,

This is not an issue, rather a way to acknowledge the quality of your package :-)

I have been working with pyimgui for several months.

As I work in the computer vision field, I needed a way to be able to display images from numpy and opencv (display & inspect images, have a way too start imgui simply, etc.). So I built some tools on top of pyimgui, and I have been using them since then.

In this context, pyimgui has proven to be extremely usable and reliable. Many thanks!

Then, I decided to try and make a pip package from those tools: would you mind having a look at it and telling me your honest opinion?
Here is a link to it : https://github.com/pthom/imgui_datascience
I have tested it with python 2 & 3, under linux, windows and osx.

Regards,

Pascal Thomet

PS : please bear in mind that this is my first experience with distributing a python package (which is quite a complex process, as I discovered). There might be some gotchas.

Using backspace on enter yields multiple keystrokes in text inputs

Issue found thanks to #24. This affects text inputs from mapped core functions as well as text inpuths in C++ coded demo window. Issue is visible only in specific integrations and/or under specific versions of Python.

The root cause: invalid method of FPS measurement in all existing rendering integrations.

drag_float and drag_int don't respect the min and max values

Hi,

As per the title, both the drag_float and drag_int controls don't appear to respect the min and max bounds set in code. Is this a known issue?

I'm using python3.6 with pyimgui 0.0.2 (installed from pip).

My pyimgui code looks like this:

imgui.begin("Test controls", True)
_, int_value = imgui.drag_int("drag int", int_value, min_value=0, max_value=10)
_, float_value = imgui.drag_float("drag float", float_value, min_value=0.0, max_value=10.0)
imgui.end()

And full example code is below:

# -*- coding: utf-8 -*-
from sdl2 import *
import ctypes
import OpenGL.GL as gl
import imgui
from imgui.integrations.sdl2 import SDL2Renderer

def main():
    window, gl_context = impl_pysdl2_init()
    renderer = SDL2Renderer(window)

    running = True
    event = SDL_Event()
    int_value = 5
    float_value = 5.3

    while running:
        while SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == SDL_QUIT:
                running = False
                break
            renderer.process_event(event)
        renderer.process_inputs()

        imgui.new_frame()

        imgui.begin("Test controls", True)
        _, int_value = imgui.drag_int("drag int", int_value, min_value=0, max_value=10)
        _, float_value = imgui.drag_float("drag float", float_value, min_value=0.0, max_value=10.0)
        imgui.end()

        gl.glClearColor(0.2, 0.2, 0.2, 0.2)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()

        SDL_GL_SwapWindow(window)

    renderer.shutdown()
    SDL_GL_DeleteContext(gl_context)
    SDL_DestroyWindow(window)
    SDL_Quit()


def impl_pysdl2_init():
    width, height = 1280, 720
    window_name = "minimal ImGui/SDL2 example"

    if SDL_Init(SDL_INIT_EVERYTHING) < 0:
        print("Error: SDL could not initialize! SDL Error: " + SDL_GetError())
        exit(1)

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8)
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1)
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)

    SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, b"1")
    SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, b"1")

    window = SDL_CreateWindow(window_name.encode('utf-8'),
                              SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                              width, height,
                              SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE)

    if window is None:
        print("Error: Window could not be created! SDL Error: " + SDL_GetError())
        exit(1)

    gl_context = SDL_GL_CreateContext(window)
    if gl_context is None:
        print("Error: Cannot create OpenGL Context! SDL Error: " + SDL_GetError())
        exit(1)

    SDL_GL_MakeCurrent(window, gl_context)
    if SDL_GL_SetSwapInterval(1) < 0:
        print("Warning: Unable to set VSync! SDL Error: " + SDL_GetError())
        exit(1)

    return window, gl_context

if __name__ == "__main__":
    main()

Thanks,
Jeremy

Running Error at basic rendering loop

When i try to run, i am getting this error, using the basic example of readthedocs

Traceback (most recent call last):
  File "F:/Programming Projects/Python/twilio-app/main.py", line 3, in <module>
    imgui.new_frame()
  File "imgui\core.pyx", line 993, in imgui.core.new_frame
imgui.core.ImGuiError: ImGui assertion error (g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f) at imgui-cpp/imgui.cpp:2046
Process finished with exit code 1

Downloaded and installed trough pip install imgui[full].
PyCharm Community edition even trough python cmd i get the same error
Windows 7 SP1 x64
Python 3.6.2 virtualenv

image_button not working

Hi there!

I can't get the image_button to return true. If I change my code to use a "normal" button, everything works fine, but the image_button seems to be broken in pyimgui.

if (imgui.image_button(texture, width, height)):
        # shows the image, but never prints "Yay"
        print("Yay")

...

if (imgui.button("test")):
        # Obviously no image, but prints "Yay" when clicked
        print("Yay")

I don't think I'm doing something wrong. Can you confirm this issue?

Write _py_show_demo_window()

Write a python implementation of ImGui::ShowDemoWindow. This task was brought up in the broader ticket: #45

This would provide a good example for pyimgui users, and it would also provide a way for pyimgui users to check what is and isn't ported.

Docs: provide a way to encode interactions in the visual examples

I am working on #20 and #21 and I have realised that it would be nice to have some easy way to encode user interactions for illustration purposes in docs. Features that would be nice to have are:

  • interpolated mouse movement
  • plain hovering
  • clicks, double clicks, keyboard inputs

Right now I have few ideas how to accomplish that:

  1. Create some very simple language to encode interactions and use is as .. visual-example:: directive option. Like:

    .. visual-example::
            :auto_layout:
            :height: 200
            :animated: 5s 10fps
            :interactions: move 0 0 | interpolate 1s | move 80 40 | click | wait 1s
    
            current = 2
            imgui.begin("Example: combo widget")
    
            clicked, current = imgui.combo(
                "combo", current, ["first", "second", "third"]
            )
    
            imgui.end()
    

    This approach seems like the simplest to implement but also the hardest to use in docstrings and most expensive to maintain.

  2. Include some annotations using special comments directly in the sample code. We could treat them as templates to include some special code in offscreen renderer. These comments would of course be removed from sample code in Sphinx. Something like this:

    .. visual-example::
            :auto_layout:
            :height: 200
            :animated: 5s 10fps
    
            current = 2
            imgui.begin("Example: combo widget")
    
            clicked, current = imgui.combo(
                "combo", current, ["first", "second", "third"]
            )
            #< click at 1s
    
            imgui.end() 
    

    Imgui allows to get last item rect/position so this approach would be easier than hardcoding interaction positions. On the other hand the auto generated code that we would have to include would be a real mess. This also makes the example code harder to read for developers.

  3. A hybrid (1+2) approach where we have simple interactions list (like in 1.) but allow to sprinkle the example code with specific labels in comments that allow to measure element position during example run. Like:

    .. visual-example::
            :auto_layout:
            :height: 200
            :animated: 5s 10fps
            :interactions: move 0 0 | interpolate 1s | move "my-combo" | click | wait 1s
    
            current = 2
            imgui.begin("Example: combo widget")
    
            clicked, current = imgui.combo(
                "my-combo", current, ["first", "second", "third"]
            )
            #: my-combo
    
            imgui.end()
    

Maybe it is not a good idea at all. Maybe there is already some "interaction" language that we could reuse. @supudo @Wiatrogon do you have any ideas?

Allow for easy way to handle inout arguments

Problem

Unfortunately dear-imgui API uses inout arguments very often. Python does not allow for such calling convention. So it is very hard to wire together imgui windows and widgets in the same way like in C++.

General idea

We could introduce some abstract base class that could be used in place of existing inout argument handling:

import abc

class InOutABC(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def set(self, value):
        pass

    @abc.abstractmethod
    def get(self):
        pass

    @classmethod
    def __subclasshook__(cls, C):
        if cls is InOutABC:
            if (
                any("set" in B.__dict__ for B in C.__mro__) and
                any("get" in B.__dict__ for B in C.__mro__)
            ):
                return True

        return NotImplemented

Usage
Then user could create his own signal-like class that would handle his inout argument data and could be used in imgui function calls without inconvenient tuple unpacking and multiple variable assignments:

class InOutWire(object):
    def __init__(self, value):
        self._value = value

    def set(self, value):
        self._value = value

    def get(self):
        return self._value

Such InOutWire could be used to easily glue together different widgets:

checked = InOutWire(False)

while True:
    imgui_ctx.new_frame()

    if imgui.checkbox("c1", checked)[0]:
        print "c1.clicked", checked.get()
    if imgui.checkbox("c2", checked)[0]:
        print "c2.clicked", checked.get()
    # ...

User could even create general objects to provide auto-generated inout arguments without the need to:

from collections import defaultdict

wires = defaultdict(lambda: Wire(False))

while True:
    imgui_ctx.new_frame()

    if imgui.checkbox("c1", wires['checked'])[0]:
        print "c1.clicked", wires['checked'].get()
    if imgui.checkbox("c2", wires['checked'])[0]:
        print "c2.clicked", wires['checked'].get()

Implementation details

Having the abstract base class InOutABC we can check if provided possible inout arguments have the compatible interface (set()/get() methods). We need to do that test in every function that will allow for such feature. Example implementation:

def checkbox(str label, state):
    cdef cimgui.bool inout_mode = isinstance(state, InOutABC)
    cdef cimgui.bool inout_state = state.get() if inout_mode else state

    result = cimgui.Checkbox(_bytes(label), &inout_state)

    if inout_mode:
        state.set(inout_state)

    return result, inout_state

Sadly this will require a lot of boilerplate and code changes. The ideal solution would be to have kind of decorator that can translate between ordinary/inout arguments. Inside of wrapped functions we could then always expect either InOutABC-compatible objects or simple flat arguments.

The trouble is that right now we allow arguments that are "inout" in the C++ layer to be both positional and keyword. In such situation I don't know how do provide such decorator that would manipulate arguments without introspecting function signatures with inspect. This would be easier if we would assume that inout arguments are always keyword-only. Good news is that Cython allows to have keyword-only arguments even on Python 2 and even without default values.

Example implementation and usage:

from functools import wraps

def allow_inout(kwarg_name, result_pos=1):

    def wrapper(func):

        @wraps(func)
        def wrapped(*args, **kwargs):
            kwarg = kwargs.get(kwarg_name, None)

            inout_mode = isinstance(kwarg, InOutABC)

            if inout_mode:
                kwargs[kwarg_name]=kwarg.get()

            result_tuple = func(*args, **kwargs)

            if inout_mode:
                kwarg.set(result_tuple[result_pos])

            return result_tuple
        
        return wrapped

    return wrapper

@allow_inout('state')
def checkbox(str label, *, state):
    cdef cimgui.bool inout_state = state
    return cimgui.Checkbox(_bytes(label), &inout_state), inout_state

Further improvements
Common idiom in imgui is to always check result of widget call using if to process user interaction. For every function that defines a widget and uses inout arguments we return a tuple. This means that some widgets will require result value indexing and some will not e.g:

if imgui.button("some button"):
    print("user interaction")

if imgui.checkbox("some checkbox", False)[0]
    print("user interaction")

This makes the API usage inconsistent. We could improve this by replacing simple return tuple with object that will take into account only the value during bool test e.g:

class InteractionTuple(tuple):
    def __bool__(self):
        return bool(self[0])

The downside: changes user expectation on tuple truth value. Other way around is to inverse whole problem. We could replace every return value that means user interaction or widget visibility with an object that clearly describes what are expectations about "True value". Example:

class InteractionTuple(tuple):
    def __bool__(self):
        raise ValueError
    
    @property
    def clicked(self)
        return bool(self[0])


class VisibilityTuple(tuple):
    def __bool__(self):
        raise ValueError
    
    @property
    def visible(self)
        return bool(self[0])

    @property
    def expanded(self)
        return bool(self[0])

# usage

if begin("my window").visible:  # alternatively: .expanded 
    ...
    if imgui.checkbox("my checkbox").clicked:
        ...

How to handle multiple widgets with same "implicit" ID

This isn't actually a bug but it may look like one.

Some widgets get same "implicit" id and usually this is the value of widget's label parameter. For instance:

if imgui.button("OK"):
    print("OK1")
if imgui.button("OK"):
    print("OK2")

All above buttons will have same label "OK". Both buttons will look like clickable but only the first one will trigger on clicking. This would be a problem for common labels like yes/no/OK/cancel etc. but these usually are on different windows and windows have different IDs scopes. e.g. if we use following code:

imgui.begin("Win1")
if imgui.button("OK"):
    print("W1-OK1")
if imgui.button("OK"):
    print("W1-OK2")
imgui.end()

imgui.begin("Win1")
if imgui.button("OK"):
    print("W2-OK1")
if imgui.button("OK"):
    print("W2-OK2")
imgui.end()

We will see W1-OK1 and W2-OK1 in output but no W1-OK2 nor W2-OK2. ImGui exposes following functions to maintain such ID scopes:

    void PushID(const char* str_id)
    void PushID(const char* str_id_begin, const char* str_id_end)
    void PushID(const void* ptr_id)
    void PushID(int int_id)
    void PopID()

In order to solve such problems they need to be ported. We already have additional context managers for managing push/pop actions on fonts and styles so we could also create custom scope or scoped context manager that would make code more readable. We would then have two ways to interact with scopes:

if imgui.button("OK"):
    print("OK outside scope")

imgui.push_id("my scope")
if imgui.button("OK"):
    print("OK in scope")
imgui.pop_id()

# or ...

if imgui.button("OK"):
    print("OK outside scope")

with imgui.scope("my scope"):
    if imgui.button("OK"):
        print("OK in scope")

how to use PlotLine in pyimgui?

Hey,
I am trying to draw a diagram in pyimgui but I cannot find any document or wiki about the function like PlotLine in C++? is it exist or not?

Loading TTF fonts

I just tried to figure on my own how to load TTF fonts (documentation pending in #34), but I get an assertion error. What I do is the following:

font = imgui.get_io().fonts.add_font_from_file_ttf("fonts/DroidSans.ttf", 16)
...
while not glfw.window_should_close(self.window):
    # draw stuff
    imgui.push_font(font)
    # draw text
    imgui.pop_font()

The font seems to load successfully, i.e. the font variable is a valid object, not None. But then I get an error upon calling push_font:

Traceback (most recent call last):
  File "/Users/...[location].../igui.py", line 200, in <module>
    app.main_loop()
  File "/Users/...[location].../igui.py", line 76, in main_loop
    self.draw()
  File "/Users/...[location].../igui.py", line 86, in draw
    self.draw_contents()
  File "/Users...[location].../igui.py", line 152, in draw_contents
    imgui.push_font(font)
  File "imgui/core.pyx", line 4757, in imgui.core.push_font
imgui.core.ImGuiError: ImGui assertion error (font && font->IsLoaded()) at imgui-cpp/imgui.cpp:4529

Commenting out the push_font and pop_font calls makes everything work, but with the default raster font (which doesn't look great on a high-resolution display).

I also tried displaying the font atlas on screen -- the loaded font doesn't show in the atlas, only the default raster font

Any ideas will be greatly appreciated! I'm running macOS 10.12, tried the above code with both Python 2.7 and 3.6, both fail the same way.

Custom drawing functionality?

Hi, is there a way to custom-draw a region, like it is possible in the C++ imgui? Likely not, because I don't see ImDrawList exposed in the Python API, but is this planned?

Research popular python game frameworks/engines integration

This is simply to gain more users that could test the lib and give some initial feedback. Projects to research:

  • pygame
  • pyglet
  • cocos2d

Pygame and cocos2d have the biggest user base so they are the first to research. Maybe we don't need anything more than SDL/SDL2/GLFW integration. Anyway it would be great to have some information about how to integrate pyimgui with these libraries and maybe create some examples for each one.

Unknown compiler directives

Hi,
I was trying to compile pyimggui, but got the errors below.

OS: Ubuntu 17.04 64 bit.
Python: 2.7

$ ξ‚°make build
Bootstrapping project environment ...
git submodule update --init
Submodule 'imgui-cpp' (https://github.com/ocornut/imgui.git) registered for path 'imgui-cpp'
Cloning into '/mnt/data/home/stu/projects/external/pyimgui/imgui-cpp'...
Submodule path 'imgui-cpp': checked out 'adb85d800d70d3ddc4548f0e8f184eede4568034'
pip install -r doc/requirements-dev.txt
Requirement already satisfied: Cython in /mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/lib/python2.7/site-packages (from -r doc/requirements-dev.txt (line 1))
Collecting PyOpenGL (from -r doc/requirements-dev.txt (line 2))
  Downloading PyOpenGL-3.1.0.tar.gz (1.2MB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1.2MB 1.1MB/s 
Collecting glfw (from -r doc/requirements-dev.txt (line 3))
  Downloading glfw-1.4.0.tar.gz
Requirement already satisfied: wheel in /mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/lib/python2.7/site-packages (from -r doc/requirements-dev.txt (line 4))
Collecting click (from -r doc/requirements-dev.txt (line 5))
  Downloading click-6.7-py2.py3-none-any.whl (71kB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 71kB 5.3MB/s 
Building wheels for collected packages: PyOpenGL, glfw
  Running setup.py bdist_wheel for PyOpenGL ... done
  Stored in directory: /home/stu/.cache/pip/wheels/1c/17/50/f69d63e0a8169fb890f5a167817a73391be85d30e86fd29504
  Running setup.py bdist_wheel for glfw ... done
  Stored in directory: /home/stu/.cache/pip/wheels/8f/14/0a/b191d11fbbab2b5dc4fa090cf37540465f920af5fab87a1fb0
Successfully built PyOpenGL glfw
Installing collected packages: PyOpenGL, glfw, click
Successfully installed PyOpenGL-3.1.0 click-6.7 glfw-1.4.0
_CYTHONIZE_WITH_COVERAGE=1 python -m pip install -e . -v
Converted retries value: Retry(total=5, connect=None, read=None, redirect=None) -> Retry(total=Retry(total=5, connect=None, read=None, redirect=None), connect=None, read=None, redirect=None)
Converted retries value: Retry(total=5, connect=None, read=None, redirect=None) -> Retry(total=Retry(total=5, connect=None, read=None, redirect=None), connect=None, read=None, redirect=None)
Obtaining file:///mnt/data/home/stu/projects/external/pyimgui
  Running setup.py (path:/mnt/data/home/stu/projects/external/pyimgui/setup.py) egg_info for package from file:///mnt/data/home/stu/projects/external/pyimgui
    Running command python setup.py egg_info
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/mnt/data/home/stu/projects/external/pyimgui/setup.py", line 96, in <module>
        ], compiler_directives=cythonize_opts, gdb_debug=True),
      File "/mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/local/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 886, in cythonize
        c_options = CompilationOptions(**options)
      File "/mnt/data/home/stu/.virtualenvs/tmp-5b770036a307de45/local/lib/python2.7/site-packages/Cython/Compiler/Main.py", line 568, in __init__
        raise ValueError(message)
    ValueError: got unknown compiler directives: gdb_debug, build_inplace
Cleaning up...
Command "python setup.py egg_info" failed with error code 1 in /mnt/data/home/stu/projects/external/pyimgui/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.