def init(options): # this is needed for py2exe if sys.platform == 'win32': os.environ['PATH'] += ";lib;bin;" from gi.repository import Gtk assert_python_version((2, 7)) Gtk.check_version(3, 4, 0)
def _set_terminal(self, terminal): """Set terminal font, colors, palette,... Arguments: * terminal -- the vte """ #General terminal.set_cursor_shape(CONF['general_cursor']) #Colors if CONF['color_palettename'] in PREDEF_PALETTE: colors = PREDEF_PALETTE[CONF['color_palettename']] elif CONF['color_palettename'] == "Custom": colors = CONF['color_palette'] else: colors = PREDEF_PALETTE['Tango'] if Gtk.check_version(3, 0, 0) is None: fg = Gdk.RGBA() fg.parse(CONF['color_text']) bg = Gdk.RGBA() bg.parse(CONF['color_background']) else: fg = Gdk.color_parse(CONF['color_text']) bg = Gdk.color_parse(CONF['color_background']) palette = [] for color in colors: if Gtk.check_version(3, 0, 0) is None: palette.append(Gdk.RGBA()) palette[-1].parse(color) else: palette.append(Gdk.color_parse(color)) terminal.set_colors(fg, bg, palette) #Font font = Pango.FontDescription(CONF['font_name']) terminal.set_font(font) terminal.set_allow_bold(CONF['font_allowbold'])
def update_state_in (self, *args): state = args[-1] if Gtk.check_version (3, 0, 0) is None: self.set_state (Gtk.StateFlags.PRELIGHT) else: self.set_state (Gtk.StateType.PRELIGHT) self.states[state] = True
def check_url_hovering(self, x, y): # Looks at all tags covering the position (x, y) in the text view, # and if one of them is a link return True # When check on_slow_mouse event, the position can be out # of the widget and return negative values. if x < 0 or y < 0: return False self.palette = None iter_tags = self.get_iter_at_location(x, y) if Gtk.check_version(3, 19, 8) is None: if not iter_tags[0]: return False iter_tags = iter_tags[1] tags = iter_tags.get_tags() for tag in tags: try: url = tag.url self.palette = tag.palette except: url = None if url is not None: return True return False
def apply_style(widget): name = nfoview.conf.color_scheme scheme = nfoview.schemes.get(name, "default") font_desc = Pango.FontDescription(nfoview.conf.font) # They f*****g broke theming again with GTK+ 3.22. unit = "pt" if Gtk.check_version(3, 22, 0) is None else "px" css = """ .nfoview-text-view, .nfoview-text-view text {{ background-color: {bg}; color: {fg}; font-family: {family}; font-size: {size}{unit}; font-weight: {weight}; }}""".format( bg=scheme.background, fg=scheme.foreground, family=font_desc.get_family().split(",")[0], size=int(round(font_desc.get_size() / Pango.SCALE)), unit=unit, weight=int(font_desc.get_weight()), ) css = css.replace("font-size: 0{unit};".format(unit=unit), "") css = css.replace("font-weight: 0;", "") css = "\n".join(filter(lambda x: x.strip(), css.splitlines())) provider = Gtk.CssProvider() provider.load_from_data(bytes(css.encode())) style = widget.get_style_context() style.add_class("nfoview-text-view") priority = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION style.add_provider_for_screen(Gdk.Screen.get_default(), provider, priority)
def apply_style(widget): name = nfoview.conf.color_scheme scheme = nfoview.schemes.get(name, "default") font_desc = Pango.FontDescription(nfoview.conf.font) # They f*****g broke theming again with GTK 3.22. unit = "pt" if Gtk.check_version(3, 22, 0) is None else "px" css = """ .nfoview-text-view, .nfoview-text-view text {{ background-color: {bg}; color: {fg}; font-family: {family}, monospace; font-size: {size}{unit}; font-weight: {weight}; }}""".format( bg=scheme.background, fg=scheme.foreground, family=font_desc.get_family().split(",")[0], size=int(round(font_desc.get_size() / Pango.SCALE)), unit=unit, # Round weight to hundreds to work around CSS errors # with weird weights such as Unscii's 101. weight=round(font_desc.get_weight(), -2), ) css = css.replace("font-size: 0{unit};".format(unit=unit), "") css = css.replace("font-weight: 0;", "") css = "\n".join(filter(lambda x: x.strip(), css.splitlines())) provider = Gtk.CssProvider() provider.load_from_data(bytes(css.encode())) style = widget.get_style_context() style.add_class("nfoview-text-view") priority = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION style.add_provider_for_screen(Gdk.Screen.get_default(), provider, priority)
def update_state_in(self, *args): state = args[-1] if Gtk.check_version(3, 0, 0) is None: self.set_state(Gtk.StateFlags.PRELIGHT) else: self.set_state(Gtk.StateType.PRELIGHT) self.states[state] = True
def sidebar(self): left_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.entry = Gtk.SearchEntry(placeholder_text=_("Search Tweaks…")) if (Gtk.check_version(3, 22, 20) == None): self.entry.set_input_hints(Gtk.InputHints.NO_EMOJI) self.entry.connect("search-changed", self._on_search) self.searchbar = Gtk.SearchBar() self.searchbar.add(self.entry) self.searchbar.props.hexpand = False self.listbox = Gtk.ListBox() self.listbox.get_style_context().add_class("tweak-categories") self.listbox.set_size_request(200, -1) self.listbox.connect("row-selected", self._on_select_row) self.listbox.set_header_func(self._list_header_func, None) scroll = Gtk.ScrolledWindow() scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) scroll.add(self.listbox) left_box.pack_start(self.searchbar, False, False, 0) left_box.pack_start(scroll, True, True, 0) self.hsize_group.add_widget(left_box) return left_box
def __event_after_cb(self, widget, event): if event.type.value_name != 'GDK_BUTTON_RELEASE': return False x, y = self.window_to_buffer_coords(Gtk.TextWindowType.WIDGET, int(event.x), int(event.y)) iter_tags = self.get_iter_at_location(x, y) if Gtk.check_version(3, 19, 8) is None: if not iter_tags[0]: return False iter_tags = iter_tags[1] for tag in iter_tags.get_tags(): try: url = tag.url except: url = None if url is not None: if event.button == 3: palette = tag.palette xw, yw = self.get_toplevel().get_pointer() palette.popup() else: self._show_via_journal(url) break return False
def _configure_settings_plugin_options(self, plugin_klass): plugin_config = self.config['plugins'].get(plugin_klass.name) or {} # use or instead of get incase the value is actually None frame = Gtk.Frame() self.gobjects['box_plugin_options'].pack_start(frame, True, True, 0) frame.set_label(plugin_klass.title) grid = Gtk.Grid() frame.add(grid) if Gtk.check_version(3, 12, 0): grid.set_property('margin-left', 12) else: grid.set_property('margin-start', 12) grid.set_property('column-spacing', 3) grid.set_property('row-spacing', 3) grid.insert_column(0) grid.insert_column(0) for row, opt in enumerate(plugin_klass.options): grid.insert_row(row) name_label = Gtk.Label() name_label.set_property('tooltip-text', opt.description) name_label.set_property('width-request', 175) name_label.set_text(opt.display_name) grid.attach(name_label, 0, row, 1, 1) widget = opt.get_widget(self.application, plugin_config.get(opt.name, opt.default)) widget.set_property('tooltip-text', opt.description) grid.attach(widget, 1, row, 1, 1) self._plugin_option_widgets[plugin_klass.name].append((opt, widget)) frame.show_all()
def _import_gtk(leftovers): # The never ending fork+gsettings problems now require us to # import Gtk _after_ the fork. This creates a funny race, since we # need to parse the command line arguments to know if we need to # fork, but need to import Gtk before cli processing so it can # handle --g-fatal-args. We strip out our flags first and pass the # left overs to gtk origargv = sys.argv try: sys.argv = origargv[:1] + leftovers[:] gi.require_version('Gtk', '3.0') from gi.repository import Gtk leftovers = sys.argv[1:] if Gtk.check_version(3, 22, 0): # pragma: no cover print("gtk3 3.22.0 or later is required.") sys.exit(1) # This will error if Gtk wasn't correctly initialized Gtk.init() globals()["Gtk"] = Gtk # This ensures we can init gsettings correctly from . import config ignore = config finally: sys.argv = origargv return leftovers
def run(self): self.running = True while self.running: event = self.display.next_event() try: if event.type == X.ButtonPress: # Check if pointer is inside monitored windows for w in self.windows: if Gtk.check_version (3, 20, 0) is None: pdevice = Gdk.Display.get_default().get_default_seat().get_pointer() else: pdevice = Gdk.Display.get_default().get_device_manager().get_client_pointer() p = self.get_window().get_device_position(pdevice) g = self.get_size() if p.x >= 0 and p.y >= 0 and p.x <= g.width and p.y <= g.height: break else: # Is outside, so activate GLib.idle_add(self.idle) self.display.allow_events(X.ReplayPointer, event.time) else: self.display.allow_events(X.ReplayPointer, X.CurrentTime) except Exception as e: print "Unexpected error: " + str(e)
def create_sidebar(self): sidebar_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.entry = Gtk.SearchEntry(placeholder_text="Search Tweaks…") if Gtk.check_version(3, 22, 20) is None: self.entry.set_input_hints(Gtk.InputHints.NO_EMOJI) self.entry.connect("search-changed", self._on_search) self.searchbar = Gtk.SearchBar() self.searchbar.add(self.entry) self.searchbar.props.hexpand = False self.listbox = Gtk.ListBox() self.listbox.set_size_request(200, -1) self.listbox.connect("row-selected", self._on_select_row) self.listbox.set_header_func(self._list_header_func, None) self.listbox.add(self.make_list_row("Magnification")) self.listbox.add(self.make_list_row("Tracking")) self.listbox.add(self.make_list_row("Colour Enhancement")) self.listbox.add(self.make_list_row("Cross hairs")) scroll = Gtk.ScrolledWindow() scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) scroll.add(self.listbox) sidebar_box.pack_start(self.searchbar, False, False, 0) sidebar_box.pack_start(scroll, True, True, 0) self.hsize_group.add_widget(sidebar_box) return sidebar_box
def run(self): self.running = True while self.running: event = self.display.next_event() try: if event.type == X.ButtonPress: # Check if pointer is inside monitored windows for w in self.windows: if Gtk.check_version(3, 20, 0) is None: pdevice = Gdk.Display.get_default( ).get_default_seat().get_pointer() else: pdevice = Gdk.Display.get_default( ).get_device_manager().get_client_pointer() p = self.get_window().get_device_position(pdevice) g = self.get_size() if p.x >= 0 and p.y >= 0 and p.x <= g.width and p.y <= g.height: break else: # Is outside, so activate GLib.idle_add(self.idle) self.display.allow_events(X.ReplayPointer, event.time) else: self.display.allow_events(X.ReplayPointer, X.CurrentTime) except Exception as e: print "Unexpected error: " + str(e)
def __init__(self, application, plugin_klass): super(PluginsConfigurationFrame, self).__init__() self.application = application self.config = application.config self.plugin_klass = plugin_klass self.option_widgets = {} self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) plugin_config = self.config['plugins'].get(plugin_klass.name) or {} # use or instead of get incase the value is actually None grid = Gtk.Grid() self.add(grid) if Gtk.check_version(3, 12, 0): grid.set_property('margin-left', 12) else: grid.set_property('margin-start', 12) grid.set_property('column-spacing', 3) grid.set_property('hexpand', True) grid.set_property('row-spacing', 3) grid.insert_column(0) grid.insert_column(0) grid.attach(self._get_title_box(), 0, 0, 2, 1) for row, opt in enumerate(plugin_klass.options, 1): grid.insert_row(row) name_label = Gtk.Label() name_label.set_property('tooltip-text', opt.description) name_label.set_property('width-request', 175) name_label.set_text(opt.display_name) grid.attach(name_label, 0, row, 1, 1) widget = opt.get_widget(self.application, plugin_config.get(opt.name, opt.default)) widget.set_property('tooltip-text', opt.description) grid.attach(widget, 1, row, 1, 1) self.option_widgets[opt.name] = OptionWidget(opt, widget) self.show_all()
def __init__(self, Context, pluginPage=None, categoryName=None): Gtk.Window.__init__(self) self.ShowingPlugin = None self.Context = Context self.connect("destroy", self.Quit) if Gtk.check_version(3, 0, 0) is None: self.get_style_context().add_class("ccsm-window") self.set_size_request(750, -1) self.set_default_size(1000, 580) self.set_title(_("CompizConfig Settings Manager")) # Build the panes self.MainBox = Gtk.HBox() self.add(self.MainBox) self.LeftPane = Gtk.VBox() self.RightPane = Gtk.VBox() self.RightPane.set_border_width(5) self.MainBox.pack_start(self.LeftPane, False, False, 0) self.MainBox.pack_end(self.RightPane, True, True, 0) self.MainPage = MainPage(self, self.Context) self.CurrentPage = None self.SetPage(self.MainPage) try: self.LeftPane.set_size_request(self.LeftPane.size_request().width, -1) except (AttributeError, TypeError): req = Gtk.Requisition() self.LeftPane.size_request(req) self.LeftPane.set_size_request(req.width, -1) self.show_all() if pluginPage in self.Context.Plugins: self.MainPage.ShowPlugin(None, self.Context.Plugins[pluginPage]) if categoryName in self.Context.Categories: self.MainPage.ToggleCategory(None, categoryName)
def connection_problems(self): """ Called by the networking code, when the server did not respond for some time or when we are disconnected. """ def destroyed(widget): self.overlaybox = None # Do we run on Gtk 3.2? if Gtk.check_version(3, 4, 0) != None: self.overlay.add(self.scrolledwindow) if self.overlaybox is not None: return self.overlaybox = OverlayDialog() # GtkOverlay is broken in Gtk 3.2, so we apply a workaround: if Gtk.check_version(3, 4, 0) == None: # Gtk 3.4+ self.overlay.add_overlay(self.overlaybox) else: # Gtk 3.2 if self.overlay.get_child() == self.scrolledwindow: self.overlay.remove(self.scrolledwindow) self.overlay.add(self.overlaybox) self.overlaybox.connect("destroy", destroyed)
def _configure_settings_plugin_options(self, plugin_klass): plugin_config = self.config['plugins'].get(plugin_klass.name) or { } # use or instead of get incase the value is actually None frame = Gtk.Frame() self.gobjects['box_plugin_options'].pack_end(frame, True, True, 0) frame.set_label(plugin_klass.title) grid = Gtk.Grid() frame.add(grid) if Gtk.check_version(3, 12, 0): grid.set_property('margin-left', 12) else: grid.set_property('margin-start', 12) grid.set_property('column-spacing', 3) grid.set_property('row-spacing', 3) grid.insert_column(0) grid.insert_column(0) for row, opt in enumerate(plugin_klass.options): grid.insert_row(row) name_label = Gtk.Label() name_label.set_property('tooltip-text', opt.description) name_label.set_property('width-request', 175) name_label.set_text(opt.display_name) grid.attach(name_label, 0, row, 1, 1) widget = opt.get_widget(plugin_config.get(opt.name, opt.default)) widget.set_property('tooltip-text', opt.description) grid.attach(widget, 1, row, 1, 1) self._plugin_option_widgets[plugin_klass.name].append( (opt, widget)) frame.show_all()
def _add_gear_button(self): self.gear_button = Gtk.MenuButton() #Set content icon = Gio.ThemedIcon(name="emblem-system-symbolic") # Use open-menu-symbolic on Gtk+>=3.14 if Gtk.check_version(3, 14, 0) is None: icon = Gio.ThemedIcon(name="open-menu-symbolic") image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.MENU) self.gear_button.add(image) # Use popover on Gtk+>=3.12 if Gtk.check_version(3, 12, 0) is None: self.gear_button.set_use_popover(True) #Pack self.hb_rbox.pack_start(self.gear_button, False, False, 0)
def __init__(self, main_window): self._menu = Gtk.Menu.new_from_model(Bars.ContextMenu()) self._menu.attach_to_widget(main_window) # In GTK 3.22 Menu.popup was deprecated, we want to popup at the # pointer, so use that new function instead if we can. if Gtk.check_version(3,22,0) is None: self.popup = self._menu.popup_at_pointer
def __create_trayicon(self): if Gtk.check_version(2, 10, 0) is not None: self.log.debug("Disabled Tray Icon. It needs PyGtk >= 2.10.0") return self.tray = Gtk.StatusIcon() self.tray.set_from_file(os.path.join(self.img_path,'gmediafinder.png')) self.tray.set_tooltip('Gmediafinder') self.tray.connect("activate", self.__on_trayicon_click) self.tray.connect("popup-menu", self.__show_tray_menu)
def _create_actions(self): action = Gio.SimpleAction.new('emit-application-signal', GLib.VariantType.new('s')) action.connect('activate', self.action_emit_application_signal) if Gtk.check_version(3, 14, 0): self.add_accelerator('<Control><Shift>F1', 'win.emit-application-signal', GLib.Variant.new_string('rpc-cache-clear')) else: self.set_accels_for_action('win.emit-application-signal(\'rpc-cache-clear\')', ['<Control><Shift>F1']) self.actions['emit-application-signal'] = action self.add_action(action)
def __init__ (self, minWidth = -1, minHeight = -1): super (SizedButton, self).__init__ () self.minWidth = minWidth self.minHeight = minHeight if Gtk.check_version(3, 0, 0) is None: self.set_size_request (self.minWidth, self.minHeight) else: self.connect ("size-request", self.adjust_size) self.connect ("size-allocate", self.adjust_size)
def get_mouse_iter(self, x, y): # Convenience method to get the iter in the buffer of x, y coords. click_coords = self.window_to_buffer_coords(Gtk.TextWindowType.TEXT, x, y) mouseClickPositionIter = self.get_iter_at_location( click_coords[0], click_coords[1]) if Gtk.check_version(3, 19, 8) is None: mouseClickPositionIter = mouseClickPositionIter[1] return mouseClickPositionIter
def __init__(self, minWidth=-1, minHeight=-1): super(SizedButton, self).__init__() self.minWidth = minWidth self.minHeight = minHeight if Gtk.check_version(3, 0, 0) is None: self.set_size_request(self.minWidth, self.minHeight) else: self.connect("size-request", self.adjust_size) self.connect("size-allocate", self.adjust_size)
def get_iter_at_coords(view, x, y): mouseClickPos = view.get_iter_at_location( *view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, int(x), int(y))) if Gtk.check_version(3, 19, 8) is None: if not mouseClickPos[0]: return False mouseClickPos = mouseClickPos[1] return mouseClickPos
def get_iter_at_coords(view, x, y): mouseClickPos = view.get_iter_at_location( *view.window_to_buffer_coords( Gtk.TextWindowType.TEXT, int(x), int(y))) if Gtk.check_version(3, 19, 8) is None: if not mouseClickPos[0]: return False mouseClickPos = mouseClickPos[1] return mouseClickPos
def get_mouse_iter(self, x, y): click_coords = self.window_to_buffer_coords(Gtk.TextWindowType.TEXT, x, y) mouseClickPositionIter = self.get_iter_at_location( click_coords[0], click_coords[1]) if Gtk.check_version(3, 19, 8) is None: if not mouseClickPositionIter[0]: return False mouseClickPositionIter = mouseClickPositionIter[1] return mouseClickPositionIter
def validate_order(self, order): order = order.upper() for i in order: if i not in ['N', 'C', 'S']: raise ValueError('Illegal character in ORDER. ' '(Choices: [N, C, S])') if len(order) != len(set(order)): raise ValueError('Repeated character in ORDER. ' 'Please specify each lock at most once.') if 'S' in order and Gtk.check_version(3, 18, 0) is not None: # Silently drop Scroll lock if GTK <= 3.18 order.remove('S')
def __init__(self, code): super().__init__() if Gtk.check_version (3, 0, 0) is None: self.connect ("draw", self.draw) else: self.connect ("expose_event", self.draw) self.add_events (Gdk.EventMask.BUTTON_PRESS_MASK) self.connect("button-press-event", self.reload_code) self.set_size_request(400, 250) self.code = code self.reload_code(None, None)
def update_state_out(self, *args): state = args[-1] self.states[state] = False if Gtk.check_version(3, 0, 0) is None: if True in self.states.values(): self.set_state(Gtk.StateFlags.PRELIGHT) else: self.set_state(Gtk.StateFlags.NORMAL) else: if True in self.states.values(): self.set_state(Gtk.StateType.PRELIGHT) else: self.set_state(Gtk.StateType.NORMAL)
def on_clbtnPalette_color_set(self, widget, index=0): """General method for on_color_set""" if Gtk.check_version(3, 0, 0) is None: changed_color = widget.get_rgba().to_string() else: changed_color = widget.get_color().to_string() if self._conf['color_palettename'] != "Custom": self._conf['color_palette'] = list( PREDEF_PALETTE[self._conf['color_palettename']]) self._conf['color_palettename'] = "Custom" self.comboboxPalette.set_active(self._palette_list.index("Custom")) self._conf['color_palette'][index] = changed_color self._set_palette(self._conf['color_palettename'])
def update_state_out (self, *args): state = args[-1] self.states[state] = False if Gtk.check_version (3, 0, 0) is None: if True in self.states.values (): self.set_state (Gtk.StateFlags.PRELIGHT) else: self.set_state (Gtk.StateFlags.NORMAL) else: if True in self.states.values (): self.set_state (Gtk.StateType.PRELIGHT) else: self.set_state (Gtk.StateType.NORMAL)
def check_gui_dependencies(): if os.getenv("NICOTINE_GTK_VERSION") == '4': gtk_version = (4, 6, 0) pygobject_version = (3, 40, 0) else: gtk_version = pygobject_version = (3, 18, 0) try: import gi gi.check_version(pygobject_version) except (ImportError, ValueError): return _("Cannot find %s, please install it.") % ( "pygobject >= " + '.'.join(map(str, pygobject_version))) try: api_version = (gtk_version[0], 0) gi.require_version('Gtk', '.'.join(map(str, api_version))) except ValueError: return _("Cannot find %s, please install it.") % ("GTK " + str(gtk_version[0])) try: from gi.repository import Gtk except ImportError: return _( "Cannot import the Gtk module. Bad install of the python-gobject module?" ) if Gtk.check_version(*gtk_version): return _( "You are using an unsupported version of GTK %(major_version)s. You should install " "GTK %(complete_version)s or newer.") % { "major_version": gtk_version[0], "complete_version": '.'.join(map(str, gtk_version)) } try: if gtk_version[0] == 4 and os.getenv("NICOTINE_LIBADWAITA") == '1': gi.require_version('Adw', '1') from gi.repository import Adw Adw.init() except (ImportError, ValueError): pass return None
def _create_actions(self): action = Gio.SimpleAction.new('emit-application-signal', GLib.VariantType.new('s')) action.connect('activate', self.action_emit_application_signal) accelerators = ( ('<Control><Shift>F1', 'rpc-cache-clear'), ('<Control><Shift>F12', 'reload-css-style') ) for key, signal_name in accelerators: if Gtk.check_version(3, 14, 0): self.add_accelerator(key, 'win.emit-application-signal', GLib.Variant.new_string(signal_name)) else: self.set_accels_for_action("win.emit-application-signal('{0}')".format(signal_name), (key,)) self.actions['emit-application-signal'] = action self.add_action(action)
def hierarchy_changed(self, widget, old_toplevel): if old_toplevel == self._old_toplevel: return if Gtk.check_version(3, 0, 0) is None: if not old_toplevel and self.get_state() != Gtk.StateFlags.NORMAL: self.set_state(Gtk.StateFlags.PRELIGHT) self.set_state(Gtk.StateFlags.NORMAL) else: if not old_toplevel and self.get_state() != Gtk.StateType.NORMAL: self.set_state(Gtk.StateType.PRELIGHT) self.set_state(Gtk.StateType.NORMAL) self._old_toplevel = old_toplevel
def hierarchy_changed (self, widget, old_toplevel): if old_toplevel == self._old_toplevel: return if Gtk.check_version(3, 0, 0) is None: if not old_toplevel and self.get_state() != Gtk.StateFlags.NORMAL: self.set_state(Gtk.StateFlags.PRELIGHT) self.set_state(Gtk.StateFlags.NORMAL) else: if not old_toplevel and self.get_state() != Gtk.StateType.NORMAL: self.set_state(Gtk.StateType.PRELIGHT) self.set_state(Gtk.StateType.NORMAL) self._old_toplevel = old_toplevel
def _set_palette(self, palette_name): if palette_name in PREDEF_PALETTE: colors = PREDEF_PALETTE[palette_name] elif palette_name == "Custom": colors = self._conf['color_palette'] else: colors = PREDEF_PALETTE['Tango'] if Gtk.check_version(3, 0, 0) is None: fg = self.clbtnFg.get_rgba() bg = self.clbtnBg.get_rgba() else: fg = self.clbtnFg.get_color() bg = self.clbtnBg.get_color() palette = [] for i in xrange(16): if Gtk.check_version(3, 0, 0) is None: palette.append(Gdk.RGBA()) palette[-1].parse(colors[i]) self.clbtnPalette[i].set_rgba(palette[-1]) else: palette.append(Gdk.color_parse(colors[i])) self.clbtnPalette[i].set_color(palette[-1]) self.demoTerm.set_colors(fg, bg, palette)
def main(): parser = argparse.ArgumentParser(description='King Phisher Client GUI', conflict_handler='resolve') utilities.argp_add_args(parser, default_root='KingPhisher') startup.argp_add_client(parser) arguments = parser.parse_args() # basic runtime checks if sys.version_info < (3, 4): color.print_error('the Python version is too old (minimum required is 3.4)') return 0 if Gtk.check_version(3, 14, 0): color.print_error('the GTK+ version is too old (minimum required is 3.14)') return 0 if sys.platform.startswith('linux') and not os.environ.get('DISPLAY'): color.print_error('no display was detected, this must be run with an interactive X session') return 0 config_file = arguments.config_file use_plugins = arguments.use_plugins use_style = arguments.use_style del arguments, parser logger = logging.getLogger('KingPhisher.Client.CLI') if sys.platform.startswith('linux') and not os.getuid(): logger.warning('it is not necessary to run the king phisher client as root') find.init_data_path('client') if not gui_utilities.which_glade(): color.print_error('unable to locate the glade ui data file') return 0 logger.debug("king phisher version: {0} python version: {1}.{2}.{3}".format(version.version, sys.version_info[0], sys.version_info[1], sys.version_info[2])) logger.debug("client running in process: {0} main tid: 0x{1:x}".format(os.getpid(), threading.current_thread().ident)) start_time = time.time() logger.debug('using ui data from glade file: ' + gui_utilities.which_glade()) try: app = application.KingPhisherClientApplication(config_file=config_file, use_plugins=use_plugins, use_style=use_style) except Exception as error: logger.critical("initialization error: {0} ({1})".format(error.__class__.__name__, getattr(error, 'message', 'n/a'))) color.print_error('failed to initialize the King Phisher client') return 0 logger.debug("client loaded in {0:.2f} seconds".format(time.time() - start_time)) GObject.threads_init() return app.run([])
def create_ui(self): self.manager = Gtk.UIManager() accelgroup = self.manager.get_accel_group() self.window.add_accel_group(accelgroup) main_actiongroup = Gtk.ActionGroup.new('Gnofract4D') self.main_actiongroup = main_actiongroup main_actiongroup.add_toggle_actions(self.get_toggle_actions()) self.explorer_menu_item = main_actiongroup.get_action( 'ToolsExplorerAction') main_actiongroup.add_actions(self.get_main_actions()) self.manager.insert_action_group(main_actiongroup, 0) # actions which are only available if we're in 4D mode self.fourd_actiongroup = Gtk.ActionGroup.new('4D-sensitive widgets') self.fourd_actiongroup.add_actions(self.get_fourd_actions()) self.manager.insert_action_group(self.fourd_actiongroup, 1) this_path = os.path.dirname(sys.modules[__name__].__file__) ui_location = os.path.join(this_path, "ui.xml") self.manager.add_ui_from_file(ui_location) self.menubar = self.manager.get_widget('/MenuBar') self.vbox.pack_start(self.menubar, False, True, 0) # this could be done with an actiongroup, but since it already works... undo = self.manager.get_widget(_("/MenuBar/EditMenu/EditUndo")) self.model.seq.make_undo_sensitive(undo) redo = self.manager.get_widget(_("/MenuBar/EditMenu/EditRedo")) self.model.seq.make_redo_sensitive(redo) # command reference if (not Gtk.check_version(3, 19, 0)): # this version of Gtk *is* new enough to support shortcuts widget builder = Gtk.Builder.new_from_file( os.path.join(this_path, "shortcuts-gnofract4d.ui")) self.shortcuts_window = builder.get_object("shortcuts-gnofract4d") self.shortcuts_window.set_transient_for(self.window) self.shortcuts_window.connect( "delete-event", lambda widget, event: Gtk.Window.hide_on_delete(widget)) else: # older GTK builds don't understand shortcuts ui and rudely crash self.shortcuts_window = None
def set_y(self, y): iter = self.get_iter_at_location(0, y) if Gtk.check_version(3, 19, 8) is None: if not iter[0]: return iter = iter[1] if self.get_iter_location(iter).y < y: self.forward_display_line(iter) yalign = float(self.get_iter_location(iter).y - y) / self.height self.scroll_to_iter(iter, 0, True, 0, yalign) self.check_autoscroll()
def _create_actions(self): action = Gio.SimpleAction.new('emit-application-signal', GLib.VariantType.new('s')) action.connect('activate', self.action_emit_application_signal) accelerators = ( ('<Control><Shift>F1', 'rpc-cache-clear'), ('<Control><Shift>F2', 'config-save'), ('<Control><Shift>F12', 'reload-css-style') ) for key, signal_name in accelerators: if Gtk.check_version(3, 14, 0): self.add_accelerator(key, 'win.emit-application-signal', GLib.Variant.new_string(signal_name)) else: self.set_accels_for_action("win.emit-application-signal('{0}')".format(signal_name), (key,)) self.actions['emit-application-signal'] = action self.add_action(action)
def create_ui(self): self.manager = Gtk.UIManager() accelgroup = self.manager.get_accel_group() self.window.add_accel_group(accelgroup) main_actiongroup = Gtk.ActionGroup.new('Gnofract4D') self.main_actiongroup = main_actiongroup main_actiongroup.add_toggle_actions(self.get_toggle_actions()) self.explorer_menu_item = main_actiongroup.get_action('ToolsExplorerAction') main_actiongroup.add_actions(self.get_main_actions()) self.manager.insert_action_group(main_actiongroup, 0) # actions which are only available if we're in 4D mode self.fourd_actiongroup = Gtk.ActionGroup.new('4D-sensitive widgets') self.fourd_actiongroup.add_actions(self.get_fourd_actions()) self.manager.insert_action_group(self.fourd_actiongroup, 1) this_path = os.path.dirname(sys.modules[__name__].__file__) ui_location = os.path.join(this_path,"ui.xml") self.manager.add_ui_from_file(ui_location) self.menubar = self.manager.get_widget('/MenuBar') self.vbox.pack_start(self.menubar, False, True, 0) # this could be done with an actiongroup, but since it already works... undo = self.manager.get_widget(_("/MenuBar/EditMenu/EditUndo")) self.model.seq.make_undo_sensitive(undo) redo = self.manager.get_widget(_("/MenuBar/EditMenu/EditRedo")) self.model.seq.make_redo_sensitive(redo) # command reference if (not Gtk.check_version(3,19,0)): # this version of Gtk *is* new enough to support shortcuts widget builder = Gtk.Builder.new_from_file( os.path.join(this_path, "shortcuts-gnofract4d.ui")) self.shortcuts_window = builder.get_object("shortcuts-gnofract4d") self.shortcuts_window.set_transient_for(self.window) self.shortcuts_window.connect( "delete-event", lambda widget, event: Gtk.Window.hide_on_delete(widget)) else: # older GTK builds don't understand shortcuts ui and rudely crash self.shortcuts_window = None
def _add_insert_button(self): self.insert_button = Gtk.MenuButton() #Set content icon = Gio.ThemedIcon(name="insert-text-symbolic") image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.MENU) self.insert_button.add(image) # Set menu model self.insert_button.props.menu_model = self.insertmenu # Use popover on Gtk+>=3.12 if Gtk.check_version(3, 12, 0) is None: self.insert_button.set_use_popover(True) #Pack self.hb_rbox.pack_start(self.insert_button, False, False, 0)
def __init__(self, winParent, settings, show=False): """Prepare the about dialog and optionally show it immediately""" self.settings = settings # Retrieve the translators list translators = [] for line in readlines(FILE_TRANSLATORS, False): if ':' in line: line = line.split(':', 1)[1] line = line.replace('(at)', '@').strip() if line not in translators: translators.append(line) # Load the user interface builder = Gtk.Builder() builder.add_from_file(FILE_UI_ABOUT) # Obtain widget references self.dialog = builder.get_object("dialogAbout") # Set various properties self.dialog.set_program_name(APP_NAME) self.dialog.set_version('Version %s' % APP_VERSION) self.dialog.set_comments(APP_DESCRIPTION) self.dialog.set_website(APP_URL) self.dialog.set_copyright(APP_COPYRIGHT) # Prepare lists for authors and contributors authors = ['%s <%s>' % (APP_AUTHOR, APP_AUTHOR_EMAIL)] contributors = [] for line in readlines(FILE_CONTRIBUTORS, False): contributors.append(line) if len(contributors) > 0: contributors.insert(0, _('Contributors:')) authors.extend(contributors) self.dialog.set_authors(authors) self.dialog.set_license('\n'.join(readlines(FILE_LICENSE, True))) self.dialog.set_translator_credits('\n'.join(translators)) # Retrieve the external resources links # only for GTK+ 3.6.0 and higher if not Gtk.check_version(3, 6, 0): for line in readlines(FILE_RESOURCES, False): resource_type, resource_url = line.split(':', 1) self.dialog.add_credit_section(resource_type, (resource_url, )) icon_logo = Pixbuf.new_from_file(FILE_ICON) self.dialog.set_logo(icon_logo) self.dialog.set_transient_for(winParent) # Optionally show the dialog if show: self.show()
def __init__(self, winParent, settings, show=False): """Prepare the about dialog and optionally show it immediately""" self.settings = settings # Retrieve the translators list translators = [] for line in readlines(FILE_TRANSLATORS, False): if ':' in line: line = line.split(':', 1)[1] line = line.replace('(at)', '@').strip() if line not in translators: translators.append(line) # Load the user interface builder = Gtk.Builder() builder.add_from_file(FILE_UI_ABOUT) # Obtain widget references self.dialog = builder.get_object("dialogAbout") # Set various properties self.dialog.set_program_name(APP_NAME) self.dialog.set_version('Version %s' % APP_VERSION) self.dialog.set_comments(APP_DESCRIPTION) self.dialog.set_website(APP_URL) self.dialog.set_copyright(APP_COPYRIGHT) # Prepare lists for authors and contributors authors = ['%s <%s>' % (APP_AUTHOR, APP_AUTHOR_EMAIL)] contributors = [] for line in readlines(FILE_CONTRIBUTORS, False): contributors.append(line) if len(contributors) > 0: contributors.insert(0, _('Contributors:')) authors.extend(contributors) self.dialog.set_authors(authors) self.dialog.set_license('\n'.join(readlines(FILE_LICENSE, True))) self.dialog.set_translator_credits('\n'.join(translators)) # Retrieve the external resources links # only for GTK+ 3.6.0 and higher if not Gtk.check_version(3, 6, 0): for line in readlines(FILE_RESOURCES, False): resource_type, resource_url = line.split(':', 1) self.dialog.add_credit_section(resource_type, (resource_url,)) icon_logo = Pixbuf.new_from_file(FILE_ICON) self.dialog.set_logo(icon_logo) self.dialog.set_transient_for(winParent) # Optionally show the dialog if show: self.show()
def __init__(self, parent, event): if Gtk.check_version(3, 12, 0) is None: # Use header bar Gtk.Dialog.__init__(self, _("Simulation"), parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL), use_header_bar=True) self.get_header_bar().set_show_close_button(False) else: # Do not use header bar Gtk.Dialog.__init__(self, _("Simulation"), parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)) self.event = event self.set_default_size(150, 100) self.props.resizable = False self.set_default_response(Gtk.ResponseType.CANCEL) self.progress_bar = Gtk.ProgressBar() self.progress_bar.activity_mode = True self.progress_bar.pulse() self.progress_bar.set_text(_(u"Running ngspice…")) self.progress_bar.set_show_text(True) self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) self.hbox.set_margin_left(18) self.hbox.set_margin_top(18) self.hbox.set_margin_bottom(18) self.hbox.set_margin_right(18) self.hbox.set_vexpand(True) self.hbox.set_spacing(12) self.hbox.pack_start(self.progress_bar, True, True, 18) box = self.get_content_area() box.add(self.hbox) self.timeout_id = GObject.timeout_add(50, self.on_timeout, None) self.show_all()
def __init__(self, parent): """Prepare the about dialog""" # Retrieve the translators list translators = [] for line in readlines(FILE_TRANSLATORS, False): if ':' in line: line = line.split(':', 1)[1] line = line.replace('(at)', '@').strip() if line not in translators: translators.append(line) # Load the user interface self.ui = GtkBuilderLoader('about.ui') # Set various properties self.ui.dialog_about.set_program_name(APP_NAME) self.ui.dialog_about.set_version('%s\n%s' % ( _('Version %s') % APP_VERSION, _('Database version: %s') % DATABASE_VERSION)) self.ui.dialog_about.set_comments(_(APP_DESCRIPTION)) self.ui.dialog_about.set_website(APP_URL) self.ui.dialog_about.set_copyright(APP_COPYRIGHT) # Prepare lists for authors and contributors authors = ['%s <%s>' % (APP_AUTHOR, APP_AUTHOR_EMAIL)] contributors = [] for line in readlines(FILE_CONTRIBUTORS, False): contributors.append(line) if len(contributors) > 0: contributors.insert(0, _('Contributors:')) authors.extend(contributors) self.ui.dialog_about.set_authors(authors) self.ui.dialog_about.set_license( '\n'.join(readlines(FILE_LICENSE, True))) self.ui.dialog_about.set_translator_credits('\n'.join(translators)) # Retrieve the external resources links # only for GTK+ 3.6.0 and higher if not Gtk.check_version(3, 6, 0): for line in readlines(FILE_RESOURCES, False): resource_type, resource_url = line.split(':', 1) self.ui.dialog_about.add_credit_section( resource_type, (resource_url,)) icon_logo = Pixbuf.new_from_file(FILE_ICON) self.ui.dialog_about.set_logo(icon_logo) self.ui.dialog_about.set_transient_for(parent)
def startup(self, application): """Configure the application during the startup""" __pychecker__ = 'unusednames=application' self.ui = UIMain(self) # Add the about action to the app menu action = Gio.SimpleAction(name="about") action.connect("activate", self.on_app_about_activate) self.add_action(action) # Add the shortcut action to the app menu # only for GTK+ 3.20.0 and higher if not Gtk.check_version(3, 20, 0): action = Gio.SimpleAction(name="shortcuts") action.connect("activate", self.on_app_shortcuts_activate) self.add_action(action) # Add the quit action to the app menu action = Gio.SimpleAction(name="quit") action.connect("activate", self.on_app_quit_activate) self.add_action(action) # Add the app menu builder_appmenu = GtkBuilderLoader(get_ui_file('appmenu.ui')) self.set_app_menu(builder_appmenu.app_menu)
def loadUI(self): """Load the interface UI""" self.ui = GtkBuilderLoader(get_ui_file('main.glade')) self.ui.win_main.set_application(self.application) self.ui.win_main.set_title(APP_NAME) # Initialize actions for widget in self.ui.get_objects_by_type(Gtk.Action): # Connect the actions accelerators widget.connect_accelerator() # Set labels widget.set_label(text(widget.get_label())) # Initialize tooltips for widget in self.ui.get_objects_by_type(Gtk.ToolButton): action = widget.get_related_action() if action: widget.set_tooltip_text(action.get_label().replace('_', '')) # Initialize column headers for widget in self.ui.get_objects_by_type(Gtk.TreeViewColumn): widget.set_title(text(widget.get_title())) # Set list items row height icon_size = preferences.ICON_SIZE self.ui.cell_name.props.height = preferences.get(icon_size) self.ui.cell_group_name.props.height = preferences.get(icon_size) # Set groups visibility self.ui.scroll_groups.set_visible( preferences.get(preferences.GROUPS_SHOW)) # Add a Gtk.Headerbar, only for GTK+ 3.10.0 and higher if (not Gtk.check_version(3, 10, 0) and not preferences.get(preferences.HEADERBARS_DISABLE)): self.load_ui_headerbar() if preferences.get(preferences.HEADERBARS_REMOVE_TOOLBAR): # This is only for development, it should always be True # Remove the redundant toolbar self.ui.toolbar_main.destroy() # Flatten the Gtk.ScrolledWindows self.ui.scroll_groups.set_shadow_type(Gtk.ShadowType.NONE) self.ui.scroll_connections.set_shadow_type(Gtk.ShadowType.NONE) # Connect signals from the glade file to the module functions self.ui.connect_signals(self)
def _get_editor_font_css(): """Return CSS for custom editor font.""" font_desc = Pango.FontDescription("monospace") if (gaupol.conf.editor.custom_font and gaupol.conf.editor.use_custom_font): font_desc = Pango.FontDescription(gaupol.conf.editor.custom_font) # They f*****g broke theming again with GTK+ 3.22. unit = "pt" if Gtk.check_version(3, 22, 0) is None else "px" css = """ .gaupol-custom-font {{ font-family: {family},monospace; font-size: {size}{unit}; font-weight: {weight}; }}""".format( family=font_desc.get_family().split(",")[0], size=int(round(font_desc.get_size() / Pango.SCALE)), unit=unit, weight=int(font_desc.get_weight())) css = css.replace("font-size: 0{unit};".format(unit=unit), "") css = css.replace("font-weight: 0;", "") css = "\n".join(filter(lambda x: x.strip(), css.splitlines())) return css
def connection_problems(self): """ Called by the networking code, when the server did not respond for some time or when we are disconnected. """ def destroyed(widget): self.overlaybox = None # Do we run on Gtk 3.2? if Gtk.check_version(3,4,0) != None: self.overlay.add(self.scrolledwindow) if self.overlaybox is not None: return self.overlaybox = OverlayDialog() # GtkOverlay is broken in Gtk 3.2, so we apply a workaround: if Gtk.check_version(3,4,0) == None: # Gtk 3.4+ self.overlay.add_overlay(self.overlaybox) else: # Gtk 3.2 if self.overlay.get_child() == self.scrolledwindow: self.overlay.remove(self.scrolledwindow) self.overlay.add(self.overlaybox) self.overlaybox.connect("destroy", destroyed)
def trigger(self, *args): if Gtk.check_version(3, 20, 0) is None: self._show_shortcuts_window() else: self._show_shortcuts_dialog()