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()
def draw_list(id_str, label, items, select_item, delete_callback=None): imgui.begin_child(id_str) imgui.text(label) cur_state.hovered_item = None for idx, item in enumerate(items): cur_id_str = "##list_{}_{}".format(id_str, idx) sel_btn_id = "Select {} {}".format(idx, cur_id_str) del_btn_id = "X{}".format(cur_id_str) imgui.begin_group() if imgui.button(sel_btn_id): print("clicked {}".format(idx)) select_item(idx) imgui.same_line() imgui.text(str(item)) if delete_callback is not None: imgui.same_line() if imgui.button(del_btn_id): delete_callback(item) print("delete!!") imgui.end_group() if imgui.is_item_hovered(): cur_state.hovered_item = item imgui.end_child()
def child(name, widget, width, height, border=False, flags=0): r""" Create a sized box with a `widget` inside. If the contents overflow, scrollbars will be created by default. Sizing of the child widget allows for three modes, depending on the sign of parameters `width` and `height`: * ==0 - use the remaining window size * \>0 - fixed size in pixels * <0 - use remaining window size minus abs(size) in pixels Args: name: Child name. This has no effect, and will be removed in the future. widget: Widget to display inside the box. width: Box width. height: Box height. border: Toggle border visibility. flags: Advanced customization flags. See the [list of available flags](https://pyimgui.readthedocs.io/en/latest/guide/window-flags.html#window-flag-options). """ while True: imgui.begin_child(name, width, height, border, flags) try: next(widget) except StopIteration as e: return e.value finally: imgui.end_child() yield
def draw_console(): global _console_text_temp if console.SHOW_CONSOLE: imgui.set_next_window_bg_alpha(0.35) imgui.set_next_window_position(0, 0) imgui.set_next_window_size(screen_utils.WIDTH, 110) imgui.begin( "ConsoleWindow", False, imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_SAVED_SETTINGS) imgui.begin_child("ConsoleOutput", 0, -25, False) for text, color in console.text_buffer: if color is None: color = (0.25, 0.75, 1) imgui.text_colored(text, color[0], color[1], color[2], 0.8) imgui.text("") imgui.set_scroll_y(imgui.get_scroll_max_y()) imgui.end_child() buf_size = 256 if len(_console_text_temp) > 0 and not _console_text_temp[0] == "/": buf_size = 64 enter, text = imgui.input_text("Input", _console_text_temp, buf_size, imgui.INPUT_TEXT_ENTER_RETURNS_TRUE) if enter: if str.startswith(text, "/"): text = str.replace(text, "/", "", 1) console.handle_input(text) else: client_net.send_message(text) text = "" _console_text_temp = text imgui.end()
def draw(self): imgui.begin("log_window", flags=imgui.WINDOW_NO_RESIZE) imgui.begin_child("log", 200, 300, border=True) for i in range(len(self.str_list) - 1, -1, -1): imgui.text(self.str_list[i]) imgui.end_child() if imgui.button('Clear'): self.str_list = [] imgui.end()
def draw(self): imgui.begin("Example: child region") imgui.begin_child("region", 150, -50, border=True) imgui.text("inside region") imgui.end_child() imgui.text("outside region") imgui.end()
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()
def gui(self): imgui.begin_child(self.name) for item, remove_button in zip(self.items, self.remove_buttons): if isinstance(item, Widget): item.gui() else: text = getattr(item, 'name', str(item)) imgui.label_text(text, text) imgui.same_line() remove_button.gui() imgui.end_child()
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: child region") imgui.begin_child("region", 150, -50, border=True) imgui.text("inside region") imgui.end_child() imgui.text("outside region") imgui.end() imgui.end_frame() imgui.render() self.renderer.render(imgui.get_draw_data())
def do_show_text(self, title, x, y, w, h, text, use_hsbar=False): """在指定的位置显示窗口并输出指定的文本""" # 子窗口标记:不可移动不可改变 flags = imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_SAVED_SETTINGS # 设置子窗口位置 imgui.set_next_window_position(x, y) imgui.set_next_window_size(w, h) # 显示子窗口 if imgui.begin(title, False, flags)[1]: flags = 0 if use_hsbar: flags |= imgui.WINDOW_HORIZONTAL_SCROLLING_BAR if text: imgui.begin_child("region", imgui.get_window_width() - 16, h - 40, True, flags) # 开启子区域,设定文本自动换行范围 if not use_hsbar: imgui.push_text_wrap_pos(imgui.get_window_width() - 4) imgui.text(text) imgui.end_child() imgui.end()
def render_inspector_keyboard ( self ): imgui.begin_child( "keyboard", 0, 0, border = True ) if self.context != None: current_keys = list( self.get_pressed_keystrokes() ) keyboard : KeyboardLibrary = self.context.library( KeyboardLibrary ) for key in current_keys: keyboard.on_press( key, self.player ) released = set( keyboard.pressed_keys ) - set( current_keys ) for key in released: keyboard.on_release( key, self.player ) for key, expr in keyboard.keys: imgui.bullet() if expr.is_pressed: imgui.text_colored( str( key ), 0, 1, 0 ) else: imgui.text( str( key ) ) imgui.end_child()
def displayInterface(self): imgui.begin_child("left_bottom", width=606, height=370) imgui.text("Network Traffic") imgui.separator() imgui.spacing() plot_rx = array('f') for byte in self.rx_bytes: plot_rx.append(byte) plot_tx = array('f') for byte in self.tx_bytes: plot_tx.append(byte) imgui.text("Download Traffic (MB) | Avg: " + str(round(sum(self.rx_bytes) / len(self.rx_bytes), 5)) + " mb | Max: " + str(round(max(self.rx_bytes), 5)) + " mb") imgui.plot_lines("##Rx Traffic (MB)", plot_rx, graph_size=(606, 150)) imgui.spacing() imgui.text("Upload Traffic (MB) | Avg: " + str(round(sum(self.tx_bytes) / len(self.tx_bytes), 5)) + " mb | Max: " + str(round(max(self.tx_bytes), 5)) + " mb") imgui.plot_lines("##Tx Traffic (MB)", plot_tx, graph_size=(606, 150)) imgui.end_child() imgui.same_line() imgui.begin_child("net_traf_alerts") imgui.text("Network Traffic Alerts") imgui.begin_child("net_traf_alerts_logger", border=True) for message in self.alerts: imgui.text_wrapped(message) imgui.end_child() imgui.end_child()
def frame_commands(): gl.glClearColor(0.1, 0.1, 0.1, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) io = imgui.get_io() if io.key_ctrl and io.keys_down[glfw.KEY_Q]: sys.exit(0) if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_quit, selected_quit = imgui.menu_item("Quit", "Ctrl+Q", False, True) if clicked_quit: sys.exit(0) imgui.end_menu() imgui.end_main_menu_bar() # turn windows on/off imgui.begin("Active examples") for label, enabled in active.copy().items(): _, enabled = imgui.checkbox(label, enabled) active[label] = enabled imgui.end() if active["window"]: imgui.begin("Hello, Imgui!") imgui.text("Hello, World!") imgui.end() if active["child"]: imgui.begin("Example: child region") imgui.begin_child("region", 150, -50, border=True) imgui.text("inside region") imgui.end_child() imgui.text("outside region") imgui.end() if active["tooltip"]: imgui.begin("Example: tooltip") imgui.button("Click me!") if imgui.is_item_hovered(): imgui.begin_tooltip() imgui.text("This button is clickable.") imgui.end_tooltip() imgui.end() if active["menu bar"]: try: flags = imgui.WINDOW_MENU_BAR imgui.begin("Child Window - File Browser", flags=flags) if imgui.begin_menu_bar(): if imgui.begin_menu('File'): clicked, state = imgui.menu_item('Close') if clicked: active["menu bar"] = False raise Exception imgui.end_menu() imgui.end_menu_bar() imgui.end() except Exception: print("exception caught, but too late!") if active["popup"]: 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() if active["popup modal"]: imgui.begin("Example: simple popup modal") if imgui.button("Open Modal popup"): imgui.open_popup("select-popup-modal") imgui.same_line() if imgui.begin_popup_modal("select-popup-modal")[0]: imgui.text("Select an option:") imgui.separator() imgui.selectable("One") imgui.selectable("Two") imgui.selectable("Three") imgui.end_popup() imgui.end() if active["popup context item"]: imgui.begin("Example: popup context view") imgui.text("Right-click to set value.") if imgui.begin_popup_context_item("Item Context Menu"): imgui.selectable("Set to Zero") imgui.end_popup() imgui.end() if active["popup context window"]: imgui.begin("Example: popup context window") if imgui.begin_popup_context_window(): imgui.selectable("Clear") imgui.end_popup() imgui.end() if active["popup context void"]: if imgui.begin_popup_context_void(): imgui.selectable("Clear") imgui.end_popup() if active["drag drop"]: imgui.begin("Example: drag and drop") imgui.button('source') if imgui.begin_drag_drop_source(): imgui.set_drag_drop_payload('itemtype', b'payload') imgui.button('dragged source') imgui.end_drag_drop_source() imgui.button('dest') if imgui.begin_drag_drop_target(): payload = imgui.accept_drag_drop_payload('itemtype') if payload is not None: print('Received:', payload) imgui.end_drag_drop_target() imgui.end() if active["group"]: imgui.begin("Example: item groups") imgui.begin_group() imgui.text("First group (buttons):") imgui.button("Button A") imgui.button("Button B") imgui.end_group() imgui.same_line(spacing=50) imgui.begin_group() imgui.text("Second group (text and bullet texts):") imgui.bullet_text("Bullet A") imgui.bullet_text("Bullet B") imgui.end_group() imgui.end() if active["tab bar"]: imgui.begin("Example Tab Bar") if imgui.begin_tab_bar("MyTabBar"): if imgui.begin_tab_item("Item 1")[0]: imgui.text("Here is the tab content!") imgui.end_tab_item() if imgui.begin_tab_item("Item 2")[0]: imgui.text("Another content...") imgui.end_tab_item() global opened_state selected, opened_state = imgui.begin_tab_item("Item 3", opened=opened_state) if selected: imgui.text("Hello Saylor!") imgui.end_tab_item() imgui.end_tab_bar() imgui.end() if active["list box"]: imgui.begin("Example: custom listbox") if imgui.begin_list_box("List", 200, 100): imgui.selectable("Selected", True) imgui.selectable("Not Selected", False) imgui.end_list_box() imgui.end() if active["table"]: imgui.begin("Example: table") if imgui.begin_table("data", 2): 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") imgui.end_table() imgui.end()
def update(self): # return done, value do_return = False recipe = '' if self.extra_font: imgui.push_font(self.extra_font) width = 750 height = 250 imgui.set_next_window_size(width, height) imgui.set_next_window_position(self.center_x - width // 2, self.center_y - height // 2) imgui.push_style_var(imgui.STYLE_ALPHA, self.alpha) imgui.begin('Drop', False, flags=self.flags) self.left_label('ID:') xx, self.id = imgui.input_text('\n', self.id, 128) self.tooltip_help('Participant ID/Name') self.add_space(3) self.left_label('Español:') _, self.spanish = imgui.checkbox('', self.spanish) self.tooltip_help('Spanish text for subsequent instructions') self.add_space(3) self.left_label('Recipe:') # current filenames recipe_names = [] recipe_short = [] for file in glob.glob('recipes/**/*.toml', recursive=True): if (os.path.sep + 'defaults' + os.path.sep) not in file: recipe_names.append(file) recipe_short.append(os.path.relpath(file, 'recipes')) changed, self.current_recipe = imgui.combo(' ', self.current_recipe, recipe_short) self.tooltip_help( 'Available recipes (TOML files) in the recipe directory') imgui.same_line() imgui.button('Preview') if imgui.is_item_hovered() and recipe_names: with open(recipe_names[self.current_recipe], 'r') as f: prev = f.read() # width in characters, height in number of newlines if prev: wid = len( max(open(recipe_names[self.current_recipe], 'r'), key=len)) # TODO: need to be careful of newline char?? hei = prev.count('\n') + 1 else: wid = 10 hei = 1 fac = 0.6 font_size = imgui.get_font_size() * fac wid = int(wid * font_size / 2) # get something like pix hei = int(hei * font_size) # if height is >= half the window height, turn to scroll val = hei if hei >= self.center_y: val = self.center_y imgui.begin_tooltip() imgui.begin_child('region', wid, val) imgui.set_scroll_y(imgui.get_scroll_y() - imgui.get_io().mouse_wheel * 30) imgui.set_window_font_scale(fac) imgui.text(prev) imgui.end_child() imgui.end_tooltip() imgui.set_item_default_focus() # imgui.set_tooltip(prev) self.add_space(3) if imgui.button('Ok'): do_return = True if imgui.get_io().keys_down[imgui.KEY_ENTER]: do_return = True imgui.pop_style_var(1) imgui.end() if self.extra_font: imgui.pop_font() # disallow depending on current state if not self.id: do_return = False try: recipe = recipe_names[self.current_recipe] except IndexError: do_return = False if not os.path.isdir(self.recipe_dir): do_return = False # no need to validate data dir, we'll create it data = { 'id': self.id, 'recipe': recipe, 'spanish': 'es' if self.spanish else 'en' } return do_return, data
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()
def rom_list(collections, console_selected, prefix='A', checkbox_extract=False): # clear both buffers imguihelper.clear() _nx.gfx_set_mode(TILED_DOUBLE) clear_terminal() imguihelper.initialize() renderer = NXRenderer() # TODO fetcing indicator roms = fetch_roms(collections[console_selected], prefix) # create collection rom folder directory = "Roms" parent_dir = "sdmc:/" path = os.path.join(parent_dir, directory, console_selected) try: os.makedirs(path, exist_ok=True) except OSError as error: print("Directory '%s' can not be created" % path) os.chdir(path) dir_content = os.listdir() while True: renderer.handleinputs() imgui.new_frame() width, height = renderer.io.display_size imgui.set_next_window_size(width, height) imgui.set_next_window_position(0, 0) imgui.begin("", flags=imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_SAVED_SETTINGS) imgui.begin_group() imgui.push_style_color(imgui.COLOR_BUTTON, *MENU_BUTTON_COLOR_SELECTED) if imgui.button("< Back", width=70, height=50): main(collections) imgui.pop_style_color(1) imgui.same_line(spacing=50) _, checkbox_extract = imgui.checkbox("EXTRACT .ZIP AFTER DOWNLOAD", checkbox_extract) imgui.text("Collection: " + console_selected) imgui.new_line() for letter in '#' + string.ascii_uppercase: button_color = MENU_BUTTON_COLOR_SELECTED if prefix == letter else MENU_BUTTON_COLOR imgui.same_line() imgui.push_style_color(imgui.COLOR_BUTTON, *button_color) if imgui.button(letter, width=28, height=28): rom_list(collections, console_selected, letter, checkbox_extract) imgui.pop_style_color(1) imgui.new_line() imgui.begin_child("region", -0, -0, border=True) for rom in roms: folder_name = os.path.splitext(rom['title'])[0] is_downloaded = any(x in dir_content for x in [rom['title'], folder_name]) button_color = ROM_COLOR_DOWNLOADED if is_downloaded else ROM_COLOR imgui.push_style_color(imgui.COLOR_BUTTON, *button_color) if imgui.button(rom['title'] + " " + rom['size'], width=1240, height=30): download(rom, console_selected, checkbox_extract) imgui.pop_style_color(1) imgui.end_child() imgui.end_group() imgui.end() imgui.render() renderer.render() renderer.shutdown()
def draw_big_lattice(self, L, name='lattice', index=None): imgui.begin_child(name, 0, self.lattice_height, border=True) win_pos = imgui.get_window_position() L = L.L # Calculate rank and node separation sizes. region_min = imgui.get_window_content_region_min() region_max = imgui.get_window_content_region_max() region_size = (region_max.x - region_min.x, region_max.y - region_min.y) n_r = len(L)+1 n_n = np.max([len(l) for l in L])+1 rank_sep = region_size[1] / n_r node_sep = region_size[0] / n_n # radius = np.min([node_sep, rank_sep]) / 8 radius = 6.0 off_x = win_pos.x + region_min.x + node_sep off_y = win_pos.y + region_min.y + rank_sep draw_list = imgui.get_window_draw_list() # Create ranks manually color = imgui.get_color_u32_rgba(*get_color('safety yellow')) offset = np.max([(len(l) - 1) * node_sep for l in L])/2 extents = [] for i in range(len(L)): n_f = len(L[i]) l = max(radius, (n_f - 1) * node_sep) x0 = round(off_x + offset + -l/2 + 0) y0 = round(off_y + rank_sep * i) x1 = round(off_x + offset + -l/2 + l) y1 = round(off_y + rank_sep * i) draw_list.add_line(x0, y0, x1, y1, color, radius) extents.append([np.array([x0, y0]), np.array([x1, y1])]) # Add random lines to simulate a lattice structure. thickness = 1 np.random.seed(0) for i in range(1, len(L)): for s0, s1 in [(1, 1), (0, 0)]: e0 = extents[i-1] e1 = extents[i] # s0 = np.random.rand() # s0 = s p0 = s0*e0[0] + (1-s0)*e0[1] # s1 = np.random.rand() # s1 = 1-s p1 = s1*e1[0] + (1-s1)*e1[1] draw_list.add_line(p0[0], p0[1], p1[0], p1[1], color, thickness) # Draw current index in red. if index is not None: e = extents[index[0]] if len(L[index[0]]) > 1: s = index[1]/(len(L[index[0]]) - 1) else: s = 0.5 p = (1-s)*e[0] + s*e[1] red = imgui.get_color_u32_rgba(*get_color('red')) draw_list.add_line(p[0]+radius/2, p[1], p[0]-radius/2, p[1], red, radius) imgui.end_child()
def render_editor(self): if imgui.button("optimize track"): self.start_optimization() imgui.same_line() _, ks = imgui.slider_float2("kcurv, kdist", self.kcurv, self.kdist, min_value=0, max_value=100.0, power=2) self.kcurv, self.kdist = ks _, self.lanewidth = imgui.slider_float("lane width", self.lanewidth, min_value=10, max_value=1000, power=1.5) # use a child region just to keep appearing/disappearing widgets at the # top from shifting stuff around imgui.begin_child("region", 0, 25, border=False) if (self.editmode == 'turn' and self.selectedpt is not None and self.selectedpt < len(self.pts['turn'])): i = self.selectedpt T = self.pts['turn'] _, T[i][2] = imgui.slider_float("turn %d radius" % (i + 1), T[i][2], min_value=-1000., max_value=1000., power=1.2) if self.editmode == 'home': _, self.homeangle = imgui.slider_float("home position angle", self.homeangle, -3.141, 3.141) imgui.end_child() w, h = imgui.get_window_size() h = self.mapim.shape[0] * w / self.mapim.shape[1] imgui.image_button(self.maptex, w, h, frame_padding=0) rectmin = imgui.get_item_rect_min() if imgui.is_item_clicked(0): mxy = imgui.get_mouse_pos() u = (mxy[0] - rectmin[0]) * self.mapim.shape[1] / w v = (mxy[1] - rectmin[1]) * self.mapim.shape[1] / w if imgui.is_mouse_double_clicked(0): self.add_point(u, v) else: self.select_point(u, v) if (imgui.is_item_hovered() and self.selectedpt is not None and imgui.is_mouse_dragging(0)): mxy = imgui.get_mouse_pos() u = (mxy[0] - rectmin[0]) * self.mapim.shape[1] / w v = (mxy[1] - rectmin[1]) * self.mapim.shape[1] / w self.move_point(u, v) scale = w / self.mapim.shape[1] dl = imgui.get_window_draw_list() self.render_ptlist(dl, self.pts['cone'], rectmin, scale, imgui.get_color_u32_rgba(1, 0.7, 0, 1), 4, self.editmode == 'cone') self.render_ptlist(dl, self.pts['turn'], rectmin, scale, imgui.get_color_u32_rgba(0, 0.3, 1, 1), 3, self.editmode == 'turn') self.render_ptlist(dl, self.pts['home'], rectmin, scale, imgui.get_color_u32_rgba(1, 1, 1, 1), 10, self.editmode == 'home') # render home position angle if len(self.pts['home']) > 0: h = self.pts['home'][0] S = 100 * np.sin(self.homeangle) C = 100 * np.cos(self.homeangle) dl.add_line(rectmin[0] + h[0] * scale, rectmin[1] + h[1] * scale, rectmin[0] + h[0] * scale + C, rectmin[1] + h[1] * scale - S, imgui.get_color_u32_rgba(1, 1, 1, 1)) self.render_turns(scale, rectmin) self.render_opttrack(scale, rectmin) if self.editmode == "cone": zoomtip(self.maptex, self.mapim.shape, 2)
def drawTools(self): imgui.begin("Drawing Tools") if imgui.button("Reset", 207, 20): self.color = .0, .0, .0 self.drawMode = "" self.vrad = 0 self.hrad = 0 self.x_center = 400 self.y_center = 300 if imgui.button( "Circle", 100, 20 ): # imgui.core.button, https://github.com/ocornut/imgui/issues/2481 self.drawMode = "c" imgui.same_line(115) if imgui.button("Ellipse", 100, 20): self.drawMode = "e" imgui.new_line() if self.drawMode == "c": changed, self.vrad = imgui.input_int("Radius", self.vrad, 1, 100) # imgui.core.input_int changed, self.x_center = imgui.slider_int( "X-axis center", self.x_center, 0, 800) # imgui.core.slider_int, set max to window size changed, self.y_center = imgui.slider_int("Y-axis center", self.y_center, 0, 600) changed, self.color = imgui.color_edit3( "Set Color", *self.color) # asterisk used for tuple, I think... elif self.drawMode == "e": changed, self.vrad = imgui.input_int("Vertical Radius", self.vrad, 1, 100) # imgui.core.input_int # changed, self.vrad = imgui.slider_int("", self.vrad, 0, 1000) changed, self.hrad = imgui.input_int("Horizontal Radius", self.hrad, 1, 100) # changed, self.hrad = imgui.slider_int("Horizontal Radius", self.hrad, 0, 1000) changed, self.x_center = imgui.slider_int( "X-axis center", self.x_center, 0, 800) # imgui.core.slider_int, set max to window size changed, self.y_center = imgui.slider_int("Y-axis center", self.y_center, 0, 600) changed, self.color = imgui.color_edit3( "Set Color", *self.color) # asterisk used for tuple, I think... imgui.new_line imgui.begin_child("Current Settings", border=True) # imgui.core.begin_child imgui.text("Currently Drawing: ") # imgui.core.text if self.drawMode == "c": imgui.same_line(200), imgui.text_colored( "Circle", 0, 1, 0) # imgui.core.same_line, imgui.core.text_colored imgui.text("Radius:"), imgui.same_line(200), imgui.text_colored( str(self.vrad), 0, 1, 0) imgui.text("X Position:"), imgui.same_line( 200), imgui.text_colored(str(self.x_center), 0, 1, 0) imgui.text("Y Position:"), imgui.same_line( 200), imgui.text_colored(str(self.y_center), 0, 1, 0) elif self.drawMode == "e": imgui.same_line(200), imgui.text_colored("Ellipse", 0, 1, 0) imgui.text("V. Radius:"), imgui.same_line(200), imgui.text_colored( str(self.vrad), 0, 1, 0) imgui.text("H. Radius:"), imgui.same_line(200), imgui.text_colored( str(self.hrad), 0, 1, 0) imgui.text("X Position:"), imgui.same_line( 200), imgui.text_colored(str(self.x_center), 0, 1, 0) imgui.text("Y Position:"), imgui.same_line( 200), imgui.text_colored(str(self.y_center), 0, 1, 0) else: imgui.text("Nothing Selected") imgui.end_child() imgui.end()
def displayInterface(self): imgui.begin_child("left_bottom", width=606, height=370) imgui.text("Watch Paths") imgui.begin_child("left_bottom", width=606, height=310, border=True) for path in list(self.watchInformation.keys()): imgui.push_text_wrap_position() imgui.text(path) imgui.same_line() if (imgui.button("- Remove Path")): del self.watchInformation[path] self.saveWatchInformation() imgui.end_child() imgui.text("Add new path:") addNewPathInputChanged, self.addingPathText = imgui.input_text( "##Path input", self.addingPathText, 2048) imgui.same_line() if (imgui.button("+ Add Path")): self.handleNewPathAdding() imgui.end_child() imgui.same_line() imgui.begin_child("file_dir_alerts") imgui.text("File/Directory Change Alerts") imgui.begin_child("file_dir_alerts_logger", border=True) for alert in self.alertsData: data = self.alertsData[alert] if (imgui.tree_node(data["timestamp"] + " " + data["path"])): imgui.indent() imgui.push_text_wrap_position() imgui.text("Change Path: " + data["path"]) if (os.path.isfile(data["path"])): if (imgui.tree_node("Last Content")): imgui.push_text_wrap_position() imgui.text(data["last-content"]) imgui.tree_pop() if (imgui.tree_node("New Content")): imgui.push_text_wrap_position() imgui.text(data["new-content"]) imgui.tree_pop() if (os.path.isdir(data["path"])): if (imgui.tree_node("Last Content")): if (imgui.tree_node( "Files (" + str(len(data["last-content"]["files"])) + ")")): for file in data["last-content"]["files"]: imgui.push_text_wrap_position() imgui.text(file) imgui.tree_pop() if (imgui.tree_node( "Directories (" + str(len(data["last-content"]["directories"])) + ")")): for file in data["last-content"]["directories"]: imgui.push_text_wrap_position() imgui.text(file) imgui.tree_pop() imgui.tree_pop() if (imgui.tree_node("New Content")): if (imgui.tree_node( "Files (" + str(len(data["new-content"]["files"])) + ")")): for file in data["new-content"]["files"]: imgui.push_text_wrap_position() imgui.text(file) imgui.tree_pop() if (imgui.tree_node( "Directories (" + str(len(data["new-content"]["directories"])) + ")")): for file in data["new-content"]["directories"]: imgui.push_text_wrap_position() imgui.text(file) imgui.tree_pop() imgui.tree_pop() imgui.tree_pop() imgui.unindent() imgui.end_child() imgui.end_child()
def render(self): imgui.render() self.impl.render(imgui.get_draw_data()) imgui.new_frame() # --Imgui Windows-- # --Note: Variables are defined in __init__ under Imgui Window Variables if self.showPlayerControls: imgui.begin("Player Controls") imgui.text("Current State:") imgui.text(wire_sponge.curState.name) imgui.new_line() imgui.begin_child("movement", 320, 180, border=True) imgui.text("Movement") if imgui.button("Turn to Opposite", 300, 20): if wire_sponge.facing == Facing.left: wire_sponge.facing == Facing.right else: wire_sponge.facing = Facing.left if imgui.button("Face Left", 140, 20): wire_sponge.facing = Facing.left imgui.same_line(spacing=20) if imgui.button("Face Right", 140, 20): wire_sponge.facing = Facing.right if imgui.button("Walk (Toggle)", 300, 20): pass if imgui.button("Walk Left", 140, 20): pass imgui.same_line(spacing=20) if imgui.button("Walk Right", 140, 20): pass if imgui.button("Jump", 300, 20): if wire_sponge.on_ground: wire_sponge.setState(SpongeState.leapBegin) wire_sponge.on_ground = False imgui.new_line() imgui.end_child() imgui.begin_child("skills", 320, 120, border=True) imgui.text("Attacks and Skills") if imgui.button("Attack", 300, 20): if wire_sponge.chain.curState == ChainState.NaN \ and wire_sponge.curState != SpongeState.throwHrz \ and wire_sponge.curState != SpongeState.throwHrzRelease \ and wire_sponge.curState != SpongeState.throwHrzPullGo: wire_sponge.setState(SpongeState.throwHrzBegin) if imgui.button("Chain Spin", 300, 20): if wire_sponge.on_ground and wire_sponge.curState != SpongeState.spin: wire_sponge.setState(SpongeState.spin) if imgui.button("Thunder Dance", 300, 20): pass imgui.new_line() imgui.end_child() imgui.end() if self.showDummyControls: imgui.begin("Dummy Controls") imgui.begin_child("spawn", 320, 80, border=True) imgui.text("Spawn Controls") if imgui.button("Respawn", 300, 20): pass if imgui.button("Spawn", 140, 20): pass imgui.same_line(spacing=20) if imgui.button("Despawn", 140, 20): pass imgui.new_line() imgui.end_child() imgui.begin_child("behaviour", 320, 80, border=True) imgui.text("Behaviour Controls") changed, self.actStand = imgui.checkbox("Stand", self.actStand) changed, self.actMove = imgui.checkbox("Move", self.actMove) changed, self.actAttack = imgui.checkbox("Attack", self.actAttack) imgui.new_line() imgui.end_child() imgui.end() if self.showControlHelp: imgui.begin("Control Help") imgui.text("Arrow Keys: Move") imgui.text("Space: Jump") imgui.text("Z: Thunder Dance") imgui.text("X: Spin Chain") imgui.text("C: Attack") imgui.end() if self.showTestWindow: imgui.begin("Test Window") imgui.text("This is the test window.") changed, self.test_checkbox = imgui.checkbox("Test Checkbox", self.test_checkbox) if imgui.button("Test Button", 100, 20): pass changed, self.test_input_int = imgui.input_int("Integer Input Test", self.test_input_int) imgui.end() # --This is where the fun begins-- if imgui.begin_main_menu_bar(): if imgui.begin_menu("Application", True): selected_test, clicked_test = imgui.menu_item( "Test Window", "", False, True ) if clicked_test: if not self.showTestWindow: self.showTestWindow = True else: self.showTestWindow = False if selected_test: pass selected_quit, clicked_quit = imgui.menu_item( "Quit", "", False, True ) if clicked_quit: exit(0) if selected_quit: pass imgui.end_menu() if imgui.begin_menu("Controls", True): selected_reset, clicked_reset = imgui.menu_item( "Reset All", "", False, True ) if clicked_reset: pass if selected_reset: pass selected_player, clicked_player = imgui.menu_item( "Player", "", False, True ) if clicked_player: if not self.showPlayerControls: self.showPlayerControls = True else: self.showPlayerControls = False if selected_player: pass selected_dummy, clicked_dummy = imgui.menu_item( "Dummy", "", False, True ) if clicked_dummy: if not self.showDummyControls: self.showDummyControls = True else: self.showDummyControls = False if selected_dummy: pass imgui.end_menu() if imgui.begin_menu("Help", True): selected_controls, clicked_controls = imgui.menu_item( "Keyboard Controls", "", False, True ) if clicked_controls: if self.showControlHelp: self.showControlHelp = False else: self.showControlHelp = True if selected_controls: pass selected_about, clicked_about = imgui.menu_item( "About", "", False, True ) if clicked_about: if self.showAbout: self.showAbout = False else: self.showAbout = True if selected_about: pass imgui.end_menu() imgui.end_main_menu_bar() imgui.end_frame()
def displayInterface(self): imgui.begin_child("left_bottom", width=606, height=370) if (self.activeInterface == "main"): imgui.text("Main Interface (SSH)") imgui.begin_child("left_bottom", width=606, height=290, border=True) imgui.begin_child("connections", width=606) imgui.columns(4, 'ssh_connections') imgui.text("ID") imgui.next_column() imgui.text("USER") imgui.next_column() imgui.text("IP") imgui.next_column() imgui.text("Time Connected") imgui.separator() imgui.set_column_width(0, 70) for conn in list(self.activeConnections.keys()): now = datetime.now() elapsed = now - self.activeConnections[conn]["connected_time"] imgui.next_column() imgui.text(self.activeConnections[conn]["ssh_proc"]) imgui.next_column() imgui.text(self.activeConnections[conn]["user"]) imgui.next_column() imgui.text(self.activeConnections[conn]["ip"]) imgui.next_column() imgui.text(str(elapsed)) imgui.columns(1) imgui.end_child() imgui.end_child() imgui.text("Select a SSH Session") clicked, current = imgui.combo("##Path input", self.sshSelected, self.sshSelectionOptions) if (clicked): self.sshSelected = current if (imgui.button("Kick")): ssh_proc = self.sshSelectionOptions[ self.sshSelected].split()[0][1:-1] log.logNorm("Kicked SSH Session (" + ssh_proc + ") " + self.activeConnections[ssh_proc]["user"]) self.disconnectSSHConnection(ssh_proc) imgui.same_line() if (imgui.button("Ban Both")): self.handleBanningUser() self.handleBanningIPAddr() self.handleDisconnectingCurrentSelection() imgui.same_line() if (imgui.button("Ban User")): self.handleBanningUser() self.handleDisconnectingCurrentSelection() imgui.same_line() if (imgui.button("Ban IP")): self.handleBanningIPAddr() self.handleDisconnectingCurrentSelection() elif (self.activeInterface == "ban"): imgui.text("Ban List (SSH)") imgui.begin_child("left_bottom", width=299, height=310, border=True) imgui.columns(2, 'ssh_connections') imgui.text("USERNAME") imgui.next_column() imgui.next_column() imgui.separator() for user in self.banList["users"]: imgui.text(user) imgui.next_column() imgui.columns(1) imgui.end_child() imgui.same_line() imgui.begin_child("right_bottom", width=299, height=310, border=True) imgui.text("IP Address") imgui.next_column() imgui.next_column() imgui.separator() for user in self.banList["ip_addresses"]: imgui.text(user) imgui.next_column() imgui.columns(1) imgui.end_child() imgui.begin_child("left_selection", width=299) clicked, current = imgui.combo("##Path input", self.banUserSelected, self.banList["users"]) imgui.same_line() if (imgui.button("Unban")): self.alert("Unbanning User (" + self.banList["users"][self.banUserSelected] + ")") del self.banList["users"][self.banUserSelected] self.saveBanList() imgui.end_child() imgui.same_line() imgui.begin_child("right_selection", width=299) clicked, current = imgui.combo("##Path input", self.banIPSelected, self.banList["ip_addresses"]) imgui.same_line() if (imgui.button("Unban")): self.alert("Unbanning IP (" + self.banList["ip_addresses"][self.banIPSelected] + ")") del self.banList["ip_addresses"][self.banIPSelected] self.saveBanList() imgui.end_child() imgui.end_child() imgui.same_line() imgui.begin_child("ssh_alerts") imgui.text("SSH Connections Alerts") imgui.begin_child("ssh_alerts_logger", border=True) for message in self.alerts: imgui.text_wrapped(message) imgui.end_child() imgui.end_child()
def render_inspector_ast ( self ): imgui.begin_child( "inspector", 0, 0, border = True ) if self.parsedTree != None: self.render_inspector( self.parsedTree ) imgui.end_child()
def main(): global width_library global width_shematic global width_context global height_window global previous_key_callback global selected_link global selected_node global iggraph global node_library global debug_is_mouse_dragging global show_debug_window # states ------------------------- scrolling = imgui.Vec2(0, 0) iggraph = IGGraph(node_library) # iggraph.reset() node_hovered_in_scene = -1 parameter_link_start = None selected_parameter = None io_hovered = None io_anchors_width_not_hovered = 10 io_anchors_width_hovered = 15 right_splitter_is_active = False left_splitter_is_active = False image_width = 0 image_height = 0 image_texture = None # states ------------------------- imgui.create_context() window = impl_glfw_init() impl = GlfwRenderer(window) io = imgui.get_io() previous_key_callback = glfw.set_key_callback(window,key_event) init_textures() assign_parameter_colors(node_library) while not glfw.window_should_close(window): glfw.poll_events() impl.process_inputs() imgui.new_frame() if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_new, selected_new = imgui.menu_item( "New", 'Cmd+N', False, True ) if clicked_new: iggraph = IGGraph(node_library) clicked_load, selected_load = imgui.menu_item( "Load", 'Cmd+L', False, True ) if clicked_load: root = tk.Tk() root.withdraw() filename = filedialog.askopenfilename() if filename : f=open(filename) iggraph.from_json(json.load(f)) f.close() clicked_save, selected_save = imgui.menu_item( "Save", 'Cmd+S', False, True ) if clicked_save: iggraph.reset() graph_json = iggraph.to_json() text2save = json.dumps(graph_json, indent=4, sort_keys=True) root = tk.Tk() root.withdraw() f = filedialog.asksaveasfile(mode='w', defaultextension=".json") if f is None: # asksaveasfile return `None` if dialog closed with "cancel". return f.write(text2save) f.close() clicked_quit, selected_quit = imgui.menu_item( "Quit", 'Cmd+Q', False, True ) if clicked_quit: exit(0) imgui.end_menu() if imgui.begin_menu("Debug", True): show_debug_window_clicked, show_debug_window_selected = imgui.menu_item( "Show Debug window", 'Cmd+D', show_debug_window, True ) if show_debug_window_clicked: show_debug_window = not show_debug_window catch_exceptions_clicked, catch_exceptions_selected = imgui.menu_item( "Catch Exceptions", '', iggraph.catch_exceptions, True ) if catch_exceptions_clicked: iggraph.catch_exceptions = not iggraph.catch_exceptions imgui.separator() imgui.menu_item( "Examples", '', False, False ) show_example_mosaic_clicked, show_example_mosaic_selected = imgui.menu_item( "Mosaic", '', False, True ) if show_example_mosaic_clicked: example_mosaic(iggraph) imgui.end_menu() imgui.end_main_menu_bar() height_window = io.display_size.y - 18 # imgui.get_cursor_pos_y() imgui.push_style_var(imgui.STYLE_ITEM_SPACING, imgui.Vec2(0,0)) imgui.set_next_window_size(io.display_size.x, height_window) imgui.set_next_window_position(0, 18) imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0) imgui.begin("Splitter test", False, imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS) imgui.pop_style_var() imgui.pop_style_var() width_shematic = io.display_size.x - separator_width - width_context - separator_width - width_library # ============================================================================== # Library # ============================================================================== imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0) imgui.begin_child("Library", width_library, 0, True) for node_name in node_library.nodes: if imgui.button(node_name, width_library): iggraph.create_node(node_name) imgui.end_child() imgui.pop_style_var() imgui.same_line() imgui.button("left_splitter", separator_width, height_window - 20) left_splitter_is_active = imgui.is_item_active() if (left_splitter_is_active): width_library += io.mouse_delta.x scrolling = imgui.Vec2(scrolling.x - io.mouse_delta.x, scrolling.y) if (imgui.is_item_hovered()): imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW) imgui.same_line() # ============================================================================== # Shematic # ============================================================================== imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0) imgui.begin_child("shematic", width_shematic, 0, True) if show_inputs_popup(iggraph): imgui.open_popup("Outputs") show_outputs_popup(iggraph) # create our child canvas if iggraph.get_state() == iggraph.STATE_IDLE: imgui.text("status: edit | ") elif iggraph.get_state() == iggraph.STATE_RUNNING: imgui.text("status: run | ") imgui.same_line() if iggraph.get_state() == iggraph.STATE_IDLE: if imgui.button("run"): #TODO if not running iggraph.set_state(iggraph.STATE_RUNNING) iggraph.prepare_to_run() imgui.open_popup("User Input") imgui.same_line() if imgui.button("run one step"): iggraph.set_state(iggraph.STATE_RUNNING) iggraph.prepare_to_run() iggraph.run_one_step() elif iggraph.get_state() == iggraph.STATE_RUNNING: if imgui.button("stop running"): iggraph.reset() iggraph.set_state(iggraph.STATE_IDLE) imgui.same_line() if imgui.button("run one step"): iggraph.set_state(iggraph.STATE_RUNNING) iggraph.run_one_step() # imgui.same_line(imgui.get_window_width() - 100) imgui.push_style_var(imgui.STYLE_FRAME_PADDING, imgui.Vec2(1, 1)) imgui.push_style_var(imgui.STYLE_WINDOW_PADDING, imgui.Vec2(0, 0)) imgui.begin_child("scrolling_region", 0, 0, True, imgui.WINDOW_NO_SCROLLBAR | imgui.WINDOW_NO_MOVE) imgui.pop_style_var() imgui.pop_style_var() imgui.push_item_width(120.0) offset = add(imgui.get_cursor_screen_pos(), scrolling) draw_list = imgui.get_window_draw_list() # Display links draw_list.channels_split(2) draw_list.channels_set_current(0) for link in iggraph.links: draw_link_param_to_param(draw_list, offset, link.output_parameter, link.input_parameter, selected_link == link) # Display nodes parameter_link_end = None one_parameter_hovered = False one_node_moving_active = False for node in iggraph.nodes: imgui.push_id(str(node.id)) node_rect_min = add(offset, node.pos) draw_list.channels_set_current(1) # foreground old_any_active = imgui.is_any_item_active() #display node content first # todo test = add(node_rect_min, NODE_WINDOW_PADDING) imgui.set_cursor_screen_position(add(node_rect_min, NODE_WINDOW_PADDING)) imgui.begin_group() imgui.text("") imgui.text(node.name) imgui.text("") imgui.end_group() # save size node_widgets_active = False # (not old_any_active and imgui.is_any_item_active()) node.size = add( add( imgui.get_item_rect_size(), NODE_WINDOW_PADDING) , NODE_WINDOW_PADDING) node_rect_max = add(node.size, node_rect_min) #display node box draw_list.channels_set_current(0) # background imgui.set_cursor_screen_position(node_rect_min) imgui.invisible_button(str(node.id), node.size.x, node.size.y) if imgui.is_item_hovered(): node_hovered_in_scene = node.id else: node_hovered_in_scene = None node_moving_active = imgui.is_item_active() use_hovered_color = node_hovered_in_scene or selected_node == node draw_list.add_rect_filled(node_rect_min.x, node_rect_min.y, node_rect_max.x, node_rect_max.y, get_node_color(node, iggraph, use_hovered_color), 5) if node_hovered_in_scene and iggraph.is_error(node): imgui.begin_tooltip() imgui.text(iggraph.error_nodes[node]) imgui.end_tooltip() # input parameters for parameter_name in node.inputs: parameter = node.inputs[parameter_name] center = node.get_intput_slot_pos(parameter) center_with_offset = add(offset, center) if io_hovered == parameter: io_anchors_width = io_anchors_width_hovered else: io_anchors_width = io_anchors_width_not_hovered imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2)) imgui.push_id(str(str(node.id) + "input" + parameter.id)) if (imgui.invisible_button("input", io_anchors_width, io_anchors_width)): selected_parameter = parameter # imgui.is_item_hovered() does not work when dragging is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2)) if is_hovering: io_hovered = parameter one_parameter_hovered = True imgui.begin_tooltip() imgui.text(parameter_name) imgui.end_tooltip() if is_hovering and imgui.is_mouse_released(0): parameter_link_end = parameter imgui.pop_id() draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter)) # output parameters for parameter_name in node.outputs: parameter = node.outputs[parameter_name] center = node.get_output_slot_pos(parameter) center_with_offset = add(offset, center) if io_hovered == parameter: io_anchors_width = io_anchors_width_hovered else: io_anchors_width = io_anchors_width_not_hovered imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2)) imgui.push_id(str(str(node.id) + "output" + parameter.id)) if (imgui.invisible_button("output", io_anchors_width, io_anchors_width)): selected_parameter = parameter is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2)) if is_hovering: io_hovered = parameter one_parameter_hovered = True imgui.begin_tooltip() imgui.text(parameter_name) imgui.end_tooltip() draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter)) imgui.pop_id() # cannot use imgui.is_item_active, seems buggy with the scroll if is_hovering and imgui.is_mouse_down(0): parameter_link_start = parameter if node_widgets_active or node_moving_active: selected_node = node one_node_moving_active = True if node_moving_active and imgui.is_mouse_dragging(0) and node.id==selected_node.id: node.pos = add(node.pos, io.mouse_delta) debug_is_mouse_dragging = imgui.is_mouse_dragging(0) imgui.pop_id() draw_list.channels_merge() if not one_parameter_hovered: io_hovered = None # scrolling mouse_is_in_schematic = (io.mouse_pos.x > width_library) and\ (io.mouse_pos.x < (width_library + width_shematic)) and\ (io.mouse_pos.y < height_window) and\ (io.mouse_pos.y > 18) if not one_node_moving_active and\ not parameter_link_start and\ imgui.is_mouse_dragging(0) and\ mouse_is_in_schematic and\ not left_splitter_is_active and\ not right_splitter_is_active and\ imgui.is_window_focused(): scroll_offset = imgui.Vec2(io.mouse_delta.x, io.mouse_delta.y) scrolling = add(scrolling, scroll_offset) # link creation if parameter_link_start and parameter_link_end: iggraph.add_link(parameter_link_start, parameter_link_end) # creating link elif parameter_link_start and imgui.is_mouse_dragging(0): draw_link_param_to_point(draw_list, offset, parameter_link_start, io.mouse_pos.x, io.mouse_pos.y, True) # mouse release if imgui.is_mouse_released(0): parameter_link_start = None imgui.pop_item_width() imgui.end_child() # mouse click on the scene if imgui.is_mouse_clicked(0): mouse_pos = imgui.get_mouse_pos() local_mouse_pos = imgui.Vec2(mouse_pos.x - offset.x, mouse_pos.y - offset.y) selected_link = None for link in iggraph.links: start_node = link.output_parameter.owner start_pos = start_node.get_output_slot_pos(link.output_parameter) end_node = link.input_parameter.owner end_pos = end_node.get_intput_slot_pos(link.input_parameter) distance_mouse_start = math.sqrt(((local_mouse_pos.x-start_pos.x)**2) + ((local_mouse_pos.y-start_pos.y)**2)) distance_mouse_end = math.sqrt(((local_mouse_pos.x-end_pos.x)**2) + ((local_mouse_pos.y-end_pos.y)**2)) distance_start_end = math.sqrt(((start_pos.x-end_pos.x)**2) + ((start_pos.y-end_pos.y)**2)) if ((distance_mouse_start + distance_mouse_end) - distance_start_end) < 0.1: selected_link = link imgui.end_child() imgui.pop_style_var() imgui.same_line() imgui.button("right_splitter", separator_width, height_window - 20) right_splitter_is_active = imgui.is_item_active() if (right_splitter_is_active): width_context -= io.mouse_delta.x if (imgui.is_item_hovered()): imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW) # ============================================================================== # Context # ============================================================================== imgui.same_line() imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0) imgui.begin_child("child3", width_context, 0, True); if selected_node: if selected_node.handle_dynamic_parameters(): if imgui.button("add parameter"): selected_node.add_dynamic_parameter() if imgui.tree_node("Inputs"): for parameter_name in selected_node.inputs: parameter = selected_node.inputs[parameter_name] if imgui.tree_node(parameter.id): display_parameter(parameter, True) imgui.tree_pop() imgui.tree_pop() if imgui.tree_node("Output"): for parameter_name in selected_node.outputs: parameter = selected_node.outputs[parameter_name] if imgui.tree_node(parameter.id): display_parameter(parameter, False) imgui.tree_pop() imgui.tree_pop() imgui.end_child() imgui.pop_style_var() # imgui.end() # ============================================================================== # Debug Window # ============================================================================== if show_debug_window: debug_window_expanded, show_debug_window = imgui.begin("Debug", True) if parameter_link_start: imgui.text("parameter_link_start: " + parameter_link_start.id) else: imgui.text("parameter_link_start: " + "None") if selected_parameter: imgui.text("selected_parameter: " + selected_parameter.id) else: imgui.text("selected_parameter: " + "None") imgui.text("is_mouse_dragging: " + str(debug_is_mouse_dragging)) imgui.text("mouse: (" + str(io.mouse_pos.x) + ", " + str(io.mouse_pos.y) + ")") imgui.end() gl.glClearColor(1., 1., 1., 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) imgui.render() impl.render(imgui.get_draw_data()) glfw.swap_buffers(window) impl.shutdown() glfw.terminate()
def render_inspector_events ( self ): imgui.begin_child( "notes", 0, 0, border = True ) if self.player != None: for note in self.player.events: imgui.text( str( note ) ) imgui.end_child()
def main(): pygame.init() size = 800, 600 screen = pygame.display.set_mode(size, pygame.DOUBLEBUF | pygame.OPENGL) io = imgui.get_io() io.fonts.add_font_default() io.display_size = size renderer = PygameRenderer() clock = pygame.time.Clock() ## Test ####### # Setup OpenGL for 2D rendering glEnable(GL_TEXTURE_2D) glClearColor(0.0, 0.0, 0.0, 0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0, size[0], size[1], 0.0) # Important glMatrixMode(GL_MODELVIEW) # new pygame.Surface test = pygame.Surface((300, 300)) test_x = 100 test_y = 100 test.fill((255, 0, 0)) tex_id = None # pygame surface to OpenGL tex ix, iy = test.get_width(), test.get_height() image = pygame.image.tostring(test, "RGBA", True) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) tex_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_id) glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ############### while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit() renderer.process_event(event) # Start frame imgui.new_frame() if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_quit, selected_quit = imgui.menu_item( "Quit", 'Cmd+Q', False, True ) if clicked_quit: exit(1) imgui.end_menu() imgui.end_main_menu_bar() global cb_another, w_closable, dg_val if imgui.begin("Main window")[1]: imgui.begin_child("aaa", 300 , -10, border=False) imgui.begin_group() imgui.text("Toggle") _, cb_another = imgui.checkbox("Another Window", cb_another) imgui.text("Another Window state = {}".format(cb_another)) w_closable = cb_another imgui.end_group() imgui.begin_group() imgui.text("Example: drag float") changed, test_x = imgui.drag_float( "test_x", test_x, ) changed, test_y = imgui.drag_float( "test_y", test_y, ) imgui.text("Changed: {}, x: {:.2f} y: {:.2f}".format(changed, test_x, test_y)) imgui.end_group() imgui.end_child() imgui.end() # Disable perm if w_closable: _, w_closable = imgui.begin("Another window", False) # return (collapse, state) imgui.text("Bar") imgui.text_colored("Eggs", 0.2, 1., 0.) imgui.text("AAAA") imgui.end() # Clean screen glClearColor(0.5, 0.5, 0.5, 1) glClear(GL_COLOR_BUFFER_BIT) ## Draw ########## x = test_x y = test_y w = test.get_width() h = test.get_height() # Prepare the matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(x, y, 0.0) # shift to (x, y) glBindTexture(GL_TEXTURE_2D, tex_id) # Actual draw glBegin(GL_QUADS) glTexCoord2f(0.0, 1.0); glVertex3f(0.0, 0.0, 0.0) # Left top glTexCoord2f(1.0, 1.0); glVertex3f(w, 0.0, 0.0) # Right top glTexCoord2f(1.0, 0.0); glVertex3f(w, h, 0.0) # Right bottom glTexCoord2f(0.0, 0.0); glVertex3f(0.0, h, 0.0) # Left bottom glEnd() ################## imgui.render() pygame.display.flip() clock.tick(60)
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
def draw_lattice(self, L, name='lattice', index=None): imgui.begin_child(name, 0, self.lattice_height, border=True) win_pos = imgui.get_window_position() L = L.L # Calculate rank and node separation sizes. region_min = imgui.get_window_content_region_min() region_max = imgui.get_window_content_region_max() region_size = (region_max.x - region_min.x, region_max.y - region_min.y) n_r = len(L)+1 n_n = np.max([len(l) for l in L])+1 rank_sep = region_size[1] / n_r node_sep = region_size[0] / n_n radius = np.min([node_sep, rank_sep]) / 4 off_x = win_pos.x + region_min.x + node_sep off_y = win_pos.y + region_min.y + rank_sep draw_list = imgui.get_window_draw_list() # Create ranks manually pos = dict() rgb = np.array([255, 255, 102], float)/255 rgb = np.array([238, 210, 2], float)/255 color = imgui.get_color_u32_rgba(rgb[0], rgb[1], rgb[2], 1.0) offset = np.max([(len(l) - 1) * node_sep for l in L])/2 for i in range(len(L)): n_f = len(L[i]) l = (n_f - 1) * node_sep for j in range(len(L[i])): F = L[i][j] x = off_x + offset + -l/2 + j * node_sep y = off_y + rank_sep * i pos[F] = (x, y) draw_list.add_circle_filled(x, y, radius, color) # Create lattice thickness = 1 color = imgui.get_color_u32_rgba(rgb[0], rgb[1], rgb[2], 0.5) for i in range(len(L)): for j in range(len(L[i])): F = L[i][j] # f_n = names[F] # print(f_n) fx, fy = pos[F] if F.parents is None: continue for H in F.parents: # print(i,j) if H in pos: hx, hy = pos[H] draw_list.add_line(hx, hy, fx, fy, color, thickness) if index is not None: x, y = pos[L[index[0]][index[1]]] active = imgui.get_color_u32_rgba(1.0,0.0,0.0,1.0) draw_list.add_circle_filled(x, y, radius, active) imgui.end_child()
def main(self): """ This is the main loop. Most action happens here """ # This is the loop I was talking about while True: # Look for any user input self.renderer.handleinputs() # Create a new frame imgui.new_frame() # Get screen width and height self.width, self.height = self.renderer.io.display_size # Set the frame as big as the screen resolution imgui.set_next_window_size(self.width, self.height) # Put the frame in the top left corner imgui.set_next_window_position(0, 0) # Create a window in the frame we created ( Ignore pep8 for this line) imgui.begin("", flags=imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_SAVED_SETTINGS) # Version placeholder imgui.text("PyNx Terminal By PuffDip" + " - V" + str(self.version_number) + str(self.currentDir)) # This check looks if any menu is open # If so the terminal rescales so the menu fits on screen if \ self.keyboard_toggled or\ self.setting_toggle: # end check # Set the region so a new menu can fit imgui.begin_child("region", -5, -430, border=True) else: # Set terminal fullscreen if no menu has been found imgui.begin_child("region", -5, -110, border=True) # Show interpreter output on screen # If this is the first time the console need to show text if self.just_booted: # set boot bool to false if len(self.input) > 0: self.just_booted = False # Show version number imgui.text(self.CONSOLE_TEXT) else: #imgui.push_font(self.font) if self.cli_history: imgui.text("{}\n\n>>>\n{}".format( "\n".join(self.cli_history), self.input)) else: imgui.text(">>>\n{}".format(self.input)) #imgui.pop_font() # Make sure the screen stays fullscreen imgui.end_child() """ If the setting menu not is selected, most likely the user is in his keyboard layout We first want to check if the user is using the setting menu. After that we check if the user uses its keyboard. If so we render the keyboard. """ # Check if the setting page is toggled if not self.setting_toggle: # Render keyboard self.krender() # If the setting page is active show the setting page instead of rendering the keyboard else: self.srender() # Command line imgui.text("Keyboard: {} | Shift: {} | SYS: {}".format( self.keyboard_toggled, self.CAPS, self.SYS)) # Give a style to the button imgui.push_style_color(imgui.COLOR_BUTTON, *self.KEY_COLOR_LGRAY) # Create a button "Import" if imgui.button("Import", width=200, height=60): # Toggle Keyboard if not already if not self.keyboard_toggled: self.keyboard_toggled = True #self.input = "https://pastebin.com/" self.input = "dpaste:>>" # push style imgui.pop_style_color(1) imgui.same_line() # Give a style to the button imgui.push_style_color(imgui.COLOR_BUTTON, *self.KEY_COLOR_LGRAY) # Create a button "Export" if imgui.button("Export", width=200, height=60): export_check = "".join(self.utils.export(self.cli_history)) self.cli_history.append(export_check) # push style imgui.pop_style_color(1) imgui.same_line() # Give a style to the button imgui.push_style_color(imgui.COLOR_BUTTON, *self.KEY_COLOR_BLACK) # Create a button "Cursor" if imgui.button("...", width=200, height=60): pass # TODO Import a cursor method # push style imgui.pop_style_color(1) # Create the keyboard toggle button imgui.same_line() self.toggleKeyboard() # If settings was already opened close setting page if self.keyboard_toggled and self.setting_toggle: self.setting_toggle = False imgui.same_line() # Give a style to the button imgui.push_style_color(imgui.COLOR_BUTTON, *self.KEY_COLOR_LGRAY) # Create a button "Confirm" if the input from the user is higher then 0 if imgui.button("Confirm", width=200, height=60) and len(self.input) > 0: # If pastebin is used if self.input.startswith("dpaste:>>"): # Make a usable url url_redirecter = self.input.split(sep=":>>")[1] # Clear user input # generate url url = "http://dpaste.com/" + url_redirecter + ".txt" # Start to fetch the data self.input = self.utils.import_url(url) else: # Execute user command out, err, exc = self.python.execute(self.input) # Append user command to history self.input += "\n" self.cli_history.append(self.input) # Check whatever the result was of the command if out: self.input = out if err: self.input = err if exc: self.input = exc # total character limit on screen limit = 160 # Make sure history doesn't go off screen if len(self.input) >= limit: result = "" tmp_list = self.input.split("\n") for sentence in tmp_list: if len(sentence) >= limit: sentence = "\n".join([ sentence[i:i + limit] for i in range(0, len(sentence), limit) ]) result += sentence result += "\n" else: result += sentence result += "\n" self.input = result # Append result to history self.cli_history.append(self.input) # Clear variable to get used once more self.input = "" # Push style of the button imgui.pop_style_color(1) # On the same line we want our next object imgui.same_line() # Create a style for a new button imgui.push_style_color(imgui.COLOR_BUTTON, *self.KEY_COLOR_BGRAY) # Create a button "Settings" if imgui.button("S", width=40, height=40): # If the keyboard was toggled turn it off if self.keyboard_toggled: self.keyboard_toggled = False self.CAPS = False self.SYS = False # Finally render the settings self.toggle() # Push style of the button imgui.pop_style_color(1) imgui.end() imgui.render() self.renderer.render() # This function is needed else the switch crashes self.renderer.shutdown()
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