Esempio n. 1
0
    def dynamic_popup_button(self, label, error, tag=None):
        """ Validating button.
		Behaves in the same way as a regular `concur.widgets.button` when `error` is None.
		When `error` is a string, it displays an error popup instead of emitting an event.
		"""
        while True:
            if imgui.button(label):
                if error is not None:
                    imgui.open_popup("Error Popup")
                else:
                    return tag if tag is not None else label, None

            if imgui.begin_popup("Error Popup"):
                imgui.text(error)
                if self.is_continuable:
                    if imgui.button("Continue anyway"):
                        imgui.close_current_popup()
                        imgui.end_popup()
                        return tag if tag is not None else label, None
                    imgui.same_line()
                    if imgui.button("Cancel"):
                        imgui.close_current_popup()
                    imgui.end_popup()
                else:
                    if imgui.button("OK"):
                        imgui.close_current_popup()
                    imgui.end_popup()
            yield
Esempio n. 2
0
    def _draw_component(self, entity, component_name, component_name_display):
        if not entity.has_component(component_name):
            return
        treeNodeFlags = imgui.TREE_NODE_DEFAULT_OPEN | imgui.TREE_NODE_FRAMED | imgui.TREE_NODE_ALLOW_ITEM_OVERLAP | imgui.TREE_NODE_FRAME_PADDING
        component = entity.get_component(component_name)
        # contentRegionAvailable = imgui.get_content_region_available()
        # lineHeight =
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, (4, 4))
        imgui.separator()
        open = imgui.tree_node(component_name_display, treeNodeFlags)
        imgui.pop_style_var()
        # TODO imgui.same_line(contentRegionAvailable.x - lin)
        imgui.same_line()
        if imgui.button("+"):
            imgui.open_popup("ComponentSettings")
        removeComponent = False
        if imgui.begin_popup("ComponentSettings"):
            if menu_item_clicked("Remove component"):
                removeComponent = True
            imgui.end_popup()
        if open:
            getattr(self, "_draw_component_%s" % component_name)(component)
            imgui.tree_pop()

        if removeComponent:
            entity.remove_component(component_name)
Esempio n. 3
0
def render_new_drawing_popup(window):

    "Settings for creating a new drawing."

    if window._new_drawing:
        imgui.open_popup("New drawing")
        w, h = window.get_size()
        imgui.set_next_window_size(200, 120)
        imgui.set_next_window_position(w // 2 - 100, h // 2 - 60)

    if imgui.begin_popup_modal("New drawing")[0]:
        imgui.text("Creating a new drawing.")
        imgui.separator()
        changed, new_size = imgui.drag_int3("Shape",
                                            *window._new_drawing["shape"],
                                            min_value=1,
                                            max_value=2048)
        if changed:
            window._new_drawing["shape"] = new_size
        if imgui.button("OK"):
            window.really_create_drawing()
            imgui.close_current_popup()
        imgui.same_line()
        if imgui.button("Cancel"):
            window._new_drawing = None
            imgui.close_current_popup()
        imgui.end_popup()
Esempio n. 4
0
    def _show_custom_context(self):
        if imgui.button("paste url"):
            shader_id = clipboard.paste().strip()
            if shader_id.startswith("http://glslsandbox.com/e#"):
                shader_id = shader_id.replace("http://glslsandbox.com/e#", "")
            self.get_input("id").value = shader_id

        imgui.same_line()
        if imgui.button("copy url"):
            shader_id = self.get("id")
            url = "http://glslsandbox.com/e#%s" % shader_id
            clipboard.copy(url)

        imgui.same_line()
        if imgui.button("save fragment"):
            imgui.open_popup("save_fragment")
        base_path = os.path.join(assets.SHADER_PATH, "generate")
        save_path = node_widget.imgui_pick_file("save_fragment", base_path)
        if save_path is not None:
            self._export_fragment(save_path)

        imgui.same_line()
        if imgui.button("reference as file"):
            imgui.open_popup("reference_fragment")
        reference_path = node_widget.imgui_pick_file("reference_fragment",
                                                     base_path)
        if reference_path is not None:
            self._export_fragment(reference_path)
            self._reference_file_watcher = assets.FileWatcher(reference_path)
Esempio n. 5
0
    def draw(self):
        imgui.new_frame()

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

        imgui.begin("Example: simple popup modal")

        if imgui.button("Open Modal popup"):
            imgui.open_popup("select-popup")

        imgui.same_line()

        if imgui.begin_popup_modal("select-popup")[0]:
            imgui.text("Select an option:")
            imgui.separator()
            imgui.selectable("One")
            imgui.selectable("Two")
            imgui.selectable("Three")
            imgui.end_popup()

        imgui.end()

        imgui.end_frame()

        imgui.render()

        self.renderer.render(imgui.get_draw_data())
Esempio n. 6
0
def render_unsaved_close_drawing(window):

    "Popup to prevent accidentally closing a drawing with unsaved work."

    drawing = window.close_unsaved_drawing

    if drawing and drawing.unsaved:
        imgui.open_popup("Really close?")

    if imgui.begin_popup_modal("Really close?",
                               flags=imgui.WINDOW_NO_RESIZE)[0]:
        imgui.text("The drawing contains unsaved work.")
        if imgui.button("Yes, close anyway"):
            window.drawings.remove(drawing)
            window.close_unsaved_drawing = None
            imgui.close_current_popup()
        imgui.same_line()
        if imgui.button("Yes, but save first"):
            window.save_drawing(drawing)
            window.drawings.remove(drawing)
            window.close_unsaved_drawing = None
            imgui.close_current_popup()
        imgui.same_line()
        if imgui.button("No, cancel"):
            window.close_unsaved_drawing = None
            imgui.close_current_popup()
        imgui.end_popup()
Esempio n. 7
0
def render_unsaved_exit(window):

    "Popup to prevent exiting the application with unsaved work."

    if window.exit_unsaved_drawings:
        imgui.open_popup("Really exit?")

    imgui.set_next_window_size(500, 200)
    if imgui.begin_popup_modal("Really exit?")[0]:
        imgui.text("You have unsaved work in these drawing(s):")

        imgui.begin_child("unsaved",
                          border=True,
                          height=imgui.get_content_region_available()[1] - 26)
        for drawing in window.exit_unsaved_drawings:
            imgui.text(drawing.filename)
            if imgui.is_item_hovered():
                pass  # TODO popup thumbnail of the picture?
        imgui.end_child()

        if imgui.button("Yes, exit anyway"):
            imgui.close_current_popup()
            pyglet.app.exit()
        imgui.same_line()
        if imgui.button("Yes, but save first"):
            for drawing in window.exit_unsaved_drawings:
                window.save_drawing(drawing)
            pyglet.app.exit()
        imgui.same_line()
        if imgui.button("No, cancel"):
            window.exit_unsaved_drawings = None
            imgui.close_current_popup()
        imgui.end_popup()
Esempio n. 8
0
    def _render_gui(self):
        w, h = self.get_size()

        imgui.new_frame()

        if self.stroke_tool and self.stroke_tool.show_rect:
            if self.stroke_tool.rect:
                rect = self.stroke_tool.rect
                p0 = self._to_window_coords(*rect.topleft)
                p1 = self._to_window_coords(*rect.bottomright)
                ui.render_selection_rectangle(self, p0, p1)

        with imgui.font(self._font):

            ui.render_menu(self)

            if self.drawing:

                imgui.set_next_window_size(115, h - 20)
                imgui.set_next_window_position(w - 115, 20)

                imgui.begin("Sidebar",
                            False,
                            flags=(imgui.WINDOW_NO_TITLE_BAR
                                   | imgui.WINDOW_NO_RESIZE
                                   | imgui.WINDOW_NO_MOVE))

                ui.render_tools(self.tools, self.icons)
                imgui.separator()

                ui.render_palette(self.drawing)
                imgui.separator()

                ui.render_layers(self.view)

                imgui.end()

                ui.render_unsaved_exit(self)
                ui.render_unsaved_close_drawing(self)

                render_plugins_ui(self.drawing)

            ui.render_new_drawing_popup(self)

            if self._error:
                imgui.open_popup("Error")
                if imgui.begin_popup_modal("Error")[0]:
                    imgui.text(self._error)
                    if imgui.button("Doh!"):
                        self._error = None
                        imgui.close_current_popup()
                    imgui.end_popup()

        imgui.render()
        imgui.end_frame()
        data = imgui.get_draw_data()
        self.imgui_renderer.render(data)
Esempio n. 9
0
    def draw_logs(self):
        imgui.push_style_var(imgui.STYLE_WINDOW_PADDING, (6, 6))
        cur_style = imgui.get_style()
        padding = cur_style.window_padding
        cur_cursor_pos = imgui.get_cursor_pos()
        imgui.set_cursor_pos(
            (cur_cursor_pos[0] + padding[0], cur_cursor_pos[1] + padding[1]))
        imgui.begin_child(self.ID_CHILD_CONSOLE,
                          self.width - cur_style.window_padding[0] * 2,
                          self.height - 80, True)

        search_text = self.config.get_string(EConfigKey.CONTENT_SEARCH_TEXT)
        win_width = imgui.get_window_width()
        for idx, record in enumerate(self.log_mgr.log_lst):
            if not self.config.is_has_log_level(record.level):
                continue
            if not utils.filter_search_text(search_text, record):
                continue
            old_color = None
            if record.level == logging.ERROR:
                old_color = utils.set_style_color(imgui.COLOR_TEXT,
                                                  TextColor.ERed)
            elif record.level == logging.WARN or record.level == logging.WARNING:
                old_color = utils.set_style_color(imgui.COLOR_TEXT,
                                                  TextColor.EYellow)
            elif record.level == logging.INFO:
                old_color = utils.set_style_color(imgui.COLOR_TEXT,
                                                  TextColor.EWhite)
            imgui.push_id(str(idx))
            ret = imgui.selectable_wrap(record.msg_with_level,
                                        idx == self.sel_idx,
                                        imgui.SELECTABLE_ALLOW_DOUBLE_CLICK,
                                        win_width * 0.98, 30)
            if ret[1]:
                self.sel_idx = idx
            if imgui.is_item_hovered() and imgui.is_mouse_double_clicked(0):
                self.detail_idx = idx
                imgui.open_popup("detail_log_%d" % self.detail_idx)
            self.draw_log_detail_info_panel(idx, record)
            if old_color:
                utils.set_style_color(imgui.COLOR_TEXT, old_color)
            imgui.pop_id()

        if imgui.is_mouse_dragging() or imgui.get_io().mouse_wheel:
            if imgui.get_scroll_y() >= imgui.get_scroll_max_y():
                self.config.set_bool(EConfigKey.CONTENT_SCROLL_TO_BOTTOM, True)
            else:
                self.config.set_bool(EConfigKey.CONTENT_SCROLL_TO_BOTTOM,
                                     False)

        is_to_bottom = self.config.get_bool(
            EConfigKey.CONTENT_SCROLL_TO_BOTTOM, True)
        if is_to_bottom:
            imgui.set_scroll_y(imgui.get_scroll_max_y())

        imgui.end_child()
        imgui.pop_style_var()
Esempio n. 10
0
    def _show_custom_ui(self):
        super()._show_custom_ui()

        if imgui.button("choose file"):
            imgui.open_popup("choose_file")
        if imgui.begin_popup("choose_file"):
            for i, path in enumerate(self._files):
                if imgui.menu_item(path, "", False, True)[0]:
                    self.set_state({"index": i})
            imgui.end_popup()
Esempio n. 11
0
def render_errors(window):

    if window._error:
        imgui.open_popup("Error")
        if imgui.begin_popup_modal("Error")[0]:
            imgui.text(window._error)
            if imgui.button("Doh!"):
                window._error = None
                imgui.close_current_popup()
            imgui.end_popup()
Esempio n. 12
0
    def show(self, value, read_only):
        clicked, self.show_texture = imgui.checkbox("Show", self.show_texture)
        if not self.show_texture:
            return

        texture = value.value
        if texture is None:
            self.texture_aspect = None
        else:
            h, w, _ = texture.shape
            self.texture_aspect = w / h

        cursor_pos = imgui.get_cursor_screen_pos()
        imgui.set_next_window_size(500, 500, imgui.ONCE)
        imgui.set_next_window_size_constraints((0.0, 0.0),
                                               (float("inf"), float("inf")),
                                               self.window_size_callback)
        imgui.set_next_window_position(*imgui.get_io().mouse_pos,
                                       imgui.ONCE,
                                       pivot_x=0.5,
                                       pivot_y=0.5)
        expanded, opened = imgui.begin(
            "Texture of %s###%s%s" %
            (self.node.spec.name, id(self.node), id(self)), True,
            imgui.WINDOW_NO_SCROLLBAR)
        if not opened:
            self.show_texture = False
        if expanded:
            if texture is None:
                imgui.text("No texture associated")
            else:
                # [::-1] reverses list
                texture_size = texture.shape[:2][::-1]
                texture_aspect = texture_size[0] / texture_size[1]
                window_size = imgui.get_content_region_available()
                imgui.image(texture._handle, window_size[0],
                            window_size[0] / texture_aspect)
                if imgui.is_item_hovered() and imgui.is_mouse_clicked(1):
                    # little hack to have first context menu entry under cursor
                    io = imgui.get_io()
                    pos = io.mouse_pos
                    io.mouse_pos = pos[0] - 20, pos[1] - 20
                    imgui.open_popup("context")
                    io.mouse_pos = pos
                if imgui.begin_popup("context"):
                    if imgui.menu_item("save")[0]:
                        util.image.save_screenshot(texture.get())
                    imgui.menu_item("texture handle: %s" % texture._handle,
                                    None, False, False)
                    imgui.menu_item("texture dtype: %s" % str(texture.dtype),
                                    None, False, False)
                    imgui.menu_item("texture shape: %s" % str(texture.shape),
                                    None, False, False)
                    imgui.end_popup()
            imgui.end()
Esempio n. 13
0
    def _show_custom_context(self):
        # called from ui-node to add custom entries in nodes context menu
        # called only when that context menu is visible

        has_state = len(self.spec.initial_state) != 0
        has_presets = len(self.spec.presets) != 0

        if has_state:
            imgui.separator()

            if imgui.button("reset state"):
                self.reset_state(force=True)
            imgui.same_line()
            if imgui.button("randomize state"):
                self.randomize_state(force=True)

            changed, self.allow_state_randomization = imgui.checkbox(
                "allow state randomization", self.allow_state_randomization)

        if has_presets:
            imgui.separator()

            if imgui.button("default preset"):
                self.reset_preset(force=True)
            imgui.same_line()
            if imgui.button("random preset"):
                self.randomize_preset(force=True)
            imgui.same_line()
            if imgui.button("choose preset..."):
                imgui.open_popup("choose_preset")
            if imgui.begin_popup("choose_preset"):
                for name, values in self.spec.presets:
                    if imgui.button(name):
                        self.set_preset(values)
                imgui.end_popup()

            changed, self.allow_preset_randomization = imgui.checkbox(
                "allow preset randomization", self.allow_preset_randomization)

        if imgui.button("copy current as preset"):
            # copy only keys that are contained in (first) preset
            # TODO see how this behavior works
            keys = None if not has_presets else list(
                self.spec.presets[0][1].keys())
            values = OrderedDict()
            for port_id, value in self.values.items():
                if not is_input(port_id):
                    continue
                name = port_name(port_id)
                if keys is not None and name not in keys:
                    continue
                values[name] = value.value
            preset = ["name", values]
            clipboard.copy(json.dumps(preset))
Esempio n. 14
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)
Esempio n. 15
0
    def draw(self):
        imgui.begin("Example: simple popup")

        if imgui.button("select"):
            imgui.open_popup("select-popup")

        imgui.same_line()

        if imgui.begin_popup("select-popup"):
            imgui.text("Select one")
            imgui.separator()
            imgui.selectable("One")
            imgui.selectable("Two")
            imgui.selectable("Three")
            imgui.end_popup()

        imgui.end()
Esempio n. 16
0
    def draw(self):
        imgui.begin("Example: simple popup modal")

        if imgui.button("Open Modal popup"):
            imgui.open_popup("select-popup")

        imgui.same_line()

        if imgui.begin_popup_modal("select-popup")[0]:
            imgui.text("Select an option:")
            imgui.separator()
            imgui.selectable("One")
            imgui.selectable("Two")
            imgui.selectable("Three")
            imgui.end_popup()

        imgui.end()
Esempio n. 17
0
 def show(self, value, read_only):
     # don't show it as read-only for now
     # as the color picker dialog might be nice for inspecting the color
     r, g, b, a = value.value[:]
     flags = imgui.COLOR_EDIT_NO_INPUTS | imgui.COLOR_EDIT_NO_LABEL | imgui.COLOR_EDIT_ALPHA_PREVIEW
     if imgui.color_button("color %s" % id(self), r, g, b, a, flags, 50,
                           50):
         imgui.open_popup("picker %s" % id(self))
     if imgui.begin_popup("picker %s" % id(self)):
         changed, color = imgui.color_picker4(
             "color", r, g, b, a, imgui.COLOR_EDIT_ALPHA_PREVIEW)
         if changed:
             if not read_only:
                 # careful here! update it safely (with numpy-assignment)
                 # but also set it properly so it is regarded as changed
                 v = value.value
                 v[:] = color
                 value.value = v
         imgui.end_popup()
Esempio n. 18
0
def menubar():
    if imgui.begin_main_menu_bar():
        if imgui.begin_menu("File", True):

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

            if clicked_quit:
                exit(1)
            imgui.end_menu()
        if imgui.begin_menu("About", True):

            clicked_about, _ = imgui.menu_item(
                "About me..", 'F1', True, True
            )

            if clicked_about:
                imgui.open_popup("about-p")
            imgui.end_menu()
    imgui.end_main_menu_bar()
def MudClientWindow(MudData):
    # mud content
    MudData['World_text_changed'], MudData['World_text'] = imgui.input_text_multiline(
        '\n',
        MudData['World_text'],
        50000,
        1280,
        660,
        imgui.INPUT_TEXT_READ_ONLY
    )
    imgui.begin_group()
    imgui.text("Input:")
    imgui.same_line()
    MudData['Player_text_changed'], MudData['Player_text'] = imgui.input_text(
        '\n\n',
        MudData['Player_text'],
        1920,
        imgui.INPUT_TEXT_ENTER_RETURNS_TRUE
    )
    imgui.end_group()
    if imgui.button("keyboard"):
        imgui.open_popup("select-popup")
Esempio n. 20
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")
Esempio n. 21
0
def main():
    loadFlightData()

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

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

        # get the style object and edit the object to make it look decent with GLFW
        style = imgui.get_style()
        style.window_rounding = 0
        style.frame_rounding = 0

        #create the main ImGuI frame to then use to display the actual GUI on
        imgui.new_frame()

        flags = imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_MENU_BAR

        imgui.set_next_window_size(window_width, window_height)
        imgui.set_next_window_position(0, 0)

        # Start the beginning of the ImGui window, drone flight logger being an ID
        imgui.begin("Drone Flight Logger", False, flags=flags)

        if imgui.button("Add new Flight"):
            imgui.open_popup("test")

        imgui.same_line()

        imgui.text("Total Flight Time: " + str(flights.getTotalFlightTime()) +
                   "h")

        imgui.same_line()

        imgui.text("| Total Batteries Used: " +
                   str(flights.getTotalBatteriesUsed()))

        # Main Menu Bar Code
        mainMenuBar()

        # create a child window in the inital window to divide the window up so there can be a preview on the left
        imgui.begin_child("flight_selector",
                          width=window_width / 5 * 2,
                          border=True)

        # loop through all flights and assign flight as the key value
        for flight in flights.getFlights():
            # get the flight data based off the flight name
            flight_data = flights.getFlights()[flight]
            # if the flight location is in the List variable of currently selected locations show it
            if currentSelectedLocations[flight_data.getLocationName()]:
                # flight drop down code, passing in the flight name and flight data
                flightDropDown(flight, flight_data)

        imgui.end_child()

        imgui.same_line()

        # create the preview sidepane of the main window
        imgui.begin_child("flight_info", border=True)

        # if there is the key preview in currentviewingflightdata show the image. Done this way as I will eventually add in the flight location and other stats to the sidepane as well
        if "preview" in currentViewingFlightData:
            imgui.image(currentViewingFlightData["preview"]['image'],
                        currentViewingFlightData["preview"]['width'] / 6,
                        currentViewingFlightData["preview"]['height'] / 6)

        imgui.end_child()

        if imgui.begin_popup_modal("test")[0]:
            addNewFlightData["date"] = imgui.input_text(
                "Flight date", addNewFlightData["date"], 2046)[1]
            addNewFlightData["batteries_used"] = imgui.input_int(
                'Batteries used', addNewFlightData["batteries_used"])[1]
            addNewFlightData["flight_time"] = imgui.input_int(
                'Flight time in minutes', addNewFlightData["flight_time"])[1]
            addNewFlightData["location_name"] = imgui.input_text(
                "Flight location", addNewFlightData["location_name"], 2046)[1]
            addNewFlightData["copyFromFolder"] = imgui.input_text(
                "Folder with new flight media",
                addNewFlightData["copyFromFolder"], 2046)[1]

            if imgui.button("test"):
                handleAddNewFlight()
                imgui.close_current_popup()

            # imgui.text("Select an option:")
            # imgui.separator()
            # imgui.selectable("One")
            # imgui.selectable("Two")
            # imgui.selectable("Three")
            imgui.end_popup()

        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()
Esempio n. 22
0
def main():

    # Theme Index
    THEME_INDEX = 2

    # window visible params
    bShowInfoPopUp = False
    bShowFiles = True
    bShowParsePdf = True
    bShowParserStatics = True

    bShowImg = False
    bShowTestWindow = True

    #delete cache files
    if os.path.isfile('ParseResult.log'):
        os.remove('ParseResult.log')
    if os.path.isfile('ManualFiles.log'):
        os.remove('ManualFiles.log')
    if os.path.isfile('Cluster.png'):
        os.remove('Cluster.png')

    pygame.init()
    size = 1280, 720  # 720p
    # size = 1920, 1080 # 1080p

    pygame.display.set_mode(
        size, pygame.DOUBLEBUF | pygame.OPENGL | pygame.RESIZABLE)
    pygame.display.set_caption("PDF成績單解析器")

    clock = pygame.time.Clock()

    favicon = pygame.image.load('asset\\Logo.png')
    pygame.display.set_icon(favicon)

    imgui.create_context()

    impl = PygameRenderer()

    io = imgui.get_io()
    smallfont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 12,
        io.fonts.get_glyph_ranges_chinese_full())
    normalfont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 16,
        io.fonts.get_glyph_ranges_chinese_full())
    largefont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 28,
        io.fonts.get_glyph_ranges_chinese_full())
    io.fonts.add_font_default()
    impl.refresh_font_texture()
    io.display_size = size

    style = imgui.get_style()
    if THEME_INDEX == 1:
        GF.SetCustomStyle1(style)
    elif THEME_INDEX == 2:
        GF.SetCustomStyle2(style)
    elif THEME_INDEX == 3:
        GF.SetCustomStyle3(style)

    CV = 0
    MV = 200
    while 1:
        clock.tick(30)  # fixed 15 fps

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # remove cache here
                sys.exit()
            if event.type == pygame.VIDEORESIZE:
                print('resize is triggered!')

            # shortcut bindings
            if event.type == pygame.KEYDOWN:
                if event.mod == pygame.KMOD_LCTRL and event.key == pygame.K_q:
                    sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F1:
                    GF.OpenHelper()

            impl.process_event(event)
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, (10, 12.5))
        imgui.new_frame()

        # Main menu region
        if imgui.begin_main_menu_bar():
            with imgui.font(normalfont):
                if imgui.begin_menu("設定", True):
                    if imgui.begin_menu(label="主題", enabled=True):
                        if THEME_INDEX == 1:
                            imgui.menu_item("默認", None, True, True)
                        else:
                            c, _ = imgui.menu_item("默認", None, False, True)
                            if c:
                                GF.SetCustomStyle1(style)
                                THEME_INDEX = 1
                        if THEME_INDEX == 2:
                            imgui.menu_item("CorporateGrey", None, True, True)
                        else:
                            c, _ = imgui.menu_item("CorporateGrey", None,
                                                   False, True)
                            if c:
                                GF.SetCustomStyle2(style)
                                THEME_INDEX = 2
                        if THEME_INDEX == 3:
                            imgui.menu_item("Light", None, True, True)
                        else:
                            c, _ = imgui.menu_item("Light", None, False, True)
                            if c:
                                GF.SetCustomStyle3(style)
                                THEME_INDEX = 3
                        imgui.end_menu()

                    clicked_quit, selected_quit = imgui.menu_item(
                        "Quit", "L-Ctrl + Q", False, True)
                    if clicked_quit:
                        sys.exit()
                    imgui.end_menu()

                if imgui.begin_menu("視窗", True):
                    if not bShowFiles:
                        F, _ = imgui.menu_item(label="選擇目錄",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        F, _ = imgui.menu_item(label="選擇目錄",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if F:
                        bShowFiles = not bShowFiles
                    if not bShowParsePdf:
                        o, _ = imgui.menu_item(label="解析成績單",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        o, _ = imgui.menu_item(label="解析成績單",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if o:
                        bShowParsePdf = not bShowParsePdf
                    if not bShowParserStatics:
                        r, _ = imgui.menu_item(label="解析結果",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        r, _ = imgui.menu_item(label="解析結果",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if r:
                        bShowParserStatics = not bShowParserStatics

                    imgui.end_menu()

                if imgui.begin_menu("資訊", True):
                    I, _ = imgui.menu_item("關於",
                                           None,
                                           selected=False,
                                           enabled=True)
                    h, _ = imgui.menu_item("幫助",
                                           shortcut="F1",
                                           selected=False,
                                           enabled=True)
                    if I:
                        bShowInfoPopUp = True

                    if h:
                        GF.OpenHelper()

                    imgui.end_menu()

            #imgui.pop_style_var(1)
            imgui.end_main_menu_bar()

        # Conditional windows
        if bShowFiles:
            imgui.set_next_window_position(0, 35, imgui.ONCE)
            imgui.set_next_window_size(230, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bFileWindow = imgui.begin("選擇目錄",
                                          True,
                                          flags=imgui.WINDOW_NO_RESIZE
                                          | imgui.WINDOW_NO_MOVE
                                          | imgui.WINDOW_NO_COLLAPSE)
                if not bFileWindow[1]:
                    bShowFiles = False
                GE.FileWindow()
                imgui.end()

        if bShowParsePdf:
            imgui.set_next_window_position(230, 35, imgui.ONCE)
            imgui.set_next_window_size(450, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bParsePdf = imgui.begin("解析成績單", True)
                if not bParsePdf[1]:
                    bShowParsePdf = False
                GE.ParsePdfWidget()
                imgui.end()

        if bShowParserStatics:
            imgui.set_next_window_position(680, 35, imgui.ONCE)
            imgui.set_next_window_size(600, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bParserStats = imgui.begin("解析結果", True)
                if not bParserStats[1]:
                    bShowParserStatics = False
                GE.ParserStaticsWidget()
                if os.path.isfile('Cluster.png'):
                    img_info = GF.loadImage('Cluster.png')
                    imgui.image(img_info[0], img_info[1], img_info[2])
                imgui.end()

        if (bShowInfoPopUp):
            imgui.open_popup("資訊")

        imgui.set_next_window_size(600, 300)
        imgui.font(normalfont)
        if imgui.begin_popup_modal(title="資訊", visible=True, flags=0)[0]:
            GE.ProgramInfoPopup()
            imgui.separator()
            bShowInfoPopUp = False
            imgui.end_popup()

        if THEME_INDEX == 1:
            gl.glClearColor(0.1, 0.1, 0.1, 1)  # for default theme
        elif THEME_INDEX == 2:
            gl.glClearColor(0.45, 0.55, 0.6, 1)  # for light theme
        elif THEME_INDEX == 3:
            gl.glClearColor(0.25, 0.25, 0.25, 1.00)

        imgui.pop_style_var()
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        impl.render(imgui.get_draw_data())
        pygame.display.flip()

        CV += 1
Esempio n. 23
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()
Esempio n. 24
0
def frame_commands():
    io = imgui.get_io()

    if io.key_ctrl and io.keys_down[glfw.KEY_Q]:
        sys.exit(0)

    with imgui.begin_main_menu_bar() as main_menu_bar:
        if main_menu_bar.opened:
            with imgui.begin_menu("File", True) as file_menu:
                if file_menu.opened:
                    clicked_quit, selected_quit = imgui.menu_item(
                        "Quit", "Ctrl+Q")
                    if clicked_quit:
                        sys.exit(0)

    # turn examples on/off
    with imgui.begin("Active examples"):
        for label, enabled in active.copy().items():
            _, enabled = imgui.checkbox(label, enabled)
            active[label] = enabled

    if active["window"]:
        with imgui.begin("Hello, Imgui!"):
            imgui.text("Hello, World!")

    if active["child"]:
        with imgui.begin("Example: child region"):
            with imgui.begin_child("region", 150, -50, border=True):
                imgui.text("inside region")
            imgui.text("outside region")

    if active["tooltip"]:
        with imgui.begin("Example: tooltip"):
            imgui.button("Click me!")
            if imgui.is_item_hovered():
                with imgui.begin_tooltip():
                    imgui.text("This button is clickable.")

    if active["menu bar"]:
        try:
            flags = imgui.WINDOW_MENU_BAR
            with imgui.begin("Child Window - File Browser", flags=flags):
                with imgui.begin_menu_bar() as menu_bar:
                    if menu_bar.opened:
                        with imgui.begin_menu('File') as file_menu:
                            if file_menu.opened:
                                clicked, state = imgui.menu_item('Close')
                                if clicked:
                                    active["menu bar"] = False
                                    raise Exception
        except Exception:
            print("exception handled")

    if active["popup"]:
        with imgui.begin("Example: simple popup"):
            if imgui.button("select"):
                imgui.open_popup("select-popup")
            imgui.same_line()
            with imgui.begin_popup("select-popup") as popup:
                if popup.opened:
                    imgui.text("Select one")
                    imgui.separator()
                    imgui.selectable("One")
                    imgui.selectable("Two")
                    imgui.selectable("Three")

    if active["popup modal"]:
        with imgui.begin("Example: simple popup modal"):
            if imgui.button("Open Modal popup"):
                imgui.open_popup("select-popup-modal")
            imgui.same_line()
            with imgui.begin_popup_modal("select-popup-modal") as popup:
                if popup.opened:
                    imgui.text("Select an option:")
                    imgui.separator()
                    imgui.selectable("One")
                    imgui.selectable("Two")
                    imgui.selectable("Three")

    if active["popup context item"]:
        with imgui.begin("Example: popup context view"):
            imgui.text("Right-click to set value.")
            with imgui.begin_popup_context_item("Item Context Menu") as popup:
                if popup.opened:
                    imgui.selectable("Set to Zero")

    if active["popup context window"]:
        with imgui.begin("Example: popup context window"):
            with imgui.begin_popup_context_window() as popup:
                if popup.opened:
                    imgui.selectable("Clear")

    if active["popup context void"]:
        with imgui.begin_popup_context_void() as popup:
            if popup.opened:
                imgui.selectable("Clear")

    if active["drag drop"]:
        with imgui.begin("Example: drag and drop"):
            imgui.button('source')
            with imgui.begin_drag_drop_source() as src:
                if src.dragging:
                    imgui.set_drag_drop_payload('itemtype', b'payload')
                    imgui.button('dragged source')
            imgui.button('dest')
            with imgui.begin_drag_drop_target() as dst:
                if dst.hovered:
                    payload = imgui.accept_drag_drop_payload('itemtype')
                    if payload is not None:
                        print('Received:', payload)

    if active["group"]:
        with imgui.begin("Example: item groups"):
            with imgui.begin_group():
                imgui.text("First group (buttons):")
                imgui.button("Button A")
                imgui.button("Button B")
            imgui.same_line(spacing=50)
            with imgui.begin_group():
                imgui.text("Second group (text and bullet texts):")
                imgui.bullet_text("Bullet A")
                imgui.bullet_text("Bullet B")

    if active["tab bar"]:
        with imgui.begin("Example Tab Bar"):
            with imgui.begin_tab_bar("MyTabBar") as tab_bar:
                if tab_bar.opened:
                    with imgui.begin_tab_item("Item 1") as item1:
                        if item1.opened:
                            imgui.text("Here is the tab content!")
                    with imgui.begin_tab_item("Item 2") as item2:
                        if item2.opened:
                            imgui.text("Another content...")
                    global opened_state
                    with imgui.begin_tab_item("Item 3",
                                              opened=opened_state) as item3:
                        opened_state = item3.opened
                        if item3.selected:
                            imgui.text("Hello Saylor!")

    if active["list box"]:
        with imgui.begin("Example: custom listbox"):
            with imgui.begin_list_box("List", 200, 100) as list_box:
                if list_box.opened:
                    imgui.selectable("Selected", True)
                    imgui.selectable("Not Selected", False)

    if active["table"]:
        with imgui.begin("Example: table"):
            with imgui.begin_table("data", 2) as table:
                if table.opened:
                    imgui.table_next_column()
                    imgui.table_header("A")
                    imgui.table_next_column()
                    imgui.table_header("B")

                    imgui.table_next_row()
                    imgui.table_next_column()
                    imgui.text("123")

                    imgui.table_next_column()
                    imgui.text("456")

                    imgui.table_next_row()
                    imgui.table_next_column()
                    imgui.text("789")

                    imgui.table_next_column()
                    imgui.text("111")

                    imgui.table_next_row()
                    imgui.table_next_column()
                    imgui.text("222")

                    imgui.table_next_column()
                    imgui.text("333")
Esempio n. 25
0
 def open(self):
     imgui.open_popup(self.name)
Esempio n. 26
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
Esempio n. 27
0
def render_palette_popup(drawing: Drawing):

    global edit_color
    global color_editor_open

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

    _, opened = imgui.begin("Color popup", True)

    imgui.begin_child("Colors", height=0)

    imgui.push_style_var(imgui.STYLE_ITEM_SPACING,
                         (0, 0))  # Make layout tighter
    width = int(imgui.get_window_content_region_width()) // 25

    for i, color in enumerate(palette.colors, 0):
        is_foreground = i == fg
        is_background = (i == bg) * 2
        selection = is_foreground | is_background
        if i in palette.overlay:
            color = as_float(palette.overlay[i])
        else:
            color = as_float(color)
        imgui.push_style_color(imgui.COLOR_FRAME_BACKGROUND,
                               *SELECTABLE_FRAME_COLORS[selection])
        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 = i
        imgui.pop_style_color(1)

        if imgui.core.is_item_clicked(1):
            edit_color = i
            color_editor_open = True
            imgui.open_popup("Edit foreground color")
            # imgui.set_next_window_position(w - 115 - 120, 200)

        if imgui.core.is_item_clicked(2):
            # Detect right button clicks on the button
            bg = i

        if imgui.begin_drag_drop_source():
            imgui.set_drag_drop_payload('start_index',
                                        i.to_bytes(1, sys.byteorder))
            imgui.color_button(f"color {i}", *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, i, image_only=image_only)
                # palette.clear_overlay()
            imgui.end_drag_drop_target()

        # if imgui.is_item_hovered():
        #     io = imgui.get_io()
        #     delta = int(io.mouse_wheel)

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

    imgui.pop_style_var(1)
    #color_editor_open = render_color_editor_popup(drawing, edit_color, color_editor_open)

    imgui.end_child()
    imgui.end()

    palette.foreground = fg
    palette.background = bg

    return opened, open_color_editor