def __init__(self, master, studio=None, **cnf): super().__init__(master, **cnf) self.update_defaults() self.__class__._instance = self if not self.__class__._view_mode: self.__class__._view_mode = StringVar(None, self.get_pref('mode')) self.__class__._transparency_flag = t = BooleanVar(None, self.get_pref('inactive_transparency')) self.__class__._side = side = StringVar(None, self.get_pref('side')) t.trace_add("write", lambda *_: self.set_pref('inactive_transparency', t.get())) self.studio = studio self._header = Frame(self, **self.style.dark, **self.style.dark_highlight_dim, height=30) self._header.pack(side="top", fill="x") self._header.pack_propagate(0) self._header.allow_drag = True Label(self._header, **self.style.dark_text_passive, text=self.name).pack(side="left") self._min = Button(self._header, image=get_icon_image("close", 15, 15), **self.style.dark_button, width=25, height=25) self._min.pack(side="right") self._min.on_click(self.minimize) self._pref = MenuButton(self._header, **self.style.dark_button) self._pref.configure(image=get_icon_image("settings", 15, 15)) self._pref.pack(side="right") self._pref.tooltip("Options") self._search_bar = SearchBar(self._header, height=20) self._search_bar.on_query_clear(self.on_search_clear) self._search_bar.on_query_change(self.on_search_query) menu = self.make_menu(( ("cascade", "View Mode", None, None, {"menu": ( ("radiobutton", "Docked", None, self.open_as_docked, {"variable": self._view_mode, "value": "docked"}), ("radiobutton", "Window", None, self.open_as_window, {"variable": self._view_mode, "value": "window"}), )}), ("cascade", "Position", None, None, {"menu": ( ("radiobutton", "Left", None, lambda: self.reposition("left"), {"variable": self._side, "value": "left"}), ("radiobutton", "Right", None, lambda: self.reposition("right"), {"variable": self._side, "value": "right"}), )}), EnableIf(lambda: self._view_mode.get() == 'window', ("cascade", "Window options", None, None, {"menu": ( ( "checkbutton", "Transparent when inactive", None, None, {"variable": self._transparency_flag}), )})), ("command", "Close", get_icon_image("close", 14, 14), self.minimize, {}), ("separator",), *self.create_menu() ), self._pref) self._pref.config(menu=menu) # self._pref.on_click(self.minimize) self.config(**self.style.dark) self.indicator = None self.window_handle = None self.on_focus(self._on_focus_get) self.on_focus_lost(self._on_focus_release) self.on_close(self.close_window) self._mode_map = { 'window': self.open_as_window, 'docked': self.open_as_docked }
def __init__(self, master, studio=None, **cnf): super().__init__(master, studio, **cnf) f = Frame(self, **self.style.dark) f.pack(side="top", fill="both", expand=True, pady=4) f.pack_propagate(0) self._variable_pane = ScrolledFrame(f, width=150) self._variable_pane.place(x=0, y=0, relwidth=0.4, relheight=1) self._detail_pane = ScrolledFrame(f, width=150) self._detail_pane.place(relx=0.4, y=0, relwidth=0.6, relheight=1, x=15, width=-20) self._search_btn = Button(self._header, image=get_icon_image("search", 15, 15), width=25, height=25, **self.style.dark_button) self._search_btn.pack(side="right") self._search_btn.on_click(self.start_search) self._add = MenuButton(self._header, **self.style.dark_button) self._add.configure(image=get_icon_image("add", 15, 15)) self._add.pack(side="right") self._delete_btn = Button(self._header, image=get_icon_image("delete", 15, 15), width=25, height=25, **self.style.dark_button) self._delete_btn.pack(side="right") self._delete_btn.on_click(self._delete) self._var_types_menu = self.make_menu(self._get_add_menu(), self._add) self._add.config(menu=self._var_types_menu) self._selected = None self._links = {} self._overlay = Label(f, **self.style.dark_text_passive, text="Add variables", compound="top") self._overlay.configure(image=get_icon_image("add", 25, 25)) self._show_overlay(True) self._editors = []
class BaseFeature(Frame): _instance = None name = "Feature" pane = None bar = None icon = "blank" _view_mode = None _transparency_flag = None _side = None rec = (20, 20, 300, 300) # Default window mode position _defaults = { "mode": "docked", "inactive_transparency": False, "position": "left", "visible": True, "side": "left", "pos": { "initialized": False, "x": 20, "y": 20, "width": 200, "height": 200, } } @classmethod def update_defaults(cls): path = "features::{}".format(cls.name) if not pref.exists(path): pref.set(path, dict(**cls._defaults)) else: pref.update_defaults(path, dict(**cls._defaults)) def __init__(self, master, studio=None, **cnf): super().__init__(master, **cnf) self.update_defaults() self.__class__._instance = self if not self.__class__._view_mode: self.__class__._view_mode = StringVar(None, self.get_pref('mode')) self.__class__._transparency_flag = t = BooleanVar(None, self.get_pref('inactive_transparency')) self.__class__._side = side = StringVar(None, self.get_pref('side')) t.trace_add("write", lambda *_: self.set_pref('inactive_transparency', t.get())) self.studio = studio self._header = Frame(self, **self.style.dark, **self.style.dark_highlight_dim, height=30) self._header.pack(side="top", fill="x") self._header.pack_propagate(0) self._header.allow_drag = True Label(self._header, **self.style.dark_text_passive, text=self.name).pack(side="left") self._min = Button(self._header, image=get_icon_image("close", 15, 15), **self.style.dark_button, width=25, height=25) self._min.pack(side="right") self._min.on_click(self.minimize) self._pref = MenuButton(self._header, **self.style.dark_button) self._pref.configure(image=get_icon_image("settings", 15, 15)) self._pref.pack(side="right") self._pref.tooltip("Options") self._search_bar = SearchBar(self._header, height=20) self._search_bar.on_query_clear(self.on_search_clear) self._search_bar.on_query_change(self.on_search_query) menu = self.make_menu(( ("cascade", "View Mode", None, None, {"menu": ( ("radiobutton", "Docked", None, self.open_as_docked, {"variable": self._view_mode, "value": "docked"}), ("radiobutton", "Window", None, self.open_as_window, {"variable": self._view_mode, "value": "window"}), )}), ("cascade", "Position", None, None, {"menu": ( ("radiobutton", "Left", None, lambda: self.reposition("left"), {"variable": self._side, "value": "left"}), ("radiobutton", "Right", None, lambda: self.reposition("right"), {"variable": self._side, "value": "right"}), )}), EnableIf(lambda: self._view_mode.get() == 'window', ("cascade", "Window options", None, None, {"menu": ( ( "checkbutton", "Transparent when inactive", None, None, {"variable": self._transparency_flag}), )})), ("command", "Close", get_icon_image("close", 14, 14), self.minimize, {}), ("separator",), *self.create_menu() ), self._pref) self._pref.config(menu=menu) # self._pref.on_click(self.minimize) self.config(**self.style.dark) self.indicator = None self.window_handle = None self.on_focus(self._on_focus_get) self.on_focus_lost(self._on_focus_release) self.on_close(self.close_window) self._mode_map = { 'window': self.open_as_window, 'docked': self.open_as_docked } @classmethod def get_pref_path(cls, short_path): return "features::{}::{}".format(cls.name, short_path) @classmethod def get_pref(cls, short_path): return pref.get(cls.get_pref_path(short_path)) @classmethod def set_pref(cls, short_path, value): pref.set(cls.get_pref_path(short_path), value) @classmethod def get_instance(cls): return cls._instance def start_search(self, *_): self._search_bar.place(relwidth=1, relheight=1) self._search_bar.lift() self._search_bar.focus_set() def quit_search(self, *_): self._search_bar.place_forget() def on_search_query(self, query: str): """ Called when inbuilt search feature is queried. Use the query string to display the necessary search results :param query: String of current search query :return: None """ pass def on_search_clear(self): """ Called when the user terminates the search bar. Ensure you make a call to the super method for the bar to actually get closed. This method can be used to restore the feature state to when not performing a search :return: """ self.quit_search() pass def on_select(self, widget): """ Called when a widget is selected in the designer :param widget: selected widget :return:None """ pass def on_widget_change(self, old_widget, new_widget=None): """ Called when a widget is fundamentally altered :param old_widget: Altered widget :param new_widget: The new widget taking the older widgets place :return: None """ pass def on_widget_layout_change(self, widget): """ Called when layout options of a widget are changed :param widget: Widget with altered layout options :return: None """ pass def on_widget_add(self, widget, parent): """ Called when a new widget is added to the designer :param widget: widget :param parent: the container widget to which thw widget is added :return: None """ pass def on_widget_delete(self, widget, silently=False): """ Called when a widget is deleted from the designer :param widget: deleted widget :param silently: flag indicating whether the deletion should be treated implicitly which is useful for instance when you don't want the deletion to be logged in the undo stack :return: None """ pass def on_widget_restore(self, widget): """ Called when a deleted widget is restored :param widget: restored widget :return: None """ pass def on_session_clear(self): """ Override to perform operations before a session is cleared and the studio resets to a new design :return: None """ pass def on_app_close(self) -> bool: """ Override to perform operations before the studio app closes. :return: True to allow shutdown to proceed or False to abort shutdown """ return True def minimize(self, *_): if self.window_handle: self.close_window() return self.studio.minimize(self) self.set_pref("visible", False) def maximize(self): if self.get_pref("mode") == "window": self.open_as_window() self.bar.select(self) else: self.studio.maximize(self) self.set_pref("visible", True) def toggle(self): if self.get_pref("visible"): self.minimize() else: self.maximize() def create_menu(self): """ Override this method to provide additional menu options :return: tuple of menu templates i.e. (type, label, image, callback, **additional_config) """ # return an empty tuple as default return () def _on_focus_release(self): if self._transparency_flag.get() and self.window_handle: if self.window_handle: self.window_handle.wm_attributes('-alpha', 0.3) if self.window_handle: self.save_window_pos() def _on_focus_get(self): if self.window_handle: self.window_handle.wm_attributes('-alpha', 1.0) def open_as_docked(self): self._view_mode.set("docked") self.set_pref('mode', 'docked') if self.window_handle: self.master.window.wm_forget(self) self.window_handle = None self.maximize() def reposition(self, side): self._side.set(side) self.studio.reposition(self, side) def open_as_window(self): if TkVersion < 8.5: logging.error("Window mode is not supported in current tk version") return self.master.window.wm_forget(self) rec = absolute_position(self) if not self.get_pref("pos::initialized") else ( self.get_pref("pos::x"), self.get_pref("pos::y"), self.get_pref("pos::width"), self.get_pref("pos::height"), ) self.window.wm_manage(self) # Allow us to create a hook in the close method of the window manager self.bind_close() self.title(self.name) self.transient(self.master.window) self.geometry('{}x{}+{}+{}'.format(rec[2], rec[3], rec[0], rec[1])) self.update_idletasks() self.window_handle = self self._view_mode.set("window") self.set_pref("mode", "window") self.studio._adjust_pane(self.pane) self.save_window_pos() if self.focus_get() != self and self.get_pref("inactive_transparency"): self.window_handle.wm_attributes('-alpha', 0.3) def save_window_pos(self): if not self.window_handle: return self.set_pref("pos", dict( x=self.winfo_x(), y=self.winfo_y(), width=self.width, height=self.height, initialized=True )) def close_window(self): if self.window_handle: # Store the current position of our window handle to used when it is reopened self.save_window_pos() self.master.window.wm_forget(self) self.window_handle = None self.studio.minimize(self) self.set_pref("visible", False)
def __init__(self, master, widget, menu=None): super().__init__(master, widget) self.title(f'Edit menu for {widget.id}') if not isinstance(menu, tk.Menu): menu = tk.Menu(widget, tearoff=False) widget.configure(menu=menu) self._base_menu = menu self._tool_bar = Frame(self, **self.style.dark, **self.style.dark_highlight_dim, height=30) self._tool_bar.pack(side="top", fill="x") self._tool_bar.pack_propagate(False) self._pane = PanedWindow(self, **self.style.dark_pane_horizontal) self._tree = MenuTree(self._pane, widget, menu) self._tree.allow_multi_select(True) self._tree.on_select(self._refresh_styles) self._tree.on_structure_change(self._refresh_styles) self._editor_pane = ScrolledFrame(self._pane) self._editor_pane_cover = Label(self._editor_pane, **self.style.dark_text_passive) self._editor_pane.pack(side="top", fill="both", expand=True) self._menu_item_styles = CollapseFrame(self._editor_pane.body) self._menu_item_styles.pack(side="top", fill="x", pady=4) self._menu_item_styles.label = "Menu Item attributes" self._menu_styles = CollapseFrame(self._editor_pane.body) self._menu_styles.pack(side="top", fill="x", pady=4) self._menu_styles.label = "Menu attributes" self._style_item_ref = {} self._menu_style_ref = {} self._prev_selection = None self._add = MenuButton(self._tool_bar, **self.style.dark_button) self._add.pack(side="left") self._add.configure(image=get_icon_image("add", 15, 15)) _types = MenuTree.Node._type_def menu_types = self._tool_bar.make_menu( [( tk.COMMAND, i.title(), get_icon_image(_types[i][0], 14, 14), functools.partial(self.add_item, i), {} ) for i in _types], self._add) menu_types.configure(tearoff=True) self._add.config(menu=menu_types) self._delete_btn = Button(self._tool_bar, image=get_icon_image("delete", 15, 15), **self.style.dark_button, width=25, height=25) self._delete_btn.pack(side="left") self._delete_btn.on_click(self._delete) self._preview_btn = Button(self._tool_bar, image=get_icon_image("play", 15, 15), **self.style.dark_button, width=25, height=25) self._preview_btn.pack(side="left") self._preview_btn.on_click(self._preview) self._pane.pack(side="top", fill="both", expand=True) self._pane.add(self._tree, minsize=350, sticky='nswe', width=350, height=500) self._pane.add(self._editor_pane, minsize=320, sticky='nswe', width=320, height=500) self.load_menu(menu, self._tree) self._show_editor_message(self._MESSAGE_EDITOR_EMPTY) self.enable_centering() self.focus_set() self._load_all_properties()
class MenuEditor(BaseToolWindow): # TODO Add context menu for nodes # TODO Add style search # TODO Handle widget change from the studio main control _MESSAGE_EDITOR_EMPTY = "No item selected" def __init__(self, master, widget, menu=None): super().__init__(master, widget) self.title(f'Edit menu for {widget.id}') if not isinstance(menu, tk.Menu): menu = tk.Menu(widget, tearoff=False) widget.configure(menu=menu) self._base_menu = menu self._tool_bar = Frame(self, **self.style.dark, **self.style.dark_highlight_dim, height=30) self._tool_bar.pack(side="top", fill="x") self._tool_bar.pack_propagate(False) self._pane = PanedWindow(self, **self.style.dark_pane_horizontal) self._tree = MenuTree(self._pane, widget, menu) self._tree.allow_multi_select(True) self._tree.on_select(self._refresh_styles) self._tree.on_structure_change(self._refresh_styles) self._editor_pane = ScrolledFrame(self._pane) self._editor_pane_cover = Label(self._editor_pane, **self.style.dark_text_passive) self._editor_pane.pack(side="top", fill="both", expand=True) self._menu_item_styles = CollapseFrame(self._editor_pane.body) self._menu_item_styles.pack(side="top", fill="x", pady=4) self._menu_item_styles.label = "Menu Item attributes" self._menu_styles = CollapseFrame(self._editor_pane.body) self._menu_styles.pack(side="top", fill="x", pady=4) self._menu_styles.label = "Menu attributes" self._style_item_ref = {} self._menu_style_ref = {} self._prev_selection = None self._add = MenuButton(self._tool_bar, **self.style.dark_button) self._add.pack(side="left") self._add.configure(image=get_icon_image("add", 15, 15)) _types = MenuTree.Node._type_def menu_types = self._tool_bar.make_menu( [( tk.COMMAND, i.title(), get_icon_image(_types[i][0], 14, 14), functools.partial(self.add_item, i), {} ) for i in _types], self._add) menu_types.configure(tearoff=True) self._add.config(menu=menu_types) self._delete_btn = Button(self._tool_bar, image=get_icon_image("delete", 15, 15), **self.style.dark_button, width=25, height=25) self._delete_btn.pack(side="left") self._delete_btn.on_click(self._delete) self._preview_btn = Button(self._tool_bar, image=get_icon_image("play", 15, 15), **self.style.dark_button, width=25, height=25) self._preview_btn.pack(side="left") self._preview_btn.on_click(self._preview) self._pane.pack(side="top", fill="both", expand=True) self._pane.add(self._tree, minsize=350, sticky='nswe', width=350, height=500) self._pane.add(self._editor_pane, minsize=320, sticky='nswe', width=320, height=500) self.load_menu(menu, self._tree) self._show_editor_message(self._MESSAGE_EDITOR_EMPTY) self.enable_centering() self.focus_set() self._load_all_properties() def _show_editor_message(self, message): # Show an overlay message self._editor_pane_cover.config(text=message) self._editor_pane_cover.place(x=0, y=0, relwidth=1, relheight=1) def _clear_editor_message(self): self._editor_pane_cover.place_forget() def _show(self, item): item.pack(fill="x", pady=1) def _hide(self, item): item.pack_forget() def _add_item(self, item): # add a menu item style editor self._style_item_ref[item.name] = item self._show(item) def _add_menu_item(self, item): # add a parent menu style editor self._menu_style_ref[item.name] = item self._show(item) def _load_all_properties(self): # Generate all style editors that may be needed by any of the types of menu items # This needs to be called only once ref = dict(PROPERTY_TABLE) ref.update(MENU_PROPERTY_TABLE) for prop in MENU_PROPERTIES: if not ref.get(prop): continue definition = dict(ref.get(prop)) definition['name'] = prop self._add_item(StyleItem(self._menu_item_styles, definition, self._on_item_change)) menu_prop = get_properties(self._base_menu) for key in menu_prop: definition = menu_prop[key] self._add_menu_item(StyleItem(self._menu_styles, definition, self._on_menu_item_change)) def _on_item_change(self, prop, value): # Called when the style of a menu item changes for node in self._tree.get(): menu_config(node._menu, node.get_index(), **{prop: value}) # For changes in label we need to change the label on the node as well node node.label = node._menu.entrycget(node.get_index(), 'label') def _on_menu_item_change(self, prop, value): nodes = self._tree.get() menus = set([node._menu for node in nodes]) for menu in menus: menu[prop] = value def _refresh_styles(self): # TODO Fix false value change when releasing ctrl key during multi-selecting # called when structure or selection changes nodes = self._tree.get() # get current selection if not nodes: # if no nodes are currently selected display message self._show_editor_message(self._MESSAGE_EDITOR_EMPTY) return self._clear_editor_message() # remove any messages # get intersection of styles for currently selected nodes # these will be the styles common to all the nodes selected, use sets for easy analysis styles = set(nodes[0].get_options().keys()) for node in nodes: styles &= set(node.get_options().keys()) # populate editors with values of the last item # TODO this is not the best approach, no value should be set for an option if it is not the same for all nodes node = nodes[-1] for style_item in self._style_item_ref.values(): # styles for menu items if style_item.name in styles: self._show(style_item) style_item.set(node.get_option(style_item.name)) else: self._hide(style_item) for style_item in self._menu_style_ref.values(): # styles for the menu style_item.set(node._menu.cget(style_item.name)) def _preview(self, *_): self.widget.event_generate("<Button-1>") def _delete(self, *_): # create a copy since the list may change during iteration selected = list(self._tree.get()) for node in selected: self._tree.deselect(node) node.remove() self._refresh_styles() def add_item(self, _type): label = f"{_type.title()}" selected = self._tree.get() if len(selected) == 1 and selected[0].type == tk.CASCADE: node = selected[0] else: node = self._tree if _type != tk.SEPARATOR: node._sub_menu.add(_type, label=label) else: node._sub_menu.add(_type) node.add_menu_item(type=_type, label=label, index=tk.END) def load_menu(self, menu, node): # if the widget has a menu we need to populate the tree when the editor is created # we do this recursively to be able to capture even cascades # we cannot directly access all items in a menu or its size # but we can get the index of the last item and use that to get size and hence viable indexes size = menu.index(tk.END) if size is None: # menu is empty return for i in range(size + 1): if menu.type(i) == tk.CASCADE: label = menu.entrycget(i, "label") # get the cascades sub-menu and load it recursively sub = self.nametowidget(menu.entrycget(i, "menu")) item_node = node.add_menu_item(type=menu.type(i), label=label, index=i, sub_menu=sub) self.load_menu(item_node._sub_menu, item_node) elif menu.type(i) == tk.SEPARATOR: # Does not need a label, set it to the default 'separator' node.add_menu_item(type=menu.type(i), index=i, label='separator') elif menu.type(i) != 'tearoff': # skip any tear_off item since they cannot be directly manipulated label = menu.entrycget(i, "label") node.add_menu_item(type=menu.type(i), label=label, index=i)
def __init__(self, master, studio=None, **cnf): super().__init__(master, studio, **cnf) f = Frame(self, **self.style.surface) f.pack(side="top", fill="both", expand=True, pady=4) f.pack_propagate(0) self._variable_pane = ScrolledFrame(f, width=150) self._variable_pane.place(x=0, y=0, relwidth=0.4, relheight=1) self._detail_pane = ScrolledFrame(f, width=150) self._detail_pane.place(relx=0.4, y=0, relwidth=0.6, relheight=1, x=15, width=-20) Label(self._detail_pane.body, **self.style.text_passive, text="Type", anchor="w").pack(side="top", fill="x") self.var_type_lbl = Label(self._detail_pane.body, **self.style.text, anchor="w") self.var_type_lbl.pack(side="top", fill="x") Label(self._detail_pane.body, **self.style.text_passive, text="Name", anchor="w").pack(side="top", fill="x") self.var_name = editors.get_editor(self._detail_pane.body, self._definitions["name"]) self.var_name.pack(side="top", fill="x") Label(self._detail_pane.body, **self.style.text_passive, text="Value", anchor="w").pack(fill="x", side="top") self._editors = {} self._editor = None self._search_btn = Button(self._header, image=get_icon_image("search", 15, 15), width=25, height=25, **self.style.button) self._search_btn.pack(side="right") self._search_btn.on_click(self.start_search) self._search_query = None self._add = MenuButton(self._header, **self.style.button) self._add.configure(image=get_icon_image("add", 15, 15)) self._add.pack(side="right") self._delete_btn = Button(self._header, image=get_icon_image("delete", 15, 15), width=25, height=25, **self.style.button) self._delete_btn.pack(side="right") self._delete_btn.on_click(self._delete) self._var_types_menu = self.make_menu(self._get_add_menu(), self._add, title="Add variable") self._var_types_menu.configure(tearoff=True) self._add.config(menu=self._var_types_menu) self._selected = None self._links = {} self._overlay = Label(f, **self.style.text_passive, text=self._empty_message, compound="top") self._overlay.configure(image=get_icon_image("add", 25, 25)) self._show_overlay(True)
class VariablePane(BaseFeature): name = "Variablepane" icon = "text" _defaults = {**BaseFeature._defaults, "side": "right"} _definitions = { "name": { "name": "name", "type": "text", } } _empty_message = "No variables added" def __init__(self, master, studio=None, **cnf): super().__init__(master, studio, **cnf) f = Frame(self, **self.style.surface) f.pack(side="top", fill="both", expand=True, pady=4) f.pack_propagate(0) self._variable_pane = ScrolledFrame(f, width=150) self._variable_pane.place(x=0, y=0, relwidth=0.4, relheight=1) self._detail_pane = ScrolledFrame(f, width=150) self._detail_pane.place(relx=0.4, y=0, relwidth=0.6, relheight=1, x=15, width=-20) Label(self._detail_pane.body, **self.style.text_passive, text="Type", anchor="w").pack(side="top", fill="x") self.var_type_lbl = Label(self._detail_pane.body, **self.style.text, anchor="w") self.var_type_lbl.pack(side="top", fill="x") Label(self._detail_pane.body, **self.style.text_passive, text="Name", anchor="w").pack(side="top", fill="x") self.var_name = editors.get_editor(self._detail_pane.body, self._definitions["name"]) self.var_name.pack(side="top", fill="x") Label(self._detail_pane.body, **self.style.text_passive, text="Value", anchor="w").pack(fill="x", side="top") self._editors = {} self._editor = None self._search_btn = Button(self._header, image=get_icon_image("search", 15, 15), width=25, height=25, **self.style.button) self._search_btn.pack(side="right") self._search_btn.on_click(self.start_search) self._search_query = None self._add = MenuButton(self._header, **self.style.button) self._add.configure(image=get_icon_image("add", 15, 15)) self._add.pack(side="right") self._delete_btn = Button(self._header, image=get_icon_image("delete", 15, 15), width=25, height=25, **self.style.button) self._delete_btn.pack(side="right") self._delete_btn.on_click(self._delete) self._var_types_menu = self.make_menu(self._get_add_menu(), self._add, title="Add variable") self._var_types_menu.configure(tearoff=True) self._add.config(menu=self._var_types_menu) self._selected = None self._links = {} self._overlay = Label(f, **self.style.text_passive, text=self._empty_message, compound="top") self._overlay.configure(image=get_icon_image("add", 25, 25)) self._show_overlay(True) def start_search(self, *_): if self.variables: super().start_search() self._variable_pane.scroll_to_start() def on_search_query(self, query): matches = [] self._variable_pane.clear_children() for item in self.variables: if query in item.name: self._show(item) matches.append(item) if not matches: self._show_overlay(True, text="No matches found", image=get_icon_image("search", 25, 25)) else: self.select(matches[0]) self._show_overlay(False) self._search_query = query def on_search_clear(self): self.on_search_query("") self._search_query = None # remove overlay if we have variables otherwise show it self._show_overlay(not self.variables) super().on_search_clear() def _get_add_menu(self): _types = VariableItem._types return [(tk.COMMAND, _types[i].get("name"), get_icon_image(_types[i].get("icon"), 14, 14), functools.partial(self.menu_add_var, i), {}) for i in _types] def create_menu(self): return ( ("cascade", "Add", get_icon_image("add", 14, 14), None, { "menu": self._get_add_menu() }), ("command", "Delete", get_icon_image("delete", 14, 14), self._delete, {}), ("command", "Search", get_icon_image("search", 14, 14), self.start_search, {}), ) def _show_overlay(self, flag=True, **kwargs): if flag: kwargs["text"] = kwargs.get("text", self._empty_message) kwargs["image"] = kwargs.get("image", get_icon_image("add", 25, 25)) self._overlay.lift() self._overlay.configure(**kwargs) self._overlay.place(x=0, y=0, relwidth=1, relheight=1) else: self._overlay.place_forget() def menu_add_var(self, var_type, **kw): item = self.add_var(var_type, **kw) self.select(item) def add_var(self, var_type, **kw): var = var_type(self.studio) item_count = len( list(filter(lambda x: x.var_type == var_type, self.variables))) + 1 name = kw.get('name', f"{var_type.__name__}_{item_count}") value = kw.get('value') item = VariableItem(self._variable_pane.body, var, name) item.bind("<Button-1>", lambda e: self.select(item)) if value is not None: item.set(value) self._show(item) self._show_overlay(False) if self._search_query is not None: # reapply search if any self.on_search_query(self._search_query) elif not self.variables: self.select(item) VariableManager.add(item) return item def delete_var(self, var): self._hide(var) VariableManager.remove(var) def _delete(self, *_): if self._selected: self.delete_var(self._selected) if self.variables: self.select(self.variables[0]) else: self._show_overlay(True) def clear_variables(self): # the list is likely to change during iteration, create local copy variables = list(self.variables) for var in variables: self.delete_var(var) self._show_overlay(True) @property def variables(self): return VariableManager.variables() def select(self, item): if item == self._selected: return item.select() if self._selected: self._selected.deselect() self._selected = item self._detail_for(item) def _show(self, item): item.pack(side="top", fill="x") def _hide(self, item): item.pack_forget() def _get_editor(self, variable): editor_type = variable.definition["type"] if not self._editors.get(editor_type): # we do not have that type of editor yet, create it self._editors[editor_type] = editors.get_editor( self._detail_pane.body, variable.definition) return self._editors[editor_type] def refresh(self): # redraw variables for current context self._variable_pane.body.clear_children() has_selection = False if not self.variables: self._show_overlay(True) else: self._show_overlay(False) for item in self.variables: self._show(item) if not has_selection: self.select(item) has_selection = True # reapply search query if any if self._search_query is not None: self.on_search_query(self._search_query) def _detail_for(self, variable): _editor = self._get_editor(variable) if self._editor != _editor: # we need to change current editor completely if self._editor: self._editor.pack_forget() self._editor = _editor self._editor.set(variable.value) self._editor.pack(side="top", fill="x") self._editor.on_change(variable.set) self.var_name.set(variable.name) self.var_name.on_change(variable.set_name) self.var_type_lbl["text"] = variable.var_type_name def on_session_clear(self): self.clear_variables() def on_context_switch(self): VariableManager.set_context(self.studio.context) self.refresh()
class VariablePane(BaseFeature): name = "Variablepane" icon = "text" _defaults = {**BaseFeature._defaults, "side": "right"} _definitions = { "name": { "name": "name", "type": "text", } } def __init__(self, master, studio=None, **cnf): super().__init__(master, studio, **cnf) f = Frame(self, **self.style.dark) f.pack(side="top", fill="both", expand=True, pady=4) f.pack_propagate(0) self._variable_pane = ScrolledFrame(f, width=150) self._variable_pane.place(x=0, y=0, relwidth=0.4, relheight=1) self._detail_pane = ScrolledFrame(f, width=150) self._detail_pane.place(relx=0.4, y=0, relwidth=0.6, relheight=1, x=15, width=-20) self._search_btn = Button(self._header, image=get_icon_image("search", 15, 15), width=25, height=25, **self.style.dark_button) self._search_btn.pack(side="right") self._search_btn.on_click(self.start_search) self._add = MenuButton(self._header, **self.style.dark_button) self._add.configure(image=get_icon_image("add", 15, 15)) self._add.pack(side="right") self._delete_btn = Button(self._header, image=get_icon_image("delete", 15, 15), width=25, height=25, **self.style.dark_button) self._delete_btn.pack(side="right") self._delete_btn.on_click(self._delete) self._var_types_menu = self.make_menu(self._get_add_menu(), self._add) self._add.config(menu=self._var_types_menu) self._selected = None self._links = {} self._overlay = Label(f, **self.style.dark_text_passive, text="Add variables", compound="top") self._overlay.configure(image=get_icon_image("add", 25, 25)) self._show_overlay(True) self._editors = [] def start_search(self, *_): if len(self.variables): super().start_search() self._variable_pane.scroll_to_start() def on_search_query(self, query): matches = [] self._variable_pane.clear_children() for item in self.variables: if query in item.name: self._show(item) matches.append(item) if not len(matches): self._show_overlay(True, text="No matches found", image=get_icon_image("search", 25, 25)) else: self.select(matches[0]) self._show_overlay(False) def on_search_clear(self): self.on_search_query("") self._show_overlay(False) super().on_search_clear() def _get_add_menu(self): _types = VariableItem._types return [(tk.COMMAND, _types[i].get("name"), get_icon_image(_types[i].get("icon"), 14, 14), functools.partial(self.add_var, i), {}) for i in _types] def create_menu(self): return ( ("cascade", "Add", get_icon_image("add", 14, 14), None, { "menu": self._get_add_menu() }), ("command", "Delete", get_icon_image("delete", 14, 14), self._delete, {}), ("command", "Search", get_icon_image("search", 14, 14), self.start_search, {}), ) def _show_overlay(self, flag=True, **kwargs): if flag: self._overlay.lift() self._overlay.configure(**kwargs) self._overlay.place(x=0, y=0, relwidth=1, relheight=1) else: self._overlay.place_forget() def add_var(self, var_type, **kw): var = var_type(self.studio) item_count = len( list(filter(lambda x: x.var_type == var_type, self.variables))) + 1 name = kw.get('name', f"{var_type.__name__}_{item_count}") value = kw.get('value') item = VariableItem(self._variable_pane.body, var, name) item.bind("<Button-1>", lambda e: self.select(item)) if value is not None: item.set(value) VariableManager.add(item) self._show(item) self._show_overlay(False) self.select(item) def delete_var(self, var): self._hide(var) VariableManager.remove(var) def _delete(self, *_): if self._selected: self.delete_var(self._selected) if len(self.variables): self.select(self.variables[0]) else: self._show_overlay(True) def clear_variables(self): # the list is likely to change during iteration, create local copy variables = list(self.variables) for var in variables: self.delete_var(var) self._show_overlay(True) @property def variables(self): return VariableManager.variables def select(self, item): if item == self._selected: return item.select() if self._selected: self._selected.deselect() self._selected = item self._detail_for(item) def _show(self, item): item.pack(side="top", fill="x") def _hide(self, item): item.pack_forget() def _detail_for(self, variable): self._detail_pane.clear_children() Label(self._detail_pane.body, **self.style.dark_text_passive, text="Type", anchor="w").pack(fill="x", side="top") Label(self._detail_pane.body, **self.style.dark_text, text=variable.var_type_name, anchor="w").pack(fill="x", side="top") Label(self._detail_pane.body, **self.style.dark_text_passive, text="Name", anchor="w").pack(fill="x", side="top") name = editors.get_editor(self._detail_pane.body, self._definitions["name"]) name.pack(side="top", fill="x") name.set(variable.name) name.on_change(variable.set_name) Label(self._detail_pane.body, **self.style.dark_text_passive, text="Value", anchor="w").pack(fill="x", side="top") value = editors.get_editor(self._detail_pane.body, variable.definition) value.set(variable.value) value.pack(side="top", fill="x") value.on_change(variable.set) def on_session_clear(self): self.clear_variables()
class BaseFeature(Pane): _instance = None name = "Feature" pane = None bar = None icon = "blank" _view_mode = None _transparency_flag = None _side = None rec = (20, 20, 300, 300) # Default window mode position _defaults = { "mode": "docked", "inactive_transparency": False, "position": "left", "visible": True, "side": "left", "pane": { "height": 300, "index": 1000, # setting 1000 allows the feature pane to pick an index }, "pos": { "initialized": False, "x": 20, "y": 20, "width": 200, "height": 200, } } @classmethod def update_defaults(cls): pref = Preferences.acquire() path = "features::{}".format(cls.name) if not pref.exists(path): pref.set(path, copy.deepcopy(cls._defaults)) else: pref.update_defaults(path, copy.deepcopy(cls._defaults)) def __init__(self, master, studio=None, **cnf): super().__init__(master, **cnf) self.update_defaults() self.__class__._instance = self if not self.__class__._view_mode: self.__class__._view_mode = StringVar(None, self.get_pref('mode')) self.__class__._transparency_flag = t = BooleanVar( None, self.get_pref('inactive_transparency')) self.__class__._side = StringVar(None, self.get_pref('side')) self.is_visible = BooleanVar(None, self.get_pref('visible')) t.trace_add( "write", lambda *_: self.set_pref('inactive_transparency', t.get())) self.studio = studio Label(self._header, **self.style.text_accent, text=self.name).pack(side="left") self._min = Button(self._header, image=get_icon_image("close", 15, 15), **self.style.button, width=25, height=25) self._min.pack(side="right") self._min.on_click(self.minimize) self._pref = MenuButton(self._header, **self.style.button) self._pref.configure(image=get_icon_image("settings", 15, 15)) self._pref.pack(side="right") self._pref.tooltip("Options") menu = self.make_menu( (("cascade", "View Mode", None, None, { "menu": ( ("radiobutton", "Docked", None, self.open_as_docked, { "variable": self._view_mode, "value": "docked" }), ("radiobutton", "Window", None, self.open_as_window, { "variable": self._view_mode, "value": "window" }), ) }), ("cascade", "Position", None, None, { "menu": ( ("radiobutton", "Left", None, lambda: self.reposition("left"), { "variable": self._side, "value": "left" }), ("radiobutton", "Right", None, lambda: self.reposition("right"), { "variable": self._side, "value": "right" }), ) }), EnableIf(lambda: self._view_mode.get() == 'window', ("cascade", "Window options", None, None, { "menu": (("checkbutton", "Transparent when inactive", None, None, { "variable": self._transparency_flag }), ) })), ("command", "Close", get_icon_image( "close", 14, 14), self.minimize, {}), ("separator", ), *self.create_menu()), self._pref) self._pref.config(menu=menu) # self._pref.on_click(self.minimize) self.config(**self.style.surface) self.indicator = None self.window_handle = None self.on_focus(self._on_focus_get) self.on_focus_lost(self._on_focus_release) self.on_close(self.close_window) self._mode_map = { 'window': self.open_as_window, 'docked': self.open_as_docked } @classmethod def get_pref_path(cls, short_path): return "features::{}::{}".format(cls.name, short_path) @classmethod def get_pref(cls, short_path): return Preferences.acquire().get(cls.get_pref_path(short_path)) @classmethod def set_pref(cls, short_path, value): Preferences.acquire().set(cls.get_pref_path(short_path), value) @classmethod def get_instance(cls): return cls._instance def on_select(self, widget): """ Called when a widget is selected in the designer :param widget: selected widget :return:None """ pass def on_widget_change(self, old_widget, new_widget=None): """ Called when a widget is fundamentally altered :param old_widget: Altered widget :param new_widget: The new widget taking the older widgets place :return: None """ pass def on_widget_layout_change(self, widget): """ Called when layout options of a widget are changed :param widget: Widget with altered layout options :return: None """ pass def on_widget_add(self, widget, parent): """ Called when a new widget is added to the designer :param widget: widget :param parent: the container widget to which thw widget is added :return: None """ pass def on_widget_delete(self, widget, silently=False): """ Called when a widget is deleted from the designer :param widget: deleted widget :param silently: flag indicating whether the deletion should be treated implicitly which is useful for instance when you don't want the deletion to be logged in the undo stack :return: None """ pass def on_widget_restore(self, widget): """ Called when a deleted widget is restored :param widget: restored widget :return: None """ pass def on_session_clear(self): """ Override to perform operations before a session is cleared and the studio resets to a new design :return: None """ pass def on_context_switch(self): """ Override to perform operations when the active tab changes """ pass def on_context_close(self, context): """ Override to perform operations when a tab context is closed """ pass def on_app_close(self) -> bool: """ Override to perform operations before the studio app closes. :return: True to allow shutdown to proceed or False to abort shutdown """ return True def minimize(self, *_): if self.window_handle: self.close_window() return self.studio.minimize(self) self.set_pref("visible", False) self.is_visible.set(False) def maximize(self): if self.get_pref("mode") == "window": self.open_as_window() self.bar.select(self) else: self.studio.maximize(self) self.set_pref("visible", True) self.is_visible.set(True) def toggle(self): if self.get_pref("visible"): self.minimize() else: self.maximize() def create_menu(self): """ Override this method to provide additional menu options :return: tuple of menu templates i.e. (type, label, image, callback, **additional_config) """ # return an empty tuple as default return () def _on_focus_release(self): if self._transparency_flag.get() and self.window_handle: if self.window_handle: self.window_handle.wm_attributes('-alpha', 0.3) if self.window_handle: self.save_window_pos() def _on_focus_get(self): if self.window_handle: self.window_handle.wm_attributes('-alpha', 1.0) def open_as_docked(self): self._view_mode.set("docked") self.set_pref('mode', 'docked') if self.window_handle: self.master.window.wm_forget(self) self.window_handle = None self.maximize() def reposition(self, side): self._side.set(side) self.studio.reposition(self, side) def open_as_window(self): if TkVersion < 8.5: logging.error("Window mode is not supported in current tk version") return self.master.window.wm_forget(self) rec = absolute_position( self) if not self.get_pref("pos::initialized") else ( self.get_pref("pos::x"), self.get_pref("pos::y"), self.get_pref("pos::width"), self.get_pref("pos::height"), ) self.window.wm_manage(self) # Allow us to create a hook in the close method of the window manager self.bind_close() self.title(self.name) self.geometry('{}x{}+{}+{}'.format(rec[2], rec[3], rec[0], rec[1])) self.update_idletasks() self.window_handle = self self._view_mode.set("window") self.set_pref("mode", "window") self.studio._adjust_pane(self.pane) self.transient(self.master.window) self.save_window_pos() if self.focus_get() != self and self.get_pref("inactive_transparency"): self.window_handle.wm_attributes('-alpha', 0.3) def save_window_pos(self): if not self.window_handle: if self.winfo_ismapped(): self.set_pref("pane::height", self.height) return self.update_idletasks() geometry = parse_geometry(self.geometry(), default=0) if geometry: # more accurate # cast geometry values returned to int self.set_pref( "pos", dict({k: int(v) for k, v in geometry.items()}, initialized=True)) else: raise Exception("Could not parse window geometry") def close_window(self): if self.window_handle: # Store the current position of our window handle to used when it is reopened self.save_window_pos() self.master.window.wm_forget(self) self.window_handle = None self.studio.minimize(self) self.set_pref("visible", False)