Example #1
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
Example #2
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()
Example #3
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])
Example #4
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")
Example #5
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())
Example #6
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()
Example #7
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()
    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