Exemplo n.º 1
0
    def __enter__(self):
        glClearColor(0, 1, 0, 0)

        while not glfw.window_should_close(self.window):
            cur_time = glfw.get_time()
            elapsed = cur_time - self.prev_time
            self.prev_time = cur_time

            glfw.poll_events()
            self.impl.process_inputs()

            self._process(elapsed)

            imgui.new_frame()

            imgui.set_next_window_position(0, 0)
            imgui.set_next_window_size(280, 180)

            imgui.begin("Uniforms", False, imgui.WINDOW_NO_RESIZE)

            imgui.push_item_width(-45)

            for cont in self.program.controls:
                cont.update()

            imgui.end()

            glClear(GL_COLOR_BUFFER_BIT)
            self._draw()

            imgui.render()
            self.impl.render(imgui.get_draw_data())

            glfw.swap_buffers(self.window)
Exemplo n.º 2
0
 def _show(self, value, read_only):
     imgui.push_item_width(self.width)
     changed, v = imgui.input_text("", value.value, 255,
                                   imgui.INPUT_TEXT_ENTER_RETURNS_TRUE)
     if imgui.is_item_hovered() and not imgui.is_item_active():
         imgui.set_tooltip(value.value)
     if changed:
         value.value = v
Exemplo n.º 3
0
 def _show(self, value, read_only):
     imgui.push_item_width(self.width)
     changed, v = imgui.drag_float("",
                                   value.value,
                                   change_speed=self.drag_factor,
                                   min_value=self.minmax[0],
                                   max_value=self.minmax[1],
                                   format="%0.4f")
     if changed and not read_only:
         value.value = self.clamper(v)
Exemplo n.º 4
0
 def _show_custom_ui(self):
     imgui.push_item_width(widget.WIDGET_WIDTH)
     if self.duplicate:
         imgui.push_style_color(imgui.COLOR_TEXT, 1.0, 0.0, 0.0)
     changed, v = imgui.input_text("", self.get("name"), 255, imgui.INPUT_TEXT_ENTER_RETURNS_TRUE)
     if self.duplicate:
         imgui.pop_style_color()
         if imgui.is_item_hovered():
             imgui.set_tooltip("Name is a duplicate!")
     if changed:
         self.name = v
Exemplo n.º 5
0
def _imgui_pick_file_menu(base_path, wildcard="*"):
    MAX_FILE_DISPLAY_LENGTH = 60

    try:
        entries = []
        for name in os.listdir(base_path):
            entries.append(
                (not os.path.isdir(os.path.join(base_path, name)), name))

        imgui.text("New:")
        imgui.same_line()
        imgui.push_item_width(-1)
        changed, value = imgui.input_text("", "", 255,
                                          imgui.INPUT_TEXT_ENTER_RETURNS_TRUE)
        if changed:
            return os.path.join(base_path, value)
        imgui.separator()
        for w in WILDCARDS:
            if imgui.button(w):
                return os.path.join(base_path, w)
            imgui.same_line()
        imgui.dummy(0, 0)
        imgui.separator()

        if len(entries) == 0:
            imgui.dummy(200, 0)

        for not_is_dir, name in sorted(entries):
            display_name = name
            if len(display_name) > MAX_FILE_DISPLAY_LENGTH:
                display_name = display_name[:MAX_FILE_DISPLAY_LENGTH //
                                            2] + "..." + display_name[
                                                -MAX_FILE_DISPLAY_LENGTH // 2:]

            if not not_is_dir:
                if imgui.begin_menu(display_name):
                    selected_path = _imgui_pick_file_menu(
                        os.path.join(base_path, name), wildcard)
                    imgui.end_menu()
                    if selected_path is not None:
                        return os.path.join(base_path, selected_path)
            else:
                if not fnmatch.fnmatch(name, wildcard):
                    continue
                clicked, state = imgui.menu_item(display_name, None, False)
                if clicked:
                    return os.path.join(base_path, name)

        imgui.separator()
        imgui.text("Pick: %s" % wildcard)
    except:
        imgui.text("Unable to open dir")
Exemplo n.º 6
0
    def _show_custom_ui(self):
        current_device_name = "<none>"
        if self._device is not None:
            current_device_name = self._device.name

        imgui.push_item_width(150)
        if imgui.begin_combo("", current_device_name):
            for device_name in mido.get_input_names():
                is_selected = device_name == current_device_name
                opened, selected = imgui.selectable(device_name, is_selected)
                if opened:
                    self.connect(device_name)
                if is_selected:
                    imgui.set_item_default_focus()
            imgui.end_combo()
Exemplo n.º 7
0
def listbox_dict(dict_string_value, current_key, title_top="", title_right="", height_in_items=20, item_width=None):
    keys = [key for key, _ in dict_string_value.items()]
    if current_key in keys:
        current_idx = keys.index(current_key)
    else:
        current_idx = -1
    if item_width is not None:
        imgui.push_item_width(item_width)
    if title_top != "":
        imgui.text(title_top)
    changed, new_idx = imgui.listbox(title_right, current_idx, keys, height_in_items=height_in_items)
    if 0 <= new_idx < len(keys):
        new_key = keys[new_idx]
    else:
        new_key = ""
    return changed, new_key
Exemplo n.º 8
0
def drawUi(width, height):
    global g_triangleVerts
    global g_cameraDistance
    global g_cameraYawDeg
    global g_cameraPitchDeg
    global g_yFovDeg

    imgui.push_item_width(200)
    _, g_cameraDistance = imgui.slider_float("CameraDistance",
                                             g_cameraDistance, 1.00, 20.0)
    _, g_yFovDeg = imgui.slider_float("Y-Fov (Deg)", g_yFovDeg, 1.00, 90.0)
    _, g_cameraYawDeg = imgui.slider_float("Camera Yaw (Deg)", g_cameraYawDeg,
                                           -180.00, 180.0)
    _, g_cameraPitchDeg = imgui.slider_float("Camera Pitch (Deg)",
                                             g_cameraPitchDeg, -89.00, 89.0)
    imgui.pop_item_width()
Exemplo n.º 9
0
    def render(self):
        events = yield from c.window(
            title=self.name,
            widget=c.multi_orr([
                c.text("Style: "),
                c.orr_same_line([
                    c.radio_button(label, active=self.style == label)
                    for label in self.style_choices
                ]),
                c.spacing(),
                c.text("Username: "******"inject" ImGui calls into the rendering routine.
                # It may be better to abstract these `lift` calls out into a function (or not).
                # Note that Concur (and ImGui as a whole) are primarily made for debug interfaces, so custom styling like this is a bit clunky.
                # The calls used for sizing are [documented here](https://pyimgui.readthedocs.io/en/latest/reference/imgui.core.html).
                # You can do a whole lot of customization like this, I recommend skimming through the above link.
                c.lift(lambda: imgui.push_item_width(100)),
                c.input_text(name="",
                             value=self.username,
                             tag="Username",
                             buffer_length=10),
                c.text("Password: "******"",
                                    value=self.password,
                                    tag="Password"),
                c.lift(lambda: imgui.pop_item_width()),
                c.checkbox("Remember credentials", self.remember_credentials),
                c.spacing(),
                c.text("Input file: "),
                c.same_line(),
                c.text(self.filepath),
                c.button("Open"),
                self.custom_spacing(0, 20),
                c.separator(),
                c.button("Save"),
                c.same_line(),
                c.button("Reset"),
            ]))

        for tag, value in events:  # This is how event handling works with `multi_orr`
            if tag in self.style_choices:
                self.style = tag
                self.style_choices[tag]()
            elif tag == "Open":
                self.prompt_for_input_file()
            elif tag == "Username":
                self.username = value
            elif tag == "Password":
                self.password = value
            elif tag == "Remember credentials":
                self.remember_credentials = value
            elif tag == "Save":
                print("Saved")
            elif tag == "Reset":
                print("Resetted")

        return self
Exemplo n.º 10
0
    def _show(self, value, read_only):
        imgui.push_item_width(self.width)
        changed, v = imgui.input_text("", value.value, 255,
                                      imgui.INPUT_TEXT_ENTER_RETURNS_TRUE)
        if imgui.is_item_hovered() and not imgui.is_item_active():
            imgui.set_tooltip(value.value)
        if changed:
            value.value = v
            return
        imgui.push_item_width(self.width)
        if imgui.button("Select file"):
            imgui.open_popup("select_file")

        path = imgui_pick_file("select_file",
                               assets.ASSET_PATH + "/" + self.prefix)
        if path is not None:
            value.value = os.path.relpath(path, assets.ASSET_PATH)
Exemplo n.º 11
0
    def _show(self, value, read_only):
        imgui.push_item_width(self.width)
        imgui.push_id("v0")
        changed0, v0 = imgui.drag_float("",
                                        value.value[0],
                                        change_speed=self.drag_factor,
                                        format="%0.4f")
        imgui.pop_id()

        imgui.push_item_width(self.width)
        imgui.push_id("v1")
        changed1, v1 = imgui.drag_float("",
                                        value.value[1],
                                        change_speed=self.drag_factor,
                                        format="%0.4f")
        imgui.pop_id()

        if (changed0 or changed1) and not read_only:
            value.value = np.array([v0, v1])
Exemplo n.º 12
0
    def _show_custom_ui(self):
        imgui.dummy(0, 10)
        imgui.text("Sourced %d blocks" % self.blocks)

        sinks = self.pulse.sinks
        current_sink_index = self.pulse.current_sink_index
        current_sink_name = sinks.get(current_sink_index, "<unknown>")
        #print("Unkown sink %s out of %s" % (repr(current_sink_index), sinks))

        imgui.push_item_width(250)
        if imgui.begin_combo("", current_sink_name):
            for index, sink_name in sinks.items():
                is_selected = index == current_sink_index
                opened, selected = imgui.selectable(sink_name, is_selected)
                if opened:
                    self.pulse.current_sink_index = index
                if is_selected:
                    imgui.set_item_default_focus()
            imgui.end_combo()
Exemplo n.º 13
0
    def _show_custom_ui(self):
        imgui.dummy(1, 5)
        imgui.text("lambda x:")
        imgui.push_item_width(208)
        changed, text = imgui.input_text("", self.get("lambda"), 255,
                                         imgui.INPUT_TEXT_ENTER_RETURNS_TRUE)
        if changed:
            self.get_input("lambda").value = text

        if self.compile_error is not None:
            imgui.text_colored("Compilation error. (?)", 1.0, 0.0, 0.0)
            if imgui.is_item_hovered():
                imgui.set_tooltip(self.compile_error)
        elif self.run_error is not None:
            imgui.text_colored("Runtime error. (?)", 1.0, 0.0, 0.0)
            if imgui.is_item_hovered():
                imgui.set_tooltip(self.run_error)
        else:
            imgui.text("Lambda compiled.")
Exemplo n.º 14
0
 def __auth_view(self):
     view = c.orr([
         c.collapsing_header(
             text="Languages",
             widget=c.orr([
                 c.radio_button(
                     label='English',
                     active=True if self.language == 'default' else False,
                     tag='english'),
                 c.same_line(),
                 c.radio_button(
                     label='Russian',
                     active=True if self.language == 'cyrillic' else False,
                     tag='cyrillic'),
                 c.same_line(),
                 c.radio_button(
                     label='Korean',
                     active=True if self.language == 'korean' else False,
                     tag='korean'),
                 c.same_line(),
                 c.radio_button(
                     label='Japanese',
                     active=True if self.language == 'japanese' else False,
                     tag='japanese'),
                 c.same_line(),
                 c.radio_button(label='Chinese',
                                active=True if self.language
                                == 'chinese_full' else False,
                                tag='chinese_full'),
                 c.same_line(),
                 c.radio_button(
                     label='German',
                     active=True if self.language == 'latin' else False,
                     tag='latin'),
             ]),
             open=True),
         self.custom_spacing(1, 1),
         c.text("Username:"******"", value=self.username, tag="username"),
         c.text("Password:"******"", value=self.password, tag="password"),
         c.button("Terminate", tag='terminate')
         if self.process else self.dynamic_popup_button(
             label="Login",
             error=self.evaluate_popup_behaviour({
                 'user': self.username,
                 'password': self.password
             }),
             tag='login'),
     ])
     return view
Exemplo n.º 15
0
    def draw_btn_bar(self):
        # 按钮栏
        utils.set_cursor_offset(6, 0)
        if imgui.button("clear"):
            print("清理")
            self.log_mgr.clear()
        imgui.same_line()

        # log等级
        for idx, log_level in enumerate(self.log_level_lst):
            is_check = self.config.is_has_log_level(log_level)
            ret = imgui.checkbox(self.log_level[idx], is_check)
            imgui.same_line()
            if ret[1] == is_check:
                continue
            if ret[1]:
                self.config.add_log_level(log_level)
            else:
                self.config.remove_log_level(log_level)

        # 搜索框
        imgui.same_line()
        old_text = self.config.get_string(EConfigKey.CONTENT_SEARCH_TEXT)
        imgui.push_item_width(240)
        imgui.push_id(EConfigKey.CONTENT_SEARCH_TEXT)
        ret = imgui.input_text("", old_text, 128)
        imgui.pop_id()
        if ret[0]:
            self.on_search_text_change(ret[1])
        imgui.pop_item_width()
        imgui.same_line()
        utils.set_cursor_offset(-8, 0)
        if imgui.button("清空"):
            self.on_search_text_change("")

        # 是否固定到底部
        imgui.same_line()
        is_to_bottom = self.config.get_bool(
            EConfigKey.CONTENT_SCROLL_TO_BOTTOM, True)
        ret = imgui.checkbox("bottom", is_to_bottom)
        if ret[1] != is_to_bottom:
            self.config.set_bool(EConfigKey.CONTENT_SCROLL_TO_BOTTOM, ret[1])
Exemplo n.º 16
0
    def _show(self, value, read_only):
        active = value.value or time.time(
        ) - self._last_active < Button.ACTIVE_TIME
        if value.value:
            self._last_active = time.time()
        imgui.push_style_color(imgui.COLOR_BUTTON_ACTIVE, 1.0, 0.0, 0.0, 1.0)
        if active:
            imgui.push_style_color(imgui.COLOR_BUTTON, 1.0, 0.0, 0.0, 1.0)
            imgui.push_style_color(imgui.COLOR_BUTTON_HOVERED, 1.0, 0.0, 0.0,
                                   1.0)
        imgui.push_item_width(self.width)
        clicked = imgui.button("Click me")
        if active:
            imgui.pop_style_color(2)
        imgui.pop_style_color(1)

        # TODO this might be a problem
        # events are reset by this widget!

        # events are a special case!!
        # this widget gets InputValueHolder value even when an input is connected
        #   (to make sure that event trigger is displayed on the button)
        # when button is pressed even though a value is connected:
        # -> set force flag on manual value, don't forget to reset it
        value_to_set = value
        if isinstance(value, ConnectedValue):
            value_to_set = value.manual_value

        # set on click
        if clicked:
            value_to_set.value = 1.0
            if read_only:
                value_to_set.force_value = True
                self._reset_force_value = True
        elif self._reset_force_value:
            value_to_set.force_value = False
            self._reset_force_value = False

        # reset otherwise if still active
        if not clicked and value.value:
            value_to_set.value = 0.0
Exemplo n.º 17
0
 def draw_input_bar(self):
     utils.set_cursor_offset(6, 0)
     cur_cmd = self.config.get_current_cmd()
     cur_txt = self.cur_edit_txt if self.is_edit_cmd else cur_cmd
     # win_width = imgui.get_window_width()
     # win_height = imgui.get_window_height()
     imgui.push_item_width(520)
     imgui.push_id(EConfigKey.CONTENT_CMD_TXT)
     ret = imgui.input_text(
         "", cur_txt, 1024, imgui.INPUT_TEXT_ENTER_RETURNS_TRUE
         | imgui.INPUT_TEXT_CALLBACK_COMPLETION
         | imgui.INPUT_TEXT_CALLBACK_HISTORY, self.input_bar_callback)
     self.is_edit_cmd = ret[1] != cur_cmd
     if self.is_edit_cmd:
         self.cur_edit_txt = ret[1]
     if ret[0]:
         self._send_cmd(ret[1])
         # print "hello world", ret[1]
     imgui.pop_id()
     imgui.same_line()
     utils.set_cursor_offset(-8, 0)
     if imgui.button("发送命令"):
         self._send_cmd(ret[1])
Exemplo n.º 18
0
    def _draw_entity_components(self, entity):
        ValueEdit(entity, "tag", "input_text", "Tag")()

        # ---------------------------------------------------
        # add component
        # ---------------------------------------------------
        imgui.same_line()
        imgui.push_item_width(-1)

        if imgui.button("Add Component"):
            imgui.open_popup("AddComponent")

        if imgui.begin_popup("AddComponent"):
            if menu_item_clicked("Transform"):
                entity.add_component("transform")
                imgui.close_current_popup()
            if menu_item_clicked("Camera"):
                print "add component camera"
                imgui.close_current_popup()
            if menu_item_clicked("Sprite Renderer"):
                print "add component sprite renderer"
                imgui.close_current_popup()
            if menu_item_clicked("Physics"):
                entity.add_component("physics")
                imgui.close_current_popup()
            imgui.end_popup()

        imgui.pop_item_width()

        # ---------------------------------------------------
        # draw components
        # ---------------------------------------------------
        self._draw_component(entity, "transform", "Transform")
        self._draw_component(entity, "camera", "Camera")
        self._draw_component(entity, "sprite_renderer", "Sprite Renderer")
        self._draw_component(entity, "physics", "Physics")
Exemplo n.º 19
0
def render_palette(drawing: Drawing):

    global color_editor_open  # Need a persistent way to keep track of the popup being closed...
    global current_color_page

    palette = drawing.palette
    fg = palette.foreground
    bg = palette.background
    fg_color = palette.foreground_color
    bg_color = palette.background_color

    imgui.begin_child("Palette", border=False, height=460)
    # Edit foreground color
    if imgui.color_button(f"Foreground (#{fg})", *as_float(fg_color), 0, 30,
                          30):
        io = imgui.get_io()
        w, h = io.display_size
        imgui.open_popup("Edit foreground color")
        imgui.set_next_window_position(w - 115 - 120, 200)
        color_editor_open = True
    if imgui.begin_popup("Edit foreground color",
                         flags=(imgui.WINDOW_NO_MOVE
                                | imgui.WINDOW_NO_SCROLL_WITH_MOUSE)):
        done, cancelled, new_color = render_color_editor(
            palette.colors[fg], fg_color)
        if done and new_color != fg_color:
            drawing.change_colors(fg, new_color)
            palette.clear_overlay()
        elif cancelled:
            palette.clear_overlay()
        else:
            palette.set_overlay(fg, new_color)
        imgui.end_popup()
    elif color_editor_open:
        # The popup was closed by clicking outside, keeping the change (same as OK)
        drawing.change_colors(fg, fg_color)
        palette.clear_overlay()
        color_editor_open = False

    imgui.same_line()

    imgui.color_button(f"Background (#{bg})", *as_float(bg_color), 0, 30, 30)

    max_pages = len(palette.colors) // 64 - 1
    imgui.push_item_width(100)
    _, current_color_page = imgui.slider_int("Page",
                                             current_color_page,
                                             min_value=0,
                                             max_value=max_pages)
    start_color = 64 * current_color_page

    imgui.begin_child("Colors", border=False)
    imgui.push_style_var(imgui.STYLE_ITEM_SPACING,
                         (0, 0))  # Make layout tighter
    width = int(imgui.get_window_content_region_width()) // 20

    imgui.push_style_color(imgui.COLOR_FRAME_BACKGROUND, 0, 0, 0)

    colors = palette.colors

    # Order the colors by column instead of by row (which is the order we draw them)
    for i, c in enumerate(
            chain.from_iterable(
                zip(range(0, 16), range(16, 32), range(32, 48), range(48,
                                                                      64)))):
        color = colors[start_color + c]
        is_foreground = c == fg
        is_background = (c == bg) * 2
        selection = is_foreground | is_background
        color = as_float(color)

        if color[3] == 0 or selection:
            x, y = imgui.get_cursor_screen_pos()

        if imgui.color_button(f"color {i}", *color[:3], 1, 0, 25, 25):
            # io = imgui.get_io()
            # if io.key_shift:
            #     if "spread_start" in temp_vars:
            #         temp_vars["spread_end"] = i
            #     else:
            #         temp_vars["spread_start"] = i
            # else:
            fg = c

        if i % width != width - 1:
            imgui.same_line()

        draw_list = imgui.get_window_draw_list()
        if color[3] == 0:
            # Mark transparent color
            draw_list.add_line(x + 1, y + 1, x + 24, y + 24,
                               imgui.get_color_u32_rgba(0, 0, 0, 1), 1)
            draw_list.add_line(x + 1, y + 2, x + 23, y + 24,
                               imgui.get_color_u32_rgba(1, 1, 1, 1), 1)

        if is_foreground:
            # Mark foregroupd color
            draw_list.add_rect_filled(x + 2, y + 2, x + 10, y + 10,
                                      imgui.get_color_u32_rgba(1, 1, 1, 1))
            draw_list.add_rect(x + 2, y + 2, x + 10, y + 10,
                               imgui.get_color_u32_rgba(0, 0, 0, 1))
        if is_background:
            # Mark background color
            draw_list.add_rect_filled(x + 15, y + 2, x + 23, y + 10,
                                      imgui.get_color_u32_rgba(0, 0, 0, 1))
            draw_list.add_rect(x + 15, y + 2, x + 23, y + 10,
                               imgui.get_color_u32_rgba(1, 1, 1, 1))

        if imgui.core.is_item_clicked(2):
            # Right button sets background
            bg = c

        # Drag and drop (currently does not accomplish anything though)
        if imgui.begin_drag_drop_source():
            imgui.set_drag_drop_payload('start_index',
                                        c.to_bytes(1, sys.byteorder))
            imgui.color_button(f"color {c}", *color[:3], 1, 0, 20, 20)
            imgui.end_drag_drop_source()
        if imgui.begin_drag_drop_target():
            start_index = imgui.accept_drag_drop_payload('start_index')
            if start_index is not None:
                start_index = int.from_bytes(start_index, sys.byteorder)
                io = imgui.get_io()
                image_only = io.key_shift
                drawing.swap_colors(start_index, c, image_only=image_only)
                palette.clear_overlay()
            imgui.end_drag_drop_target()

    imgui.pop_style_color(1)
    imgui.pop_style_var(1)
    imgui.end_child()

    imgui.end_child()

    if imgui.is_item_hovered():
        io = imgui.get_io()
        delta = int(io.mouse_wheel)
        current_color_page = min(max(current_color_page - delta, 0), max_pages)

    palette.foreground = fg
    palette.background = bg
Exemplo n.º 20
0
    def render(self):

        videowindow, self.open = imgui.begin("Video window {}".format(
            self.filename),
                                             self.open,
                                             flags=imgui.WINDOW_NO_SCROLLBAR)

        w, h = imgui.get_window_size()

        if imgui.APPEARING:
            imgui.set_window_size(400, 300)

        w, h = imgui.core.get_content_region_available()
        w = int(max(w, 0))
        h = int(max(h - 85, 0))

        if not self.open:
            imgui.end()
            self.terminate()
            return

        if self.ctx.update() and w > 0 and h > 0:

            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo)
            gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture)

            gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, w, h, 0, gl.GL_RGB,
                            gl.GL_UNSIGNED_BYTE, None)

            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
            gl.glBindTexture(gl.GL_TEXTURE_2D, 0)

            self.ctx.render(flip_y=False,
                            opengl_fbo={
                                'w': w,
                                'h': h,
                                'fbo': self.fbo
                            })

        try:
            imgui.text("Filename: {} fbo: {} tex: {}".format(
                self.mpv.filename, self.fbo, self.texture))
        except:
            imgui.text("Filename: {} fbo: {} tex: {}".format(
                self.mpv.filename, self.fbo, self.texture))

        try:
            imgui.text("{0:.2f}s/{1:.2f}s ({2:.2f}s remaining)".format(
                self.mpv.time_pos, self.mpv.duration,
                self.mpv.playtime_remaining))
        except:
            imgui.text("Loading...")

        imgui.image(self.texture, w, h)

        imgui.push_item_width(-1)

        changed, values = imgui.slider_float("##Playback Percentage",
                                             *self.playbackPos,
                                             min_value=0.0,
                                             max_value=100.0,
                                             format="Playback Percentage %.0f",
                                             power=1.0)

        if changed and values:
            try:
                self.mpv.command('seek', values, 'absolute-percent')
            except:
                pass
            self.playbackPos = (values, )
        elif self.mpv.percent_pos:
            self.playbackPos = (self.mpv.percent_pos, )

        changed, values = imgui.slider_float("##Volume",
                                             *self.volume,
                                             min_value=0.0,
                                             max_value=100.0,
                                             format="Volume %.0f",
                                             power=1.0)

        if changed:
            self.mpv.volume = values
            self.volume = (values, )
        elif self.mpv.volume:
            self.volume = (self.mpv.volume, )

        imgui.end()
Exemplo n.º 21
0
def image_explorer_impl(im, title=""):
    # type: (ImageWithZoomInfo, str) -> None
    """
    :return: imgui.Vec2 (mouse_location_original_image) or None (if not on image)
    """

    if im.image.size == 0:
        imgui.text("empty image !")
        return imgui.Vec2(0, 0)

    zoomed_image = im.zoomed_image()

    if not im.hide_buttons:
        _display_zoom_or_pan_buttons(im)
        if title != "":
            imgui.same_line()
            imgui.text("     " + title)
    mouse_location = imgui_cv.image(zoomed_image,
                                    image_adjustments=im.image_adjustments)
    mouse_location_original_image = None
    viewport_center_original_image = im.viewport_center_original_image()

    if not im.hide_buttons and mouse_location is not None:
        mouse_drag_button = 0
        is_mouse_dragging = imgui.is_mouse_dragging(
            mouse_drag_button) and imgui.is_item_hovered()
        drag_delta = imgui.get_mouse_drag_delta(mouse_drag_button)

        mouse_location_original_image = im.zoom_info.mouse_location_original_image(
            mouse_location)

        # Handle dragging / zoom or pan
        if not is_mouse_dragging:
            im.zoom_info.last_delta = imgui.Vec2(0, 0)
        if is_mouse_dragging:
            drag_delta_delta = imgui.Vec2(
                drag_delta.x - im.zoom_info.last_delta.x,
                drag_delta.y - im.zoom_info.last_delta.y)

            if im.zoom_info.zoom_or_pan == ZoomOrPan.Zoom:
                k = 1.03
                if drag_delta.y < 0:
                    zoom_ratio = k
                else:
                    zoom_ratio = 1. / k
                im.zoom_info.affine_transform = np.dot(
                    im.zoom_info.affine_transform,
                    compute_zoom_matrix(mouse_location_original_image,
                                        zoom_ratio))

            if im.zoom_info.zoom_or_pan == ZoomOrPan.Pan:
                im.zoom_info.affine_transform = np.dot(
                    im.zoom_info.affine_transform,
                    compute_pan_matrix(drag_delta_delta,
                                       im.zoom_info.affine_transform[0, 0]))

            im.zoom_info.last_delta = drag_delta

    # Zoom & Pan buttons

    def perform_zoom(ratio):
        im.zoom_info.affine_transform = np.dot(
            im.zoom_info.affine_transform,
            compute_zoom_matrix(viewport_center_original_image, ratio))

    import functools
    perform_zoom_plus = functools.partial(perform_zoom, 1.25)
    perform_zoom_minus = functools.partial(perform_zoom, 1. / 1.25)

    def perform_scale_one():
        im.zoom_info.set_scale_one(SizePixel.from_image(im.image),
                                   im.current_viewport_size())

    def perform_full_view():
        im.zoom_info.set_full_view(SizePixel.from_image(im.image),
                                   im.current_viewport_size())

    def perform_force_viewport_size():
        im.set_force_viewport_size(True)

    def perform_reset_viewport_size():
        im.set_force_viewport_size(False)

    def perform_hide_buttons():
        im.hide_buttons = True

    def perform_show_buttons():
        im.hide_buttons = False

    def show_zoom_button(name, action, same_line=True):
        if imgui.small_button(imgui_ext.make_unique_label(name)):
            action()
        if same_line:
            imgui.same_line()

    if im.hide_buttons:
        show_zoom_button("+", perform_show_buttons, False)
        imgui.same_line()
        imgui.text(title)
    else:
        show_zoom_button("-", perform_hide_buttons)
    if not im.hide_buttons:
        show_zoom_button("zoom +", perform_zoom_plus)
        show_zoom_button("zoom -", perform_zoom_minus)
        if im.can_show_big_viewport():
            show_zoom_button("scale 1", perform_scale_one)
        if im.is_not_full_view():
            show_zoom_button("full view", perform_full_view)
        if not im.show_adjustments:
            if imgui.small_button(imgui_ext.make_unique_label("Adjust")):
                im.show_adjustments = True
        # adjustments
        if im.show_adjustments:
            imgui.new_line()
            imgui.text("Adjust:")
            imgui.same_line()
            imgui.push_item_width(80)
            # noinspection PyArgumentList
            changed, im.image_adjustments.factor = imgui.slider_float(
                imgui_ext.make_unique_label("k"),
                im.image_adjustments.factor,
                0.,
                32.,
                display_format="%.3f",
                power=5.)
            imgui.same_line()
            imgui.push_item_width(80)
            changed, im.image_adjustments.delta = imgui.slider_float(
                imgui_ext.make_unique_label("delta"),
                im.image_adjustments.delta,
                0.,
                255.,
                display_format="%.3f",
                power=5.)
            imgui.same_line()
            if not im.image_adjustments.is_none():
                if imgui.small_button(imgui_ext.make_unique_label("reset")):
                    im.image_adjustments = imgui_cv.ImageAdjustments()
            imgui.same_line()
            if imgui.small_button(imgui_ext.make_unique_label("hide adjust")):
                im.show_adjustments = False
        # Show image info
        image_type_msg = str(im.image.dtype) + str(im.image.shape)
        zoom = im.zoom_info.affine_transform[0, 0]
        import math
        if not _is_close(zoom, 1):
            zoom_msg = "Zoom:{0:.2f} ".format(zoom)
        else:
            zoom_msg = ""
        msg = zoom_msg + image_type_msg
        imgui.text(msg)

        if im.can_show_big_viewport():
            imgui.same_line()
            if im.get_force_viewport_size():
                show_zoom_button("reset viewport", perform_reset_viewport_size)
            else:
                show_zoom_button("fit viewport", perform_force_viewport_size)
            imgui.new_line()
        # Save button
        # imgui.same_line()
        imgui.push_item_width(60)
        changed, im.filename = imgui.input_text(
            imgui_ext.make_unique_label(""), im.filename, 1000)
        imgui.same_line()
        if imgui.small_button(imgui_ext.make_unique_label("save")):
            cv2.imwrite(im.filename, im.image)
        # Show pixel color info
        if mouse_location is not None:
            color = zoomed_image[int(round(mouse_location.y)),
                                 int(round(mouse_location.x))]

            mouse2 = np.array([[mouse_location.x], [mouse_location.y], [1.]])
            pt_original = np.dot(
                numpy.linalg.inv(im.zoom_info.affine_transform), mouse2)
            position_msg = "({0},{1})".format(int(round(pt_original[0, 0])),
                                              int(round(pt_original[1, 0])))
            imgui.text(position_msg + " " + color_msg(color))
        else:
            imgui.text("")

    return mouse_location_original_image
Exemplo n.º 22
0
def render():
    global selected_index, selected_file, clones_for_file, padding

    imgui.set_next_window_position(10, 10)
    imgui.set_next_window_size(280, 375)
    imgui.begin(
        "Clone Classes", False, imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE
        | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_MENU_BAR)

    if imgui.begin_menu_bar():
        if imgui.begin_menu('Sort'):
            clicked, _ = imgui.menu_item('identifier (ascending)')
            if clicked:
                clones.sort(key=lambda x: x.class_identifier)

            clicked, _ = imgui.menu_item('identifier (descending)')
            if clicked:
                clones.sort(key=lambda x: x.class_identifier, reverse=True)

            clicked, _ = imgui.menu_item('clones (ascending)')
            if clicked:
                clones.sort(key=lambda x: x.num_clones)

            clicked, _ = imgui.menu_item('clones (descending)')
            if clicked:
                clones.sort(key=lambda x: x.num_clones, reverse=True)

            clicked, _ = imgui.menu_item('files (ascending)')
            if clicked:
                clones.sort(key=lambda x: len(x.files))

            clicked, _ = imgui.menu_item('files (descending)')
            if clicked:
                clones.sort(key=lambda x: len(x.files), reverse=True)

            imgui.end_menu()

        imgui.end_menu_bar()

    for index, clone_class in enumerate(clones):

        if selected_index is clone_class.class_identifier:
            label = "--> Class {0:03d} ({1} files, {2} clones)".format(
                clone_class.class_identifier, len(clone_class.files),
                clone_class.num_clones)
        else:
            label = "Class {0:03d} ({1} files, {2} clones)".format(
                clone_class.class_identifier, len(clone_class.files),
                clone_class.num_clones)

        if imgui.button(label, width=260):
            select_clone(clone_class.class_identifier)

    imgui.end()

    imgui.set_next_window_position(10, 390)
    imgui.set_next_window_size(280, 380)
    imgui.begin(
        "Files", False, imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE
        | imgui.WINDOW_NO_COLLAPSE)

    for index, file_name in enumerate(unique_file_name):
        if selected_file is file_name:
            label = "--> {}".format(os.path.basename(file_name))
        else:
            label = "{}".format(os.path.basename(file_name))

        if imgui.button(label, width=260):
            select_file(file_name)

    imgui.end()

    imgui.set_next_window_position(300, 10)
    imgui.set_next_window_size(890, 760)
    imgui.begin(
        "Details", False, imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE
        | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_HORIZONTAL_SCROLLING_BAR
        | imgui.WINDOW_MENU_BAR)

    if selected_file is not None and clones_for_file is not None:
        if imgui.begin_menu_bar():
            if imgui.begin_menu('Actions'):
                clicked, _ = imgui.menu_item('Open in editor')

                if clicked:
                    os.system("open \"{}\"".format(selected_file))

                imgui.end_menu()

            imgui.end_menu_bar()

        file_buffer = file_buffers[selected_file]

        total_cloned_lines = 0
        for _, file in clones_for_file:
            total_cloned_lines += file.num_cloned_lines

        imgui.begin_group()
        imgui.text("Information for this file")
        imgui.bullet_text("This file contains {} lines".format(
            file_buffer.max_line))
        imgui.bullet_text("{} lines are cloned".format(total_cloned_lines))
        imgui.bullet_text("That is {0:.2f}% of the total file".format(
            total_cloned_lines / file_buffer.max_line * 100))
        imgui.end_group()

        imgui.same_line(300)

        imgui.push_item_width(200)
        imgui.begin_group()
        changed, value = imgui.slider_int("Lines of padding", padding, 0, 100)
        if changed:
            padding = value
        imgui.end_group()
        imgui.pop_item_width()

        imgui.spacing()
        imgui.spacing()
        imgui.spacing()
        imgui.spacing()

        for class_identifier, file in clones_for_file:
            expanded, visible = imgui.collapsing_header(
                "Clone class {0:03d}".format(class_identifier), None,
                imgui.TREE_NODE_DEFAULT_OPEN)

            if expanded:
                if imgui.button(
                        "View all files for clone class {0:03d}".format(
                            class_identifier)):
                    select_clone(class_identifier)

                file_buffers[file.file_name].to_imgui(file, padding)

    if selected_index is not None:
        imgui.push_item_width(200)
        imgui.begin_group()
        changed, value = imgui.slider_int("Lines of padding", padding, 0, 100)
        if changed:
            padding = value
        imgui.end_group()
        imgui.pop_item_width()

        clone_class = None

        for clone in clones:
            if clone.class_identifier is selected_index:
                clone_class = clone

        for i, file in enumerate(clone_class.files):
            expanded, visible = imgui.collapsing_header(
                file.file_name, None, imgui.TREE_NODE_DEFAULT_OPEN)

            if expanded:
                if imgui.button("View all clones for \"{}\"".format(
                        file.file_name)):
                    select_file(file.file_name)

                file_buffers[file.file_name].to_imgui(file, padding)

    imgui.end()
Exemplo n.º 23
0
 def _show(self, value, read_only):
     imgui.push_item_width(self.width)
     changed, v = imgui.combo("", value.value, self.choices)
     if changed and not read_only:
         value.value = v
Exemplo n.º 24
0
def ParsePdfWidget():
    '''
    Use subprocess.Popen to run another script in background
    '''
    global WDIR
    global ODIR
    global N_Group
    global AllFileStatus

    with imgui.font(largefont):
        imgui.text("Step 1: 設定工作目錄")
    imgui.bullet_text("設定好推甄資料的目錄。")
    if WDIR:
        imgui.separator()
        with imgui.font(largefont):
            imgui.text("Step 2: 檢查各別檔案")
        imgui.push_text_wrap_position(450)
        imgui.bullet_text("檔案命名有些錯誤,需要額外調整,如: 10054818.pdf 變為10054818_1.pdf")
        imgui.dummy(50, 0)
        imgui.same_line()
        if imgui.button("檢查檔案"):
            AllFileStatus = GF.CheckAllFiles(WDIR)
        imgui.push_text_wrap_position(450)
        imgui.text(AllFileStatus)
        imgui.separator()
        with imgui.font(largefont):
            imgui.text("Step 3: 執行程式-解析成績單內容")    
        imgui.dummy(50, 0)
        imgui.same_line()
        if imgui.button("設定輸出目錄"):
            ODIR = TkFileDialog()    
        if ODIR != "":
            imgui.text("輸出目錄位置:")
            imgui.push_text_wrap_position(250)
            imgui.text(ODIR)
            imgui.dummy(50, 0)
            imgui.same_line()
            if imgui.button("開始解析"):
                if WDIR == "":
                    imgui.text("請設定檔案目錄")
                else:
                    subprocess.run(["python","Subprocesses/ParseScoreSheet.py", WDIR, ODIR])                        
        imgui.separator()
    if os.path.isfile('ManualFiles.log'):
        with imgui.font(largefont):
            imgui.text("Step 4: 執行程式-手動檔案分類")
        imgui.push_item_width(150)
        changed, N_Group = imgui.slider_int("幾群?", N_Group, min_value = 2, max_value = 20)
        imgui.text(f"分成{N_Group}群")        
        if imgui.button("開始分群"):
            subprocess.run(["python","Subprocesses/GroupPdf.py", ODIR, str(N_Group)])
        imgui.separator()
    if os.path.isdir(ODIR+"/Manual"):
        with imgui.font(largefont):
            imgui.text("Step 5: 手動處理")
            imgui.push_text_wrap_position(250)
            imgui.text("""
            恭喜~~~
            只剩下一咪咪手動的作業就能完工了!!

            祝你有美好的一天!!
            你現在可以關閉這個程式。
            """)
Exemplo n.º 25
0
 def _show(self, value, read_only):
     imgui.push_item_width(self.width)
     changed, v = imgui.input_int("", value.value)
     if changed and not read_only:
         value.value = int(self.clamper(v))
Exemplo n.º 26
0
def main():
    global width_library
    global width_shematic
    global width_context
    global height_window

    global previous_key_callback
    global selected_link
    global selected_node
    global iggraph
    global node_library
    global debug_is_mouse_dragging
    
    global show_debug_window

    # states -------------------------
    
    scrolling = imgui.Vec2(0, 0)

    iggraph = IGGraph(node_library)

    # iggraph.reset()

    node_hovered_in_scene = -1
    parameter_link_start = None
    selected_parameter = None

    io_hovered = None 
    io_anchors_width_not_hovered = 10
    io_anchors_width_hovered = 15 
    right_splitter_is_active = False
    left_splitter_is_active = False
    
    image_width = 0
    image_height = 0
    image_texture = None

    # states -------------------------

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    io = imgui.get_io()
    previous_key_callback = glfw.set_key_callback(window,key_event)
    init_textures()

    assign_parameter_colors(node_library)

    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_new, selected_new = imgui.menu_item(
                    "New", 'Cmd+N', False, True
                )
                if clicked_new:
                    iggraph = IGGraph(node_library)
                clicked_load, selected_load = imgui.menu_item(
                    "Load", 'Cmd+L', False, True
                )
                if clicked_load:
                    root = tk.Tk()
                    root.withdraw()
                    filename = filedialog.askopenfilename()
                    if filename :
                        f=open(filename)
                        iggraph.from_json(json.load(f))
                        f.close()
                clicked_save, selected_save = imgui.menu_item(
                    "Save", 'Cmd+S', False, True
                )
                if clicked_save:
                    iggraph.reset()
                    graph_json = iggraph.to_json()
                    text2save = json.dumps(graph_json, indent=4, sort_keys=True)
                    root = tk.Tk()
                    root.withdraw()
                    f = filedialog.asksaveasfile(mode='w', defaultextension=".json")
                    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
                        return
                    f.write(text2save)
                    f.close()
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            if imgui.begin_menu("Debug", True):
                show_debug_window_clicked,  show_debug_window_selected = imgui.menu_item(
                    "Show Debug window", 'Cmd+D', show_debug_window, True
                )
                if show_debug_window_clicked:
                    show_debug_window = not show_debug_window
                catch_exceptions_clicked,  catch_exceptions_selected = imgui.menu_item(
                    "Catch Exceptions", '', iggraph.catch_exceptions, True
                )
                if catch_exceptions_clicked:
                    iggraph.catch_exceptions = not iggraph.catch_exceptions
                imgui.separator()
                imgui.menu_item(
                    "Examples", '', False, False
                )
                show_example_mosaic_clicked,  show_example_mosaic_selected = imgui.menu_item(
                    "Mosaic", '', False, True
                )
                if show_example_mosaic_clicked:
                    example_mosaic(iggraph)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        height_window = io.display_size.y - 18  # imgui.get_cursor_pos_y()

        imgui.push_style_var(imgui.STYLE_ITEM_SPACING, imgui.Vec2(0,0))
        imgui.set_next_window_size(io.display_size.x, height_window)
        imgui.set_next_window_position(0, 18)
        imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0)
        imgui.begin("Splitter test", False, imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS)
        imgui.pop_style_var()
        imgui.pop_style_var()

        width_shematic = io.display_size.x - separator_width  - width_context - separator_width - width_library

        # ==============================================================================
        # Library
        # ==============================================================================

        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("Library", width_library, 0, True)
        for node_name in node_library.nodes:
            if imgui.button(node_name, width_library):
                iggraph.create_node(node_name)
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("left_splitter", separator_width, height_window - 20)
        left_splitter_is_active = imgui.is_item_active()
        if (left_splitter_is_active):
            width_library += io.mouse_delta.x
            scrolling = imgui.Vec2(scrolling.x - io.mouse_delta.x, scrolling.y)
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)
        
        imgui.same_line()

        # ==============================================================================
        # Shematic
        # ==============================================================================
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("shematic", width_shematic, 0, True)

        if show_inputs_popup(iggraph):
            imgui.open_popup("Outputs")
        show_outputs_popup(iggraph)

        # create our child canvas
        if iggraph.get_state() == iggraph.STATE_IDLE:
            imgui.text("status: edit | ")
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            imgui.text("status: run  | ")
        imgui.same_line()
        if iggraph.get_state() == iggraph.STATE_IDLE:
            if imgui.button("run"):
                #TODO if not running
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                imgui.open_popup("User Input")
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                iggraph.run_one_step()
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            if imgui.button("stop running"):
                iggraph.reset()
                iggraph.set_state(iggraph.STATE_IDLE)
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.run_one_step()
        # imgui.same_line(imgui.get_window_width() - 100)
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, imgui.Vec2(1, 1))
        imgui.push_style_var(imgui.STYLE_WINDOW_PADDING, imgui.Vec2(0, 0))
        imgui.begin_child("scrolling_region", 0, 0, True, imgui.WINDOW_NO_SCROLLBAR | imgui.WINDOW_NO_MOVE)
        imgui.pop_style_var()
        imgui.pop_style_var()
        imgui.push_item_width(120.0)

        offset = add(imgui.get_cursor_screen_pos(), scrolling)
        draw_list = imgui.get_window_draw_list()

        # Display links
        draw_list.channels_split(2)
        draw_list.channels_set_current(0)
        for link in iggraph.links:
            draw_link_param_to_param(draw_list, offset, link.output_parameter, link.input_parameter, selected_link == link)

        # Display nodes
        parameter_link_end = None
        one_parameter_hovered = False
        one_node_moving_active = False
        for node in iggraph.nodes:
            imgui.push_id(str(node.id))
            node_rect_min = add(offset, node.pos)
            draw_list.channels_set_current(1) # foreground
            old_any_active = imgui.is_any_item_active()

            #display node content first
            # todo
            test = add(node_rect_min, NODE_WINDOW_PADDING)
            imgui.set_cursor_screen_position(add(node_rect_min, NODE_WINDOW_PADDING))
            imgui.begin_group()
            imgui.text("")
            imgui.text(node.name)
            imgui.text("")
            imgui.end_group()

            # save size
            node_widgets_active = False # (not old_any_active and imgui.is_any_item_active())
            node.size = add( add( imgui.get_item_rect_size(), NODE_WINDOW_PADDING) , NODE_WINDOW_PADDING)
            node_rect_max = add(node.size, node_rect_min) 
            
            #display node box
            draw_list.channels_set_current(0) # background
            imgui.set_cursor_screen_position(node_rect_min)
            imgui.invisible_button(str(node.id), node.size.x, node.size.y)
            if imgui.is_item_hovered():
                node_hovered_in_scene = node.id
            else:
                node_hovered_in_scene = None
            node_moving_active = imgui.is_item_active()
            use_hovered_color = node_hovered_in_scene or selected_node == node
            draw_list.add_rect_filled(node_rect_min.x, node_rect_min.y, node_rect_max.x, node_rect_max.y, get_node_color(node, iggraph, use_hovered_color), 5)
            if node_hovered_in_scene and iggraph.is_error(node):
                imgui.begin_tooltip()
                imgui.text(iggraph.error_nodes[node])
                imgui.end_tooltip()

            # input parameters
            for parameter_name in node.inputs:
                parameter = node.inputs[parameter_name]
                center = node.get_intput_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "input" + parameter.id))
                if (imgui.invisible_button("input", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                # imgui.is_item_hovered() does not work when dragging
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                               (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                if is_hovering and imgui.is_mouse_released(0):
                    parameter_link_end = parameter
                imgui.pop_id()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))

            # output parameters
            for parameter_name in node.outputs:
                parameter = node.outputs[parameter_name]
                center = node.get_output_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "output" + parameter.id))
                if (imgui.invisible_button("output", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                    (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))
                imgui.pop_id()
                # cannot use imgui.is_item_active, seems buggy with the scroll
                if is_hovering and imgui.is_mouse_down(0):
                    parameter_link_start = parameter

            if node_widgets_active or node_moving_active:
                selected_node = node
                one_node_moving_active = True
            if node_moving_active and imgui.is_mouse_dragging(0) and node.id==selected_node.id:
               node.pos = add(node.pos, io.mouse_delta)

            debug_is_mouse_dragging = imgui.is_mouse_dragging(0)

            imgui.pop_id()
        draw_list.channels_merge()
        if not one_parameter_hovered:
            io_hovered = None

        # scrolling
        mouse_is_in_schematic = (io.mouse_pos.x > width_library) and\
                                (io.mouse_pos.x < (width_library + width_shematic)) and\
                                (io.mouse_pos.y < height_window) and\
                                (io.mouse_pos.y > 18)
        if not one_node_moving_active and\
           not parameter_link_start and\
           imgui.is_mouse_dragging(0) and\
           mouse_is_in_schematic and\
           not left_splitter_is_active and\
           not right_splitter_is_active and\
           imgui.is_window_focused():
            scroll_offset = imgui.Vec2(io.mouse_delta.x, io.mouse_delta.y)
            scrolling = add(scrolling, scroll_offset)
        # link creation
        if parameter_link_start and parameter_link_end:
            iggraph.add_link(parameter_link_start, parameter_link_end)
        # creating link
        elif parameter_link_start and imgui.is_mouse_dragging(0):
            draw_link_param_to_point(draw_list, offset, parameter_link_start, io.mouse_pos.x, io.mouse_pos.y, True)
        # mouse release
        if imgui.is_mouse_released(0):
            parameter_link_start = None

        imgui.pop_item_width()
        imgui.end_child()

        # mouse click on the scene
        if imgui.is_mouse_clicked(0):
            mouse_pos = imgui.get_mouse_pos()
            local_mouse_pos = imgui.Vec2(mouse_pos.x - offset.x, mouse_pos.y - offset.y)
            selected_link = None
            for link in iggraph.links:
                start_node = link.output_parameter.owner
                start_pos = start_node.get_output_slot_pos(link.output_parameter)
                end_node = link.input_parameter.owner
                end_pos = end_node.get_intput_slot_pos(link.input_parameter)
                distance_mouse_start = math.sqrt(((local_mouse_pos.x-start_pos.x)**2) + ((local_mouse_pos.y-start_pos.y)**2))
                distance_mouse_end = math.sqrt(((local_mouse_pos.x-end_pos.x)**2) + ((local_mouse_pos.y-end_pos.y)**2))
                distance_start_end = math.sqrt(((start_pos.x-end_pos.x)**2) + ((start_pos.y-end_pos.y)**2))
                if ((distance_mouse_start + distance_mouse_end) - distance_start_end) < 0.1:
                    selected_link = link
                
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("right_splitter", separator_width, height_window - 20)
        right_splitter_is_active = imgui.is_item_active()
        if (right_splitter_is_active):
            width_context -= io.mouse_delta.x
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)

        # ==============================================================================
        # Context
        # ==============================================================================

        imgui.same_line()
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("child3", width_context, 0, True);
        if selected_node:
            if selected_node.handle_dynamic_parameters():
                if imgui.button("add parameter"):
                    selected_node.add_dynamic_parameter()
            if imgui.tree_node("Inputs"):
                for parameter_name in selected_node.inputs:
                    parameter = selected_node.inputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, True)
                        imgui.tree_pop()
                imgui.tree_pop()
            if imgui.tree_node("Output"):
                for parameter_name in selected_node.outputs:
                    parameter = selected_node.outputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, False)
                        imgui.tree_pop()
                imgui.tree_pop()
        imgui.end_child()
        imgui.pop_style_var()

        # 
        imgui.end()

        # ==============================================================================
        # Debug Window
        # ==============================================================================
        if show_debug_window:
            debug_window_expanded, show_debug_window = imgui.begin("Debug", True)
            if parameter_link_start:
                imgui.text("parameter_link_start: " + parameter_link_start.id)
            else:
                imgui.text("parameter_link_start: " + "None")
            if selected_parameter:
                imgui.text("selected_parameter: " + selected_parameter.id)
            else:
                imgui.text("selected_parameter: " + "None")
            imgui.text("is_mouse_dragging: " + str(debug_is_mouse_dragging))
            imgui.text("mouse: (" + str(io.mouse_pos.x) + ", " + str(io.mouse_pos.y) + ")")
            imgui.end()

        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()
    def run(self):
        # Loop until the user closes the window
        while not glfw.window_should_close(self.window):
            # Poll for and process events
            glfw.poll_events()

            # build gui.
            self.impl.process_inputs()

            w, h = glfw.get_window_size(self.window)
            glViewport(0, 0, w, h)

            imgui.new_frame()

            timeline_height = 35
            imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0)
            imgui.push_style_var(imgui.STYLE_FRAME_ROUNDING, 0)

            imgui.set_next_window_position(0, h - timeline_height - 10)
            imgui.set_next_window_size(w, timeline_height)

            imgui.begin(
                "Timeline", False, imgui.WINDOW_NO_TITLE_BAR
                | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_SCROLLBAR)
            imgui.columns(1)
            imgui.same_line(0, 0)
            imgui.push_item_width(-50)
            changed, value = imgui.slider_int("", self.sliderValue, 0,
                                              self.num_scans - 1)
            if changed: self.sliderValue = value
            if self.sliderValue != self.currentTimestep:
                self.currentTimestep = self.sliderValue

            imgui.push_style_var(imgui.STYLE_FRAME_ROUNDING, 3)

            play_delay = 1
            refresh_rate = 0.05

            current_time = time.time()

            imgui.same_line(spacing=5)
            changed = imgui.button("<", 20)
            if self.currentTimestep > 0:
                # just a click
                if changed:
                    self.currentTimestep = self.sliderValue = self.currentTimestep - 1
                    self.lastUpdate = current_time

                # button pressed.
                if imgui.is_item_active() and not self.button_backward_hold:
                    self.hold_start = current_time
                    self.button_backward_hold = True

                if not imgui.is_item_active() and self.button_backward_hold:
                    self.button_backward_hold = False

                # start playback when button pressed long enough
                if self.button_backward_hold and (
                    (current_time - self.hold_start) > play_delay):
                    if (current_time - self.lastUpdate) > refresh_rate:
                        self.currentTimestep = self.sliderValue = self.currentTimestep - 1
                        self.lastUpdate = current_time

            imgui.same_line(spacing=2)
            changed = imgui.button(">", 20)

            if self.currentTimestep < self.num_scans - 1:
                # just a click
                if changed:
                    self.currentTimestep = self.sliderValue = self.currentTimestep + 1
                    self.lastUpdate = current_time

                # button pressed.
                if imgui.is_item_active() and not self.button_forward_hold:
                    self.hold_start = current_time
                    self.button_forward_hold = True

                if not imgui.is_item_active() and self.button_forward_hold:
                    self.button_forward_hold = False

                # start playback when button pressed long enough
                if self.button_forward_hold and (
                    (current_time - self.hold_start) > play_delay):
                    if (current_time - self.lastUpdate) > refresh_rate:
                        self.currentTimestep = self.sliderValue = self.currentTimestep + 1
                        self.lastUpdate = current_time

            imgui.pop_style_var(3)
            imgui.end()

            imgui.set_next_window_position(20, 20, imgui.FIRST_USE_EVER)
            imgui.set_next_window_size(200, 150, imgui.FIRST_USE_EVER)
            imgui.begin("Show Data")

            if len(self.subdirs) > 1:
                for i, subdir in enumerate(self.subdirs):
                    changed, value = imgui.checkbox(subdir,
                                                    self.current_subdir == i)
                    if i < len(self.subdirs) - 1: imgui.same_line()
                    if changed and value: self.current_subdir = i

            subdir = self.subdirs[self.current_subdir]

            data_available = "input" in self.availableData[subdir]
            if data_available:
                imgui.push_style_var(imgui.STYLE_ALPHA, 1.0)
            else:
                imgui.push_style_var(imgui.STYLE_ALPHA, 0.3)

            changed, value = imgui.checkbox("input", self.showInput)
            if changed and value and data_available:
                self.showInput = True
                self.showLabels = False

            imgui.pop_style_var()

            data_available = "labels" in self.availableData[subdir]
            if data_available:
                imgui.push_style_var(imgui.STYLE_ALPHA, 1.0)
            else:
                imgui.push_style_var(imgui.STYLE_ALPHA, 0.3)

            changed, value = imgui.checkbox("labels", self.showLabels)
            if changed and value and data_available:
                self.showInput = False
                self.showLabels = True

            imgui.pop_style_var()

            data_available = "invalid" in self.availableData[subdir]
            if data_available:
                imgui.push_style_var(imgui.STYLE_ALPHA, 1.0)
            else:
                imgui.push_style_var(imgui.STYLE_ALPHA, 0.3)

            changed, value = imgui.checkbox("invalid", self.showInvalid)
            if changed and data_available: self.showInvalid = value

            imgui.pop_style_var()

            data_available = "occluded" in self.availableData[subdir]
            if data_available:
                imgui.push_style_var(imgui.STYLE_ALPHA, 1.0)
            else:
                imgui.push_style_var(imgui.STYLE_ALPHA, 0.3)

            changed, value = imgui.checkbox("occluded", self.showOccluded)
            if changed and data_available: self.showOccluded = value

            imgui.pop_style_var()

            imgui.end()

            # imgui.show_demo_window()

            showData = []
            if self.showInput: showData.append("input")
            if self.showOccluded: showData.append("occluded")
            if self.showInvalid: showData.append("invalid")

            mvp = self.projection_ @ self.cam.matrix @ self.conversion_

            glClearColor(1.0, 1.0, 1.0, 1.0)

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            glBindVertexArray(self.vao)

            self.program.bind()
            self.program["mvp"] = mvp.transpose()
            self.program["view_mat"] = (
                self.cam.matrix @ self.conversion_).transpose()
            self.program["lightPos"] = glow.vec3(10, 10, 10)
            self.program["voxel_scale"] = 0.8
            self.program["voxel_alpha"] = 1.0
            self.program["use_label_colors"] = True

            self.label_colors.bind(0)

            if self.showLabels:
                self.setCurrentBufferData("labels", self.currentTimestep)
                glDrawArraysInstanced(GL_TRIANGLES, 0, 36, self.num_instances)

            self.program["use_label_colors"] = False
            self.program["voxel_color"] = glow.vec3(0.3, 0.3, 0.3)

            self.program["voxel_alpha"] = 0.5

            for data_name in showData:
                self.program["voxel_scale"] = 0.5
                if data_name == "input": self.program["voxel_scale"] = 0.8

                self.setCurrentBufferData(data_name, self.currentTimestep)
                glDrawArraysInstanced(GL_TRIANGLES, 0, 36, self.num_instances)

            self.program.release()
            self.label_colors.release(0)

            glBindVertexArray(self.vao_no_points)

            self.prgDrawPose.bind()
            self.prgDrawPose["mvp"] = mvp.transpose()
            self.prgDrawPose["pose"] = np.identity(4, dtype=np.float32)
            self.prgDrawPose["size"] = 1.0

            glDrawArrays(GL_POINTS, 0, 1)
            self.prgDrawPose.release()

            glBindVertexArray(0)

            # draw gui ontop.
            imgui.render()
            self.impl.render(imgui.get_draw_data())

            # Swap front and back buffers
            glfw.swap_buffers(self.window)
Exemplo n.º 28
0
    def render(self):
        if self.task_statuses:  # Prepare the progress bar
            n_working_or_finished = sum([
                status in ["Working...", "Done."]
                for status in self.task_statuses
            ])
            n_total_threads = len(self.task_statuses)
            progress = n_working_or_finished / n_total_threads
            progress_text = f"{n_working_or_finished}/{n_total_threads}"
            progress_bar = self.progress_bar_widget(progress_text, progress)
        else:
            progress_bar = c.nothing()

        # use `multi_orr`, so that concurrent events aren't thrown away
        events = yield from c.window(
            self.name,
            c.multi_orr([
                c.text_tooltip(
                    "Drag the slider or enter your preferred amount directly to adjust the amount of threads used.",
                    c.text("Number of Threads")),
                c.slider_int(label="",
                             value=self.n_threads,
                             min_value=1,
                             max_value=100,
                             tag='threads'),
                c.same_line(),
                c.lift(lambda: imgui.push_item_width(
                    self.evaluate_field_size(self.n_threads, self.n_tasks))),
                c.interactive_elem(imgui.input_int,
                                   "",
                                   self.n_threads,
                                   tag="threads"),
                c.lift(lambda: imgui.pop_item_width()),
                c.slider_int(label="",
                             value=self.n_tasks,
                             min_value=1,
                             max_value=100,
                             tag='tasks'),
                c.same_line(),
                c.lift(lambda: imgui.push_item_width(
                    self.evaluate_field_size(self.n_threads, self.n_tasks))),
                c.interactive_elem(imgui.input_int,
                                   "",
                                   self.n_tasks,
                                   tag="threads"),
                c.lift(lambda: imgui.pop_item_width()),
                c.input_text(name="Information, the feature needs",
                             value=self.information,
                             tag="info"),
                c.button("Terminate", tag='terminate')
                if self.process else self.dynamic_popup_button(
                    "Start", "Feature information is missing. Continue anyway?"
                    if not self.information else self.evaluate_popup_behaviour(
                        {'information': True})),
                c.separator(),
                c.text_colored("Feature status:", 'yellow'),
                c.text(f"{self.window_status}"),
                progress_bar,
                c.optional(bool(self.task_statuses),
                           self.generate_thread_table),
                c.separator(),
                c.text_colored(f"{self.name} Log:", 'orange'),

                # c.child(name=f"{self.name} Log", widget=self.log_widget(self.log), width=-1, height=-1, border=True),
                c.window("Log", self.log_widget(self.log)),
                c.tag(tag_name="status_queue",
                      elem=c.listen(self.status_queue)),
                c.tag("log_queue", c.listen(self.log_queue)),
            ]))

        for tag, value in events:  # This is how event handling works with `multi_orr`

            if tag == "info":
                self.information = value

            elif tag == "Start":
                assert self.process is None
                self.status_queue = Queue()
                self.task_statuses = ["Waiting"] * self.n_tasks
                information_dict = {
                    'log_queue': self.log_queue,
                    'information': self.information
                }
                self.process = Process(target=self.threadify,
                                       args=(
                                           NiceFeature,
                                           information_dict,
                                       ))
                self.process.start()

            elif tag == "terminate":
                assert self.process is not None
                self.process.terminate()
                self.window_status = "Terminated."
                self.process = None

                for i, status in enumerate(self.task_statuses, 0):
                    if status in ["Waiting", "Working..."]:
                        self.task_statuses[i] = "Terminated."

            elif tag == "status_queue":  # Handle events fired by threads.
                # Update the thread state table
                thread_id, new_status = value
                # Update the feature status
                if thread_id < 0:
                    self.window_status = new_status
                    if new_status == "Work done.":
                        self.process = None
                else:
                    self.task_statuses[thread_id] = new_status

            elif tag == "log_queue":
                msg = value.getMessage()

                # Colored logging
                try:
                    text, color = msg.split("|")
                except:
                    text, color = msg, "white"

                if color == "green":
                    rgb_tuple = (0, 255, 0)
                elif color == "red":
                    rgb_tuple = (255, 0, 0)
                else:
                    rgb_tuple = (255, 255, 255)

                self.log_list.append((text, rgb_tuple))

            elif tag == "tasks":
                self.n_tasks = value

            elif tag == "threads":
                self.n_threads = value

        return self
Exemplo n.º 29
0
    def render_ui(self):
        imgui.new_frame()
        if imgui.begin("Settings"):
            imgui.push_item_width(imgui.get_window_width() * 0.33)
            changed = False
            c, SlimeConfig.move_speed = imgui.slider_float(
                "Movement speed", SlimeConfig.move_speed, 0.5, 50
            )
            changed = changed or c
            c, SlimeConfig.turn_speed = imgui.slider_float(
                "Turn speed",
                SlimeConfig.turn_speed,
                0.5,
                50,
            )
            changed = changed or c
            c, SlimeConfig.evaporation_speed = imgui.slider_float(
                "Evaporation speed", SlimeConfig.evaporation_speed, 0.1, 10
            )
            changed = changed or c
            c, SlimeConfig.diffusion_speed = imgui.slider_float(
                "Diffusion speed",
                SlimeConfig.diffusion_speed,
                0.1,
                10,
            )
            changed = changed or c
            c, SlimeConfig.sensor_angle = imgui.slider_float(
                "Sensor-angle",
                SlimeConfig.sensor_angle,
                0,
                np.pi,
            )
            changed = changed or c
            c, SlimeConfig.sensor_size = imgui.slider_int(
                "Sensor-size",
                SlimeConfig.sensor_size,
                1,
                3,
            )
            changed = changed or c
            c, SlimeConfig.sensor_distance = imgui.slider_int(
                "Sensor distance",
                SlimeConfig.sensor_distance,
                1,
                10,
            )
            changed = changed or c
            if changed:
                self.update_uniforms()
            imgui.pop_item_width()

        imgui.end()

        if imgui.begin("Appearance"):
            imgui.push_item_width(imgui.get_window_width() * 0.33)
            changed_c1, SlimeConfig.color1 = imgui.color_edit3(
                "Color1", *SlimeConfig.color1
            )
            changed_c2, SlimeConfig.color2 = imgui.color_edit3(
                "Color2", *SlimeConfig.color2
            )
            if changed_c1 or changed_c2:
                self.update_uniforms()

        imgui.end()

        if imgui.begin("Actions"):
            imgui.push_item_width(imgui.get_window_width() * 0.33)
            changed, SlimeConfig.N = imgui.input_int(
                "Number of Slimes", SlimeConfig.N, step=1024, step_fast=2**15
            )
            SlimeConfig.N = min(max(2048, SlimeConfig.N), 2**24)
            if imgui.button("Restart Slimes"):
                self.restart_sim()

            imgui.pop_item_width()

        imgui.end()
        imgui.render()
        self.imgui.render(imgui.get_draw_data())
Exemplo n.º 30
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)