def to_invisible( widget: Gtk.Widget, duration: int = 600) -> bool: """Animate the opacity from 1 to 0 for duration in milliseconds.""" frame_clock = widget.get_frame_clock() start_time = frame_clock.get_frame_time() end_time = start_time + 1000*duration if hasattr(widget, 'anime_id') \ and widget.anime_id: widget.remove_tick_callback(widget.anime_id) def animate( widget: Gtk.Widget, frame_clock: Gdk.FrameClock) -> bool: current_time = frame_clock.get_frame_time() if current_time < end_time \ and widget.get_opacity() > 0: t = (current_time-start_time) / (end_time-start_time) t = 1 - Animation.ease_out_cubic(t) widget.set_opacity(t) return GLib.SOURCE_CONTINUE else: widget.anime_id = None return GLib.SOURCE_REMOVE widget.anime_id = widget.add_tick_callback(animate) return False
def register_widget(self, widget: Gtk.Widget, param_name: str, exportable: bool = True): if param_name in self._params: raise ValueError( "register_widget cannot overwrite existing parameters!") if isinstance(widget, Gtk.SpinButton): self._params[param_name] = widget.get_value() self._signal_ids[param_name] = widget.connect( "value-changed", self._spinbutton_value_changed_cb, param_name) elif isinstance(widget, Gtk.CheckButton): self._params[param_name] = widget.get_active() self._signal_ids[param_name] = widget.connect( "toggled", self._checkbutton_toggled_cb, param_name) elif isinstance(widget, Gtk.FileChooserButton): self._params[param_name] = widget.get_filename() self._signal_ids[param_name] = widget.connect( "selection-changed", self._filechooserbutton_selection_changed_cb, param_name) elif isinstance(widget, Gtk.Entry): #pylint: disable=used-before-assignment self._params[param_name] = tmp if (tmp := widget.get_text().strip( )) != "" else widget.get_placeholder_text() self._signal_ids[param_name] = widget.connect( "changed", self._entry_changed_cb, param_name)
def _process_control(self, control: Gtk.Widget, param: Pmd2PatchParameter) -> Union[int, str]: try: if param.type == Pmd2PatchParameterType.INTEGER or param.type == Pmd2PatchParameterType.STRING: assert isinstance(control, Gtk.Entry) control: Gtk.Entry value = control.get_text() if param.type == Pmd2PatchParameterType.INTEGER: return int(value) return value elif param.type == Pmd2PatchParameterType.SELECT: assert isinstance(control, Gtk.ComboBoxText) control: Gtk.ComboBoxText selected_id = control.get_active_id() for option in param.options: # We do it like this, because option.value has the correct type, # selected_id is always a string. if option.value == selected_id: return option.value raise TypeError("Unknown option " + selected_id) raise TypeError("Unknown parameter type " + param.type) except ValueError: raise PatchNotConfiguredError( _("Invalid values for some settings provided. Please try again." ), "*", _("Invalid values for some settings provided. Please try again." ))
def to_invisible(widget: Gtk.Widget, duration: int = 600) -> bool: """Animate the opacity from 1 to 0 for duration in milliseconds.""" frame_clock = widget.get_frame_clock() start_time = frame_clock.get_frame_time() end_time = start_time + 1000 * duration # Stop the current animating when the same widget requested to be # animated again before it has finished animating widget.animate = False def animate(widget: Gtk.Widget, frame_clock: Gdk.FrameClock) -> bool: widget.animate = True current_time = frame_clock.get_frame_time() if current_time < end_time \ and 0 < widget.get_opacity() \ and widget.animate: t = (current_time - start_time) / (end_time - start_time) t = 1 - Animation.ease_out_cubic(t) widget.set_opacity(t) return GLib.SOURCE_CONTINUE else: return GLib.SOURCE_REMOVE widget.add_tick_callback(animate) return False
def on_folder_rename_activated(self, sender: Gtk.Widget, title: str) -> None: sender.destroy() folder = self.document_grid.selected_folder if folder and self.storage.rename_folder(folder, title): self.document_grid.reload_items()
def __init__(self, entry: Gtk.Widget, history): self.entry = entry if isinstance(entry, Gtk.ComboBoxText): self.get_text = entry.get_active_text() elif isinstance(entry, Gtk.Entry): self.get_text = entry.get_text() UndoableTextContainer.__init__(self, self.entry, history)
def filter_library(self, widget: Gtk.Widget = None): self.__load_tile_states() if isinstance(widget, Gtk.Switch): self.show_installed_only = widget.get_active() elif isinstance(widget, Gtk.SearchEntry): self.search_string = widget.get_text() self.flowbox.set_filter_func(self.__filter_library_func)
def create_keep(gtkwidget: Gtk.Widget, isactive: bool): checkbutton = Gtk.CheckButton(halign=Gtk.Align.CENTER) if isactive: checkbutton.set_active(True) gtkwidget.set_opacity(0.3) checkbutton.connect('toggled', on_button_toggled, gtkwidget) return checkbutton
def get_surface_for_pixbuf(widget: Gtk.Widget, pixbuf: Optional[GdkPixbuf.Pixbuf])\ -> Optional[cairo.Surface]: """:returns: a cairo surface, if possible""" if not pixbuf: return None scale_factor = widget.get_scale_factor() return Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_factor, widget.get_window())
def on_folder_create_activated(self, sender: Gtk.Widget, title: str): sender.destroy() self.storage.add_folder(title, path=self.document_grid.current_folder_path) self.document_grid.reload_items( path=self.document_grid.current_folder_path) self.check_grid_items()
def cursor_change(w: Gtk.Widget, evt: Gdk.EventCrossing): cursor = None if evt.get_event_type() == Gdk.EventType.ENTER_NOTIFY: cursor = Gdk.Cursor.new_from_name(w.get_display(), "pointer") elif evt.get_event_type() == Gdk.EventType.LEAVE_NOTIFY: cursor = Gdk.Cursor.new_from_name(w.get_display(), "default") if cursor: w.get_window().set_cursor(cursor)
def hdl_response(dialog: Gtk.Widget, response: Gtk.ResponseType) -> None: del self.cancel_dialog dialog.destroy() self.progress_helper.disconnect(status_handler_id) if response == Gtk.ResponseType.YES: self.session.cancel_analyses()
def on_document_rename_activated(self, sender: Gtk.Widget, title: str): sender.destroy() doc = self.document_grid.selected_document or self.editor.document if not doc: return if storage.update(doc_id=doc.document_id, data={'title': title}): self.document_grid.reload_items()
def do_add(self, widget: Gtk.Widget): log.debug("widget=%r", widget) if widget in map(lambda ci: ci.widget, self._children): log.warning("Trying to add already added widget %r to %r", widget, self) else: widget.set_parent(self) self._children.append(self.ChildItem(widget)) self.queue_resize()
def snapshot_widget(root: Gtk.Widget) -> dict: style = root.get_style_context() snap = { 'type': type(root).__name__, 'label': get_label_for_widget(root), 'classes': style.list_classes()} if isinstance(root, Gtk.Container): snap['children'] = list(map(snapshot_widget, root.get_children())) return snap
def on_pref_apply(value_widgets: List[Gtk.Editable], apply_btn: Gtk.Widget) -> None: values = {w.get_name(): w.get_text() for w in value_widgets} new_config = validate_applet_config(**values) if isinstance(new_config, AppletConfig): if save_to_gsettings(mate_applet.get_preferences_path(), new_config): notify(ConfigUpdated(id(mate_applet.get_child()), new_config)) apply_btn.get_ancestor(Gtk.Dialog).close() else: logging.error(new_config) # TODO: display the error back
def __init__(self, contents: Gtk.Widget, parent: Gtk.ApplicationWindow, title: str): super().__init__( destroy_with_parent=True, transient_for=parent, window_position=Gtk.WindowPosition.NONE, border_width=5, title=title, ) self.add(contents) contents.show_all()
def snapshot_widget(root: Gtk.Widget) -> dict: style = root.get_style_context() snap = { 'type': type(root).__name__, 'label': get_label_for_widget(root), 'classes': style.list_classes() } if isinstance(root, Gtk.Container): snap['children'] = list(map(snapshot_widget, root.get_children())) return snap
def mouse_motion(widget: Gtk.Widget, event: Gdk.EventMotion): # world.player.x = round(event.x) # TODO we don't need round, just for testing purposes for the shadow # world.player.y = round(event.y) window_state.pointer_x = event.x window_state.pointer_y = event.y world.player.rotation = math.atan2(window_state.pointer_y - world.player.y, window_state.pointer_x - world.player.x) widget.queue_draw() client_protocol.send(type="position", x=world.player.x, y=world.player.y, rotation=world.player.rotation)
def animate( widget: Gtk.Widget, frame_clock: Gdk.FrameClock) -> bool: current_time = frame_clock.get_frame_time() if current_time < end_time \ and widget.get_opacity() > 0: t = (current_time-start_time) / (end_time-start_time) t = 1 - Animation.ease_out_cubic(t) widget.set_opacity(t) return GLib.SOURCE_CONTINUE else: widget.anime_id = None return GLib.SOURCE_REMOVE
def append_to_snapshot(cmd: lib.Command, snapshot: Gtk.Snapshot, x, y, widget: Gtk.Widget, colors: lib.icon.CommandColorScheme, code: lib.CodeBuffer = None) -> int: defin: lib.CommandDefinition = cmd.definition bg, fg = colors[defin.color] # Extend the width of the icon for icons with data data_layout, icon_width = _create_data_layout(cmd, widget) area = Graphene.Rect.init( Graphene.Rect(), x, y, icon_width * icon.WIDTH, icon.HEIGHT) # Background snapshot.append_color(bg, area) # Foreground icon if not (defin.data_only and cmd.data): if icon_width > 1: icon_area = Graphene.Rect.init( Graphene.Rect(), x + (icon_width - 1) * icon.WIDTH / 2, y, icon.WIDTH, icon.HEIGHT) else: icon_area = area defin.icon.snapshot(snapshot, icon_area, fg, widget.get_scale_factor()) # Data if cmd.data and defin.show_data: if defin.id == 'img' and code is not None: texture = code.get_command_data_preview(cmd) if texture is not None: t_scale = max( 1, texture.get_width() / area.get_width(), texture.get_height() / area.get_height()) ta_width = texture.get_width() / t_scale ta_height = texture.get_height() / t_scale t_area = Graphene.Rect.init( Graphene.Rect(), area.get_x() + area.get_width() / 2 - ta_width / 2, area.get_y() + area.get_height() / 2 - ta_height / 2, ta_width, ta_height) snapshot.append_texture(texture, t_area) if defin.id == 'color': data_color = utils.rgba(f'rgb({cmd.data})') layout = widget.create_pango_layout('⬤') _append_layout( snapshot, layout, icon.FONT_NORMAL, data_color, area) if data_layout: _append_layout( snapshot, data_layout, None, fg, area, 0 if defin.data_only else 5) return icon_width
def get_label_for_widget(widget: Gtk.Widget): my_label = None if hasattr(widget, 'get_label'): my_label = widget.get_label() # Mainly for the stackswitcher radio buttons if not my_label and hasattr(widget, 'get_child'): child = widget.get_child() if hasattr(child, 'get_label'): my_label = child.get_label() if not my_label and hasattr(widget, 'get_text'): my_label = widget.get_text() return my_label
def set_content(self, label: Gtk.Label, control: Gtk.Widget, control_expand: bool = True): h_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=64) self.add(h_box) h_box.pack_start(label, False, False, 0) h_box.pack_end(control, control_expand, control_expand, 0) label.set_margin_start(16) control.set_margin_end(16) if not control_expand: control.set_halign(Gtk.Align.END) self.set_size_request(-1, 48) self.show_all()
def find_child(widget: Gtk.Widget, child_name): """Find child widget by its name. Goes recursive if needed. :param widget: parent widget :param child_name: name of the widget :return: """ if widget.get_name() == child_name: return widget if hasattr(widget, 'get_children'): for child in widget.get_children(): _widget = find_child(child, child_name) if _widget: return _widget
def get_end_point( scroll: Gtk.ScrolledWindow, target: Gtk.Widget) -> int: talloc = target.get_allocation() adjustment = scroll.get_vadjustment() start_point = adjustment.get_value() page_size = adjustment.get_page_size() if start_point <= talloc.y \ and (talloc.y+talloc.height) <= (start_point+page_size): # If all parts of the target widget content are visible, # no need to animate the scroll. return -1 else: if talloc.y > start_point: # If the height of the target widget is greater than the # height of its container, scroll to the top-left # coordinates of the widget. Otherwise, scroll to the # bottom-right coordinates of the widget. if talloc.height > page_size: end_point = talloc.y else: end_point = min(adjustment.get_upper()-page_size, talloc.y+talloc.height-page_size) else: end_point = talloc.y return end_point
def __init__(self, widget: Gtk.Widget, color: Gdk.RGBA) -> None: super().__init__(1.0) self.widget = widget self.color = color self.sig = widget.connect_after("draw", self.on_draw)
def _draw(self, widget: Gtk.Widget, ctx: Context): height = widget.get_allocated_height() ctx.scale(20, height) ctx.rectangle(0, 0, 1, 1) set_rgb(ctx, self.color) ctx.fill()
def insert_image_link(self, widget: Gtk.Widget = None, link: str = None): if not link: return text = os.path.basename(link.strip()) with user_action(self.buffer): if self.buffer.get_has_selection(): (start, end) = self.buffer.get_selection_bounds() text = self.buffer.get_text(start, end, True) self.buffer.delete(start, end) self.buffer.insert(start, f'[{text}]({link})') else: self.buffer.insert_at_cursor(f'[{text}]({link})') if widget: widget.destroy()
def _do_init(self, footer_area: Gtk.Widget) -> Gtk.Widget: self._widget = Gtk.Grid() _, image_processor_area = self.new_component( image_processor_cs.factory( active_tool=self.presenter.bn_active_tool, tool_ids=[ ToolID.DROP_REGION, ToolID.SURFACE, ToolID.FOREGROUND_DETECTION, ], plugins=[ conan_drop_region_plugin_cs.factory( model=self.presenter.drop_region_plugin_model, z_index=DrawPriority.OVERLAY, ), conan_surface_plugin_cs.factory( model=self.presenter.surface_plugin_model, z_index=DrawPriority.OVERLAY, ), foreground_detection_plugin_cs.factory( model=self.presenter.foreground_detection_plugin_model, ), conan_preview_plugin_cs.factory( model=self.presenter.preview_plugin_model, z_index=DrawPriority.BACKGROUND, ), ] ) ) image_processor_area.show() self._widget.add(image_processor_area) self._widget.show() _, footer_inside = self.new_component( linear_navigator_footer_cs.factory( do_back=self.presenter.prev_page, do_next=self.presenter.next_page, next_label='Start analysis', ) ) footer_inside.show() footer_area.add(footer_inside) return self._widget
def override_color(widget: Gtk.Widget, fg: Color = None, bg: Color = None): """Widget needs provider prop""" if fg: fg = f"color: {fg.as_HEX()};" else: fg = "" if bg: bg = f"background-color: {bg.as_HEX()};" else: bg = "" css = f""" .override {{ {fg} {bg} }} textview text {{ {fg} {bg} }} """ widget.provider.load_from_data(bytes(css, encoding="UTF-8")) widget.get_style_context().add_provider( widget.provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) widget.get_style_context().add_class("override")
def get_modal_parent(widget: Gtk.Widget = None) -> Gtk.Window: if not widget: from meld.meldapp import app parent = app.get_active_window() elif not isinstance(widget, Gtk.Window): parent = widget.get_toplevel() else: parent = widget return parent
def messagedialog(parentwindow: Gtk.Widget, messagetype: Gtk.MessageType, title: str, detail: str): if not isinstance(parentwindow, Gtk.Window): parentwindow = parentwindow.get_toplevel() if not isinstance(parentwindow, Gtk.Window): parentwindow = None logger.warning('Cannot find toplevel window for dialog parent.') md = Gtk.Dialog(transient_for=parentwindow, title=title, modal=True, destroy_with_parent=True) ca = md.get_content_area() hb = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) ca.pack_start(hb, True, True, 0) img = Gtk.Image() img.set_valign(Gtk.Align.START) img.set_vexpand(False) img.set_vexpand_set(True) hb.pack_start(img, False, True, 0) if messagetype == Gtk.MessageType.QUESTION: img.set_from_icon_name('dialog-question', Gtk.IconSize.DIALOG) md.add_buttons('Cancel', Gtk.ResponseType.CANCEL, 'No', Gtk.ResponseType.NO, 'Yes', Gtk.ResponseType.YES) elif messagetype == Gtk.MessageType.ERROR: img.set_from_icon_name('dialog-error', Gtk.IconSize.DIALOG) md.add_buttons('OK', Gtk.ResponseType.OK) elif messagetype == Gtk.MessageType.WARNING: img.set_from_icon_name('dialog-warning', Gtk.IconSize.DIALOG) md.add_buttons('OK', Gtk.ResponseType.OK) elif messagetype == Gtk.MessageType.INFO: img.set_from_icon_name('dialog-information', Gtk.IconSize.DIALOG) md.add_buttons('OK', Gtk.ResponseType.OK) l = Gtk.Label(label=detail) l.set_valign(Gtk.Align.FILL) l.set_vexpand(True) l.set_vexpand_set(True) hb.pack_start(l, True, True, 0) ca.show_all() result = md.run() md.destroy() if result == Gtk.ResponseType.YES or result == Gtk.ResponseType.OK: return True elif result == Gtk.ResponseType.NO: return False else: return None
def bind_setting(self, widget: Gtk.Widget, prop: str, setting: str): widget.connect('notify::' + prop, self._on_property_change, (prop, setting)) self.settings_map[setting] = (widget, prop) self.settings[setting] = None
def __init__(self, button: Gtk.Widget, subreddit_name: str): self._subreddit_name = subreddit_name button.connect('clicked', self.__clicked_cb)
def _iter_all_widgets(root: Gtk.Widget): yield root if isinstance(root, Gtk.Container): for child in root.get_children(): yield from _iter_all_widgets(child)