Beispiel #1
0
    def render_ui(self):
        """Render the UI"""
        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        # Create window with the framebuffer image
        imgui.begin("Custom window with Image", True)
        # Create an image control by passing in the OpenGL texture ID (glo)
        # and pass in the image size as well.
        # The texture needs to he registered using register_texture for this to work
        imgui.image(self.fbo.color_attachments[0].glo, *self.fbo.size)
        imgui.end()

        imgui.render()
        self.imgui.render(imgui.get_draw_data())
Beispiel #2
0
    def draw(self):
        imgui.new_frame()

        imgui.set_next_window_position(16, 32, imgui.ONCE)
        imgui.set_next_window_size(512, 512, imgui.ONCE)

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        imgui.end_frame()

        imgui.render()

        self.renderer.render(imgui.get_draw_data())
Beispiel #3
0
    def draw(self, *args, **kwargs):
        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

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

        imgui.render()
Beispiel #4
0
def on_draw(dt):
    app.clock.tick()
    window.clear()

    impl.process_inputs()

    imgui.new_frame()
    imgui.show_test_window()

    imgui.render()
    impl.render(imgui.get_draw_data())
Beispiel #5
0
def main():
    pygame.init()
    size = 800, 600

    pygame.display.set_mode(size, pygame.DOUBLEBUF | pygame.OPENGL | pygame.RESIZABLE)

    imgui.create_context()
    impl = PygameRenderer()

    io = imgui.get_io()
    io.display_size = size

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            impl.process_event(event)

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        #imgui.same_line()
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        #imgui.same_line()
        imgui.bullet_text("bullet_text")
        # 不换行
        #imgui.same_line()
        imgui.end()

        # note: cannot use screen.fill((1, 1, 1)) because pygame's screen
        #       does not support fill() on OpenGL sufraces
        gl.glClearColor(1, 1, 1, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        impl.render(imgui.get_draw_data())

        pygame.display.flip()
Beispiel #6
0
def main():
    pygame.init()
    clock = pygame.time.Clock()
    size = 640, 480

    pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.OPENGL)

    io = imgui.get_io()
    io.fonts.add_font_default()
    io.display_size = size

    renderer = PygameRenderer()

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            renderer.process_event(event)

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )

                if clicked_quit:
                    pygame.quit()
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        # note: cannot use screen.fill((1, 1, 1)) because pygame's screen
        #       does not support fill() on OpenGL sufraces
        gl.glClearColor(1, 1, 1, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()

        pygame.display.flip()
        clock.tick(60)
Beispiel #7
0
def main():
    window, gl_context = impl_pysdl2_init()
    impl = SDL2Impl(window)

    opened = True

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

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(1)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_user_guide()
        imgui.show_test_window()

        if opened:
            expanded, opened = imgui.begin("fooo", True)
            imgui.text("Bar")
            imgui.text_colored("Eggs", 0.2, 1., 0.)
            imgui.end()

        with imgui.styled(imgui.STYLE_ALPHA, 1):
            imgui.show_metrics_window()

        gl.glClearColor(114 / 255., 144 / 255., 154 / 255., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()

        SDL_GL_SwapWindow(window)

    impl.shutdown()
    SDL_GL_DeleteContext(gl_context)
    SDL_DestroyWindow(window)
    SDL_Quit()
Beispiel #8
0
def on_frame():
    if imgui.begin_main_menu_bar():
        if imgui.begin_menu("File", True):
            clicked_quit, selected_quit = imgui.menu_item(
                "Quit", 'Cmd+Q', False, True)
            if clicked_quit:
                exit(1)
            imgui.end_menu()
        imgui.end_main_menu_bar()
    imgui.show_test_window()
    imgui.begin("Custom window", True)
    imgui.text("Bar")
    imgui.text_colored("Eggs", 0.2, 1., 0.)
    imgui.end()
def main():
    window, gl_context = impl_pysdl2_init()
    imgui.create_context()
    impl = SDL2Renderer(window)

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

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

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

        imgui.render()
        impl.render(imgui.get_draw_data())
        SDL_GL_SwapWindow(window)

    impl.shutdown()
    SDL_GL_DeleteContext(gl_context)
    SDL_DestroyWindow(window)
    SDL_Quit()
Beispiel #10
0
def main():
    ctx = imgui.create_context()
    implot.create_context()
    implot.set_imgui_context(ctx)

    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_ansi("B\033[31marA\033[mnsi ")
        imgui.text_ansi_colored("Eg\033[31mgAn\033[msi ", 0.2, 1., 0.)
        imgui.extra.text_ansi_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        # show_test_window()
        imgui.show_test_window()
        implot.show_demo_window()

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

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Beispiel #11
0
def main():
    window = impl_glfw_init()
    impl = GlfwImpl(window)

    opened = True

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, selected_quit = imgui.menu_item("Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(1)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_user_guide()
        imgui.show_test_window()

        if opened:
            expanded, opened = imgui.begin("fooo", True)
            imgui.text("Bar")
            imgui.text_colored("Eggs", 0.2, 1., 0.)
            imgui.end()

        with imgui.styled(imgui.STYLE_ALPHA, 1):
            imgui.show_metrics_window()

        gl.glClearColor(114 / 255., 144 / 255., 154 / 255., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        glfw.swap_buffers(window)

    impl.shutdown()
    imgui.shutdown()
    glfw.terminate()
Beispiel #12
0
    def menu(self):

        imgui.new_frame()

        #menu bar
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Ctrl+Q', False, True)

                if clicked_quit:
                    glfw.set_window_should_close(self.window, True)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Demo window", True)
        imgui.text('ImGuiDemo')
        imgui.text_colored("* hold Left Mouse Button and drag to translate",
                           0.2, 1., 0.)
        imgui.text_colored("* use scroll wheel to zoom", 0.4, 1., 0.)
        imgui.text_colored("* press SPACE to toggle animation", 0.6, 1., 0.)

        changed, self.ui.animate = imgui.checkbox("Animate", self.ui.animate)
        changed, self.ui.gamma = imgui.slider_float("Gamma", self.ui.gamma,
                                                    0.3, 3.3)
        changed, self.ui.blue = imgui.slider_float("Blue", self.ui.blue, 0.0,
                                                   1.0)
        imgui.text("Animation Angle: {:0.2f}".format(self.ui.theta /
                                                     (2.0 * np.pi) * 360.0))
        changed, self.ui.speed = imgui.slider_float("Speed", self.ui.speed,
                                                    0.0, np.pi / 2.0)

        #transfer changed variables to shader programs
        self.quad['blue'] = self.ui.blue
        self.quad['gamma'] = self.ui.gamma

        imgui.end()
Beispiel #13
0
    def render(self, time: float, frametime: float):
        global selected_symbol
        global input_text
        self.candlestick_chart.render()
        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )
                if clicked_quit:
                    exit(1)
                imgui.end_menu()
            changed, value = imgui.input_text("", input_text, 30)
            if changed:
                imgui.set_next_window_position(imgui.get_item_rect_min().x,
                                               imgui.get_item_rect_max().y)
                imgui.set_next_window_size(imgui.get_item_rect_size().x, 0)
                if imgui.begin("##popup", False,
                               imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE):
                    for index, row in symbol_list.iterrows():
                        if value.upper() in row[0]:
                            opened, selected = imgui.selectable(row[0] + " - " + row[2])
                            if imgui.is_item_clicked():
                                input_text = row[0]
                                selected_symbol = row[0]
                imgui.end()
            if imgui.button("download"):
                yfc.download(selected_symbol, symbol_data_file())
            imgui.end_main_menu_bar()

        if not imgui.get_io().want_capture_mouse:
            self.candlestick_chart.render_gui()
        # if len(df):
        #     graphics.draw_table(df, 0)

        imgui.show_test_window()

        imgui.render()
        self.imgui.render(imgui.get_draw_data())
Beispiel #14
0
    def update(dt, field_texture):
        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", "Cmd+Q", False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.image(field_texture.id,
                    field_texture.width,
                    field_texture.height,
                    border_color=(1, 0, 0, 1))
        imgui.end()
Beispiel #15
0
def main():
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

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

        imgui.render()
        glfw.swap_buffers(window)

    impl.shutdown()
    imgui.shutdown()
    glfw.terminate()
    def render_ui(self):
        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        imgui.render()
        self.imgui.render(imgui.get_draw_data())
Beispiel #17
0
def main():
    width, height = 1280, 720
    window_name = "minimal ImGui/GLFW3 example"

    if not glfw.init():
        print("Could not initialize OpenGL context")
        exit(1)

    # OS X supports only forward-compatible core profiles from 3.2
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(int(width), int(height), window_name, None,
                                None)
    glfw.make_context_current(window)

    if not window:
        glfw.terminate()
        print("Could not initialize Window")
        exit(1)

    imgui_ctx = GlfwImpl(window)
    imgui_ctx.enable()

    opened = True

    style = imgui.GuiStyle()

    while not glfw.window_should_close(window):
        glfw.poll_events()
        imgui_ctx.new_frame()

        imgui.show_user_guide()
        imgui.show_test_window()

        if opened:
            expanded, opened = imgui.begin("fooo", True)
            imgui.text("Bar")
            imgui.text_colored("Eggs", 0.2, 1., 0.)
            imgui.end()

        with imgui.styled(imgui.STYLE_ALPHA, 1):
            imgui.show_metrics_window()

        imgui.show_style_editor(style)

        # note: this is redundant
        width, height = glfw.get_framebuffer_size(window)
        gl.glViewport(0, 0, int(width / 2), int(height))

        gl.glClearColor(114 / 255., 144 / 255., 154 / 255., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        glfw.swap_buffers(window)

    glfw.terminate()
Beispiel #18
0
    if touch != None:
        curX = touch['cur_x'] + w // 2
        curY = -touch['cur_y'] + h // 2
        press = touch['is_holded'] | touch['is_moved']
    impl.process_inputs()

    core.update()

    imgui.new_frame()

    if imgui.begin_main_menu_bar():
        if imgui.begin_menu("File", True):
            clicked_quit, selected_quit = imgui.menu_item("Quit", 'Cmd+Q', False, True)
            if clicked_quit:
                exit(1)
            imgui.end_menu()
        imgui.end_main_menu_bar()

    imgui.show_test_window()

    imgui.begin("Custom window", True)
    imgui.text("Bar")
    imgui.text("w={}:h={}".format(w, h))
    imgui.text("x={}:y={}:press={}".format(curX, curY, press))
    imgui.text_colored("Eggs", 0.2, 1., 0.)
    imgui.end()

    imgui.render()
    impl.render(imgui.get_draw_data())
    core.swap()
Beispiel #19
0
def main():
    if len(sys.argv) < 2:
        print('I need a path to the project\'s root')
        return 1

    project_path = Path(sys.argv[1])
    if not os.path.isdir(project_path):
        print('Invalid path')
        return 1

    project_file = project_path / 'project.plik'
    if os.path.isfile(project_file):
        printf(HTML(f'<gray>Found project file at {project_file}</gray>'))

    # Init graphics
    imgui.create_context()
    window = _glfw_init(500, 1000)
    renderer = GlfwRenderer(window)

    __main_locals_marker = None

    def on_glfw_key(window, key, scancode, action, mods):
        renderer.keyboard_callback(window, key, scancode, action, mods)

        if action == glfw.RELEASE:
            if key in (glfw.KEY_PAUSE, glfw.KEY_SCROLL_LOCK):
                # Pretty slow I assume, but reliable
                frame = inspect.currentframe()
                while frame:
                    if '__main_locals_marker' in frame.f_locals:
                        break
                    frame = frame.f_back

                ipshell(local_ns=frame.f_locals)

    # Need to set this after creating the renderer because by default it does its own hooks
    glfw.set_key_callback(window, on_glfw_key)

    #  TODO
    state = State()
    state.project_path = project_path
    state.project_file = project_file

    app.prompt.start(state)

    running = True
    while not glfw.window_should_close(window) and running:

        glfw.poll_events()
        renderer.process_inputs()

        # TODO Render only when any events are detected to lower CPU usage
        imgui.new_frame()

        imgui.show_test_window()

        # state.window_width, state.window_height = glfw.get_window_size(window)
        # TODO Just set the font at the beginning!
        # with imgui.font(font):
        running = app.prompt.process_next_entry(state)

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

        imgui.render()
        renderer.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    renderer.shutdown()
    glfw.terminate()
Beispiel #20
0
    def on_draw(dt):
        nonlocal bpm_window_average, p

        window.clear()

        audio.process()
        if audio.beat_on.value:
            bpm = float(bpm_from_last_beat)
            print(bpm)
            if is_bpm_sensible(bpm):
                current_bpm.value = bpm_window_average(bpm)
                print("--- bpm", bpm, "---")
            else:
                print("hmm?", bpm)
            last_beat.value = float(time)

        is_beat_running = bpm_fits_lower_threshold(bpm_from_last_beat)
        if not is_beat_running and not p:
            bpm_window_average = sliding_window_average(8)
            print("-- empty --")
            p = True
        if is_beat_running:
            p = False

        w, h = window.get_size()
        pipeline.render_screen(None, (w, h))

        if render_hud:
            #print(audio._current_beat_amplitude, audio.vu.value, audio.vu_norm.value)
            #print(audio.vu._evaluated, audio.vu._value)
            color = (0.0, 1.0, 0.0, 1.0)
            bg_color = (0.0, 0.0, 0.0, 0.8)
            box_height = 200
            bounds = (10, h - box_height - 10, w - 10, h - 10)

            threshold_color = (1.0, 0.0, 0.0, 1.0)
            threshold = audio.beat_threshold
            threshold_y = float(
                var.Const(threshold).map_range(0.0, 1.0, bounds[3], bounds[1]))

            ortho_px = glm.ortho(0, w, 0, h, -1.0, 1.0)
            glm.scale(ortho_px, 1.0, -1.0, 1.0)
            plot_values(audio.beat_values, ortho_px, bounds, color, bg_color,
                        [0.0, 1.0])
            primitive.draw_line((bounds[0], threshold_y),
                                (bounds[2], threshold_y), threshold_color,
                                ortho_px)

            #fft = audio._current_fft
            #freqs = fftpack.fftfreq(len(fft), d=1.0 / 5000.0)
            #fft = fft[0:len(fft) // 2] * 0.05
            #if len(fft) > 1:
            #    plot_bar_values(fft, ortho_px, (10, 10, w - 10, 210), color, bg_color, [0.0, 1.0])
            #print(freqs)

        imgui_renderer.process_inputs()
        imgui.new_frame()
        imgui.show_test_window()

        imgui.set_next_window_position(10,
                                       10,
                                       condition=imgui.ALWAYS,
                                       pivot_x=0,
                                       pivot_y=0)
        imgui.set_next_window_size(0.0, 0.0)
        flags = imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE + imgui.WINDOW_NO_MOVE + imgui.WINDOW_NO_COLLAPSE

        imgui.begin("Stats", None, flags)
        imgui.text("FPS: %.2f" % app.clock.get_fps())
        imgui.text("Current BPM: %.2f" % current_bpm.value)
        imgui.text("Beat running: %s" % {
            True: "Yes",
            False: "Nope"
        }[is_beat_running])
        imgui.end()

        imgui.render()
        imgui_renderer.render(imgui.get_draw_data())

        #print("Resetting:", repr(Event), audio.vu in Event._instances)
        Event.reset_instances()
        GenerativeStage.reset_instances()

        var.ReloadVar.reload_vars()
Beispiel #21
0
async def draw() -> Eff[[ACTIONS], None]:
    global state

    im.show_metrics_window()
    im.show_test_window()

    # ------------------------
    # t_flags = 0
    # t_flags = (
    # 	  im.WINDOW_NO_TITLE_BAR
    # 	| im.WINDOW_NO_MOVE
    # 	| im.WINDOW_NO_RESIZE
    # 	| im.WINDOW_NO_COLLAPSE
    # 	| im.WINDOW_NO_FOCUS_ON_APPEARING
    # 	| im.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS
    # )
    # with window(name="test", flags=t_flags):
    # 	im.button("bloop")
    # 	pos = util.point_offset(im.get_window_position(), im.Vec2(40, 80))
    # 	im.set_next_window_position(pos.x, pos.y)
    # 	with window(name="a window"):
    # 		im.text("I'm a window")

    # 	top_left = im.get_item_rect_min()
    # 	size = im.get_item_rect_size()
    # 	bottom_right = util.point_offset(top_left, size)
    # 	im.text('TL: '+str(top_left))
    # 	im.text('BR: '+str(bottom_right))
    # 	util.add_rect(im.get_window_draw_list(), util.Rect(top_left, bottom_right), (1.,1.,1.,1.))

    debug_log("test_drew", False)
    with window("test") as (expanded, _):
        only_draw_if(expanded)

        debug_log("test_drew", True)  # only_draw_if didn't abort, overwrite
        US = ui['settings']

        opts = ['first', 'second', 'third']
        default_state = ('no_selection', None)

        US.setdefault('selectable_state', default_state)
        US.setdefault('selectable_added', [])
        if not im.is_window_focused():
            US['selectable_state'] = default_state

        changed, selection_changed, selectable_state = double_click_listbox(
            US['selectable_state'], opts)
        if changed:
            US['selectable_state'] = selectable_state

        o_ix = selectable_state[1]
        im.text_colored(
            "[ {!s:<10} ] {}".format(opts[o_ix] if o_ix is not None else "---",
                                     "(!)" if selection_changed else ""),
            *(0.3, 0.8, 0.5))
        im.text("")
        im.text("{!r:<5} {!r:<5} {}".format(changed, selection_changed,
                                            selectable_state))

        if selectable_state[0] == 'double_clicked':
            US['selectable_added'].append(opts[selectable_state[1]])
        im.text(str(US['selectable_added']))

        c = im.is_mouse_clicked()
        dc = im.is_mouse_double_clicked()
        im.text("{!r:<5} {!r:<5} {!r:<5}".format(c, dc, c and dc))
        im.text("focused: " + repr(im.is_window_focused()))

    with window(name="signals"):
        if im.button("load example"):
            await emit(FileAction.Load(filename=example_file_path))

        if len(state.data.signals) > 0:

            def right_pad(s: str, limit: int) -> str:
                n_spaces = max(0, limit - len(s))
                return s + (' ' * n_spaces)

            for sig_id, sig_name in sorted(state.data.signal_names.items(),
                                           key=lambda pair: pair[1]):
                im.text_colored(right_pad(sig_name, 5), 0.2, 0.8, 1)
                im.same_line()
                signal = state.data.signals[sig_id]
                im.text(str(signal))
        else:
            im.text("No signals loaded")

    # -------------------------
    # with window(name="modules"):
    # 	modules = sorted(
    #		rlu.all_modules(dir=pathlib.Path.cwd()),
    #		key=lambda mod: (getattr(mod, '__reload_incarnation__', -1), mod.__name__)
    #	)
    # 	for mod in modules:
    # 		incarnation_text = str(getattr(mod, '__reload_incarnation__', '-'))
    # 		im.text("{mod}[{inc}]".format(mod=mod.__name__, inc=incarnation_text))

    with window(name="settings"):
        ui_settings = ui['settings']
        changed, move = im.checkbox("move plots",
                                    ui_settings['plot_window_movable'])
        if changed:
            ui_settings['plot_window_movable'] = move

        # im.same_line()
        changed, option = str_combo(
            "resample", ui_settings['plot_resample_function'],
            ['numpy_interp', 'scipy_zoom', 'crude_downsample'])
        if changed:
            ui_settings['plot_resample_function'] = option

        # im.same_line()
        changed, option = str_combo("plots", ui_settings['plot_draw_function'],
                                    ['imgui', 'manual'])
        if changed:
            ui_settings['plot_draw_function'] = option

        changed, val = im.slider_float('filter_slider_power',
                                       ui_settings['filter_slider_power'],
                                       min_value=1.,
                                       max_value=5.,
                                       power=1.0)
        if changed:
            ui_settings['filter_slider_power'] = val

        if im.button("reload"):
            await emit(AppRunnerAction.Reload())

        # im.same_line()
        # im.button("bla bla bla")

        # im.same_line()
        # im.button("ple ple ple")

        im.text("state | ")

        im.same_line()
        if im.button("dump##state"):
            await emit(AppStateAction.SaveState)

        im.same_line()
        if im.button("load##state"):
            await emit(AppStateAction.LoadState)

        im.same_line()
        if im.button("reset##state"):
            await emit(AppStateAction.ResetState)

        im.text("history | ")

        im.same_line()
        if im.button("dump##history"):
            await emit(AppStateAction.SaveUserActionHistory)

        im.same_line()
        if im.button("load##history"):
            await emit(AppStateAction.LoadUserActionHistory)

        im.same_line()
        if im.button("reset##history"):
            await emit(AppStateAction.ResetUserActionHistory)

        im.same_line()
        if im.button("run##history"):
            await emit(AppStateAction.RunHistory)

    # TODO: Window positions can theoretically be accessed
    # after being drawn using internal APIs.
    # See:
    #	imgui_internal.h > ImGuiWindow (search "struct IMGUI_API ImGuiWindow")
    #	imgui.cpp        > ImGui::GetCurrentContext()
    #
    # (sort-of pseudocode example)
    #
    # foo_id = None
    #
    # with window("foo"):
    # 	foo_id = GetCurrentWindow().ID
    # 	...
    #
    # ...
    #
    # with window("accessing other windows"):
    # 	windows = imgui.GetCurrentContext().Windows
    # 	foo_win = windows[ windows.find(lambda win: win.ID = foo_id) ]
    # 	im.text( "pos:{}, size:{}".format(foo_win.Pos, foo_win.Size) )

    # ----------------------------
    # await ng.graph_window(state.graph)

    prev_color_window_background = im.get_style().color(
        im.COLOR_WINDOW_BACKGROUND)

    im.set_next_window_position(0, 100)
    with color({im.COLOR_WINDOW_BACKGROUND: (0., 0., 0., 0.05)}), \
      window(name="nodes",
       flags = (
          im.WINDOW_NO_TITLE_BAR
        # | im.WINDOW_NO_MOVE
        # | im.WINDOW_NO_RESIZE
        | im.WINDOW_NO_COLLAPSE
        | im.WINDOW_NO_FOCUS_ON_APPEARING
        | im.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS
       )
      ):
        box_positions = {}
        inputs = ng.get_inputs(state.graph, state.data.box_outputs)

        with color({im.COLOR_WINDOW_BACKGROUND: prev_color_window_background}):

            # source boxes
            for (id_, box_state) in state.source_boxes.items():
                pos = await signal_source_window(box_state, state.data.signals,
                                                 state.data.signal_names)
                box_positions[id_] = pos

            # filter boxes
            for (id_, box_state) in state.filter_boxes.items():
                pos = await filter_box_window(box_state,
                                              ui_settings=ui_settings)
                box_positions[id_] = pos

            # signal plot 1
            for (id_, box_state) in state.plots.items():
                pos = await signal_plot_window(box_state,
                                               inputs[id_],
                                               ui_settings=ui_settings)
                box_positions[id_] = pos

        # connections between boxes
        link_selection = state.link_selection

        prev_cursor_screen_pos = im.get_cursor_screen_position()

        # get slot coords and draw slots
        with color({im.COLOR_CHECK_MARK: (0, 0, 0, 100 / 255)}):
            draw_list = im.get_window_draw_list()
            SPACING = 20.
            slot_center_positions = {}

            for (id_, position) in box_positions.items():
                node = state.graph.nodes[id_]

                left_x = position.top_left.x
                right_x = position.bottom_right.x
                top_y = position.top_left.y

                for slot_ix in range(node.n_inputs):
                    pos = im.Vec2(left_x - 20 - 3,
                                  top_y + 30 + slot_ix * SPACING)
                    im.set_cursor_screen_position(pos)

                    slot = ng.InputSlotId(id_, slot_ix)
                    was_selected = (slot == link_selection.dst_slot)

                    changed, selected = im.checkbox(
                        "##in{}{}".format(id_, slot_ix), was_selected)
                    if changed:
                        await emit(LinkSelectionAction.ClickInput(slot))

                    center_pos = util.rect_center(
                        util.get_item_rect())  # bounding rect of prev widget
                    slot_center_positions[('in', id_, slot_ix)] = center_pos

                for slot_ix in range(node.n_outputs):
                    pos = im.Vec2(right_x + 3, top_y + 30 + slot_ix * SPACING)
                    im.set_cursor_screen_position(pos)

                    slot = ng.OutputSlotId(id_, slot_ix)
                    was_selected = (slot == link_selection.src_slot)

                    changed, selected = im.checkbox(
                        "##out{}{}".format(id_, slot_ix), was_selected)
                    if changed:
                        await emit(LinkSelectionAction.ClickOutput(slot))

                    center_pos = util.rect_center(
                        util.get_item_rect())  # bounding rect of prev widget
                    slot_center_positions[('out', id_, slot_ix)] = center_pos

        # end drawing slots

        # draw links
        for (src, dst) in state.graph.links:
            src_pos = slot_center_positions[('out', src.node_id, src.ix)]
            dst_pos = slot_center_positions[('in', dst.node_id, dst.ix)]
            draw_list.add_line(*src_pos,
                               *dst_pos,
                               col=im.get_color_u32_rgba(0.5, 0.5, 0.5, 1.),
                               thickness=2.)

        im.set_cursor_screen_position(prev_cursor_screen_pos)
    # end nodes window

    im.show_style_editor()
Beispiel #22
0
def draw(imgui) -> None:
    global show_sendable_debug
    global show_demo
    global active_widgets

    if imgui.begin_main_menu_bar():
        if imgui.begin_menu("Help"):
            clicked, _ = imgui.menu_item(
                "Hide Demo" if show_demo else "Show Demo")
            if clicked:
                show_demo = not show_demo
            imgui.end_menu()
        imgui.end_main_menu_bar()

    if show_demo:
        imgui.show_test_window()

    if imgui.begin('All Entries'):
        if imgui.begin_popup_context_window():
            clicked, do_debug = imgui.checkbox('Show Chooser Debug Info',
                                               show_sendable_debug)
            if clicked:
                show_sendable_debug = do_debug
            imgui.end_popup()

        def table_tree(table: EntryGroup):
            for key, entry in table.items():
                if isinstance(entry, NetworkTableEntry):
                    imgui.text(entry_name(key) + ': ' + str(entry.value))

                    imgui.same_line()
                    imgui.push_id(key)
                    if imgui.button('Add'):
                        active_widgets[key] = Widget(entry)
                    imgui.pop_id()
                else:
                    t = NetworkTables.getTable(key)
                    if '.type' in t.getKeys():
                        name = t.getString('.name', '')

                        imgui.text(name)

                        imgui.same_line()
                        imgui.push_id(key)
                        if imgui.button('Add'):
                            active_widgets[key] = Widget(t, EntryType.Chooser)
                        imgui.pop_id()

                        if show_sendable_debug:
                            if imgui.tree_node('Chooser Debug (' + key + ')'):
                                table_tree(entry)
                                imgui.tree_pop()
                    elif imgui.tree_node(entry_name(key),
                                         imgui.TREE_NODE_DEFAULT_OPEN):
                        # nothing fancy, just a subtable
                        table_tree(entry)
                        imgui.tree_pop()

        entries = buildList(
            sorted(NetworkTables.getEntries('', 0), key=lambda e: e.getName()))
        table_tree(entries)
    imgui.end()

    to_close: List[str] = []
    for key, widget in active_widgets.items():
        expanded, opened = imgui.begin(entry_name(key), True)
        if not opened:
            to_close.append(key)

        if ((widget.tipe.is_entry() and widget.entry is None)
                or (not widget.tipe.is_entry() and widget.table is None)):
            imgui.text_colored('WARNING! Disconnected!', 1, 0, 0)
            imgui.end()
            continue

        if widget.tipe == EntryType.Boolean:
            assert widget.entry is not None

            if widget.show_indicator:
                imgui.push_item_width(-1)
                r, g, b = (0, 1, 0) if widget.entry.value else (1, 0, 0)
                imgui.color_button(key + '/indicator',
                                   r,
                                   g,
                                   b,
                                   width=imgui.get_window_width(),
                                   height=100)

            clicked, new_val = imgui.checkbox('on', widget.entry.value)
            if clicked:
                widget.entry.setValue(new_val)
        elif widget.tipe == EntryType.Double:
            assert widget.entry is not None

            val = str(widget.entry.getDouble(0))
            changed, new_val = imgui.input_text('', val, 64,
                                                imgui.INPUT_TEXT_CHARS_DECIMAL)
            if changed:
                try:
                    widget.entry.setDouble(float(new_val))
                except ValueError:
                    pass
        elif widget.tipe == EntryType.String:
            assert widget.entry is not None

            changed, new_val = imgui.input_text('', widget.entry.getString(''),
                                                256)
            if changed:
                widget.entry.setString(new_val)
        elif widget.tipe == EntryType.Chooser:
            assert widget.table is not None

            values = widget.table.getStringArray('options', [])
            try:
                selected = values.index(widget.table.getString('active', ''))
            except ValueError:
                selected = 0

            changed, current = imgui.combo('', selected, values)
            if changed:
                widget.table.putString('active', values[current])
        else:
            try:
                assert widget.entry is not None
                imgui.text(str(widget.entry.value))
            except AttributeError:
                imgui.text('Could not view contents.')

        if imgui.begin_popup_context_window():
            if widget.tipe == EntryType.Boolean:
                clicked, new_val = imgui.checkbox('Show Indicator',
                                                  widget.show_indicator)
                if clicked:
                    widget.show_indicator = new_val
            imgui.end_popup()

        # imgui.button('Options')

        imgui.end()

    for key in to_close:
        active_widgets.pop(key)
Beispiel #23
0
 def draw(self):
     imgui.show_test_window()