Exemple #1
0
	def _apply_css(config):
		if OSDWindow.css_provider:
			Gtk.StyleContext.remove_provider_for_screen(
				Gdk.Screen.get_default(), OSDWindow.css_provider)
		
		colors = {}
		for x in config['osk_colors'] : colors["osk_%s" % (x,)] = config['osk_colors'][x]
		for x in config['osd_colors'] : colors[x] = config['osd_colors'][x]
		colors = OSDCssMagic(colors)
		try:
			css_file = os.path.join(get_share_path(), "osd-styles", config["osd_style"])
			css = file(css_file, "r").read()
			if ((Gtk.get_major_version(), Gtk.get_minor_version()) > (3, 20)):
				css += OSDWindow.CSS_3_20
			OSDWindow.css_provider = Gtk.CssProvider()
			OSDWindow.css_provider.load_from_data((css % colors).encode("utf-8"))
			Gtk.StyleContext.add_provider_for_screen(
					Gdk.Screen.get_default(),
					OSDWindow.css_provider,
					Gtk.STYLE_PROVIDER_PRIORITY_USER)
		except GLib.Error, e:
			log.error("Failed to apply css with user settings:")
			log.error(e)
			log.error("Retrying with default values")
			
			OSDWindow.css_provider = Gtk.CssProvider()
			css_file = os.path.join(get_share_path(), "osd-styles", "Classic.gtkstyle.css")
			css = file(css_file, "r").read()
			if ((Gtk.get_major_version(), Gtk.get_minor_version()) > (3, 20)):
				css += OSDWindow.CSS_3_20
			OSDWindow.css_provider.load_from_data((css % colors).encode("utf-8"))
			Gtk.StyleContext.add_provider_for_screen(
					Gdk.Screen.get_default(),
					OSDWindow.css_provider,
					Gtk.STYLE_PROVIDER_PRIORITY_USER)
Exemple #2
0
def get_workarea_dimensions(window=None):
    """
        Returns the x-offset, y-offset, width and height of the work area
        for a given window or for the default screen if no window is given.
        Falls back to the screen dimensions if not available.

        :param window: class: `Gtk.Window`, optional

        :returns: :class:`CairoRectangleInt`
    """
    if window is None:
        screen = Gdk.Screen.get_default()
        default_monitor = screen.get_primary_monitor()
        return screen.get_monitor_workarea(default_monitor)
    elif (
        Gtk.get_major_version() > 3
        or Gtk.get_major_version() == 3
        and Gtk.get_minor_version() >= 22
    ):
        # Gdk.Monitor was introduced in Gtk+ 3.22
        display = window.get_window().get_display()
        work_area = display.get_monitor_at_window(window.get_window()).get_workarea()
    else:
        screen = window.get_screen()
        monitor_nr = screen.get_monitor_at_window(window.get_window())
        work_area = screen.get_monitor_workarea(monitor_nr)
    return work_area
Exemple #3
0
	def __init__(self, config_file=None, use_plugins=True, use_style=True):
		super(KingPhisherClientApplication, self).__init__()
		if use_style:
			gtk_version = (Gtk.get_major_version(), Gtk.get_minor_version())
			if gtk_version > (3, 18):
				self._theme_file = 'theme.v2.css'
			else:
				self._theme_file = 'theme.v1.css'
		else:
			self._theme_file = DISABLED
		self.logger = logging.getLogger('KingPhisher.Client.Application')
		# log version information for debugging purposes
		self.logger.debug("gi.repository GLib version: {0}".format('.'.join(map(str, GLib.glib_version))))
		self.logger.debug("gi.repository GObject version: {0}".format('.'.join(map(str, GObject.pygobject_version))))
		self.logger.debug("gi.repository Gtk version: {0}.{1}.{2}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()))
		if rpc_terminal.has_vte:
			self.logger.debug("gi.repository VTE version: {0}".format(rpc_terminal.Vte._version))
		if graphs.has_matplotlib:
			self.logger.debug("matplotlib version: {0}".format(graphs.matplotlib.__version__))
		self.set_property('application-id', 'org.king-phisher.client')
		self.set_property('register-session', True)
		self.config_file = config_file or os.path.join(USER_DATA_PATH, 'config.json')
		"""The file containing the King Phisher client configuration."""
		if not os.path.isfile(self.config_file):
			self._create_config()
		self.config = None
		"""The primary King Phisher client configuration."""
		self.main_window = None
		"""The primary top-level :py:class:`~.MainAppWindow` instance."""
		self.rpc = None
		"""The :py:class:`~.KingPhisherRPCClient` instance for the application."""
		self._ssh_forwarder = None
		"""The SSH forwarder responsible for tunneling RPC communications."""
		self.style_provider = None
		try:
			self.emit('config-load', True)
		except IOError:
			self.logger.critical('failed to load the client configuration')
			raise

		self.connect('window-added', self.signal_window_added)
		self.actions = {}
		self._create_actions()

		if not use_plugins:
			self.logger.info('disabling all plugins')
			self.config['plugins.enabled'] = []
		self.plugin_manager = plugins.ClientPluginManager(
			[os.path.join(USER_DATA_PATH, 'plugins'), find.find_data_directory('plugins')],
			self
		)
		if use_plugins:
			self.plugin_manager.load_all()
Exemple #4
0
def apply_gtk_css():
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    if Gtk.get_major_version() == 3 and Gtk.get_minor_version() == 22:
        print "Gtk version is " + gtk_version + ", Flowblade theme is available."
    else:
        print "Gtk version is " + gtk_version + ", Flowblade theme only available for Gtk 3.22"
        return
        
    provider = Gtk.CssProvider.new()
    display = Gdk.Display.get_default()
    screen = display.get_default_screen()
    Gtk.StyleContext.add_provider_for_screen (screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
    
    provider.load_from_path(respaths.ROOT_PATH + "/res/css/gtk-dark-fix.css")
Exemple #5
0
 def __init__(self, config_file=None):
     super(KingPhisherClientApplication, self).__init__()
     self.logger = logging.getLogger('KingPhisher.Client.Application')
     # log version information for debugging purposes
     self.logger.debug("gi.repository GLib version: {0}".format('.'.join(
         map(str, GLib.glib_version))))
     self.logger.debug("gi.repository GObject version: {0}".format('.'.join(
         map(str, GObject.pygobject_version))))
     self.logger.debug("gi.repository Gtk version: {0}.{1}.{2}".format(
         Gtk.get_major_version(), Gtk.get_minor_version(),
         Gtk.get_micro_version()))
     if tools.has_vte:
         self.logger.debug("gi.repository VTE version: {0}".format(
             tools.Vte._version))
     if graphs.has_matplotlib:
         self.logger.debug("matplotlib version: {0}".format(
             graphs.matplotlib.__version__))
     self.set_property('application-id', 'org.king-phisher.client')
     self.set_property('register-session', True)
     self.config_file = (config_file or CONFIG_FILE_PATH)
     """The file containing the King Phisher client configuration."""
     self.config = None
     """The main King Phisher client configuration."""
     try:
         self.load_config(load_defaults=True)
     except IOError:
         self.logger.critical('failed to load the client configuration')
         raise
Exemple #6
0
    def create_context_menu(self, widget):

        if self.popup_menu:
            return

        if Gtk.get_major_version() == 4:
            if isinstance(widget, (Gtk.TextView, Gtk.TreeView)):
                """ In GTK 4, attaching directly to a Gtk.TextView or Gtk.TreeView seems to cause
                issues related to resizing the menu and updating the hover state of menu items.
                Wrap the GtkScrolledWindow parent of Gtk.TextView and Gtk.TreeView in a Gtk.Box and
                attach to it instead. """

                while not isinstance(widget, Gtk.Box):
                    widget = widget.get_parent()

            self.popup_menu = Gtk.PopoverMenu.new_from_model_full(
                self, Gtk.PopoverMenuFlags.NESTED)
            self.popup_menu.set_parent(widget)
            self.popup_menu.set_has_arrow(False)
            self.popup_menu.present()
            return

        if isinstance(widget, (Gtk.Button, Gtk.TreeView)):
            """ In GTK 3, attaching directly to a Gtk.Button or Gtk.TreeView seems to cause
            theming issues with checkboxes. Attach to the nearest Gtk.Box instead. """

            while not isinstance(widget, Gtk.Box):
                widget = widget.get_parent()

        self.popup_menu = Gtk.Menu.new_from_model(self)
        self.popup_menu.attach_to_widget(widget, None)
Exemple #7
0
    def connect_events(self, widget):

        if Gtk.get_major_version() == 4:
            self.gesture_click = Gtk.GestureClick()
            widget.add_controller(self.gesture_click)

            self.gesture_press = Gtk.GestureLongPress()
            widget.add_controller(self.gesture_press)

            self.shortcut_controller = Gtk.ShortcutController()
            self.shortcut_controller.set_scope(Gtk.ShortcutScope.LOCAL)
            self.shortcut_controller.add_shortcut(
                Gtk.Shortcut(
                    trigger=Gtk.ShortcutTrigger.parse_string("<Shift>F10"),
                    action=Gtk.CallbackAction.new(self._callback_menu),
                ))
            widget.add_controller(self.shortcut_controller)

        else:
            self.gesture_click = Gtk.GestureMultiPress.new(widget)
            self.gesture_press = Gtk.GestureLongPress.new(widget)

            # Shift+F10
            widget.connect("popup-menu", self._callback_menu)

        self.gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
        self.gesture_click.set_button(Gdk.BUTTON_SECONDARY)
        self.gesture_click.connect("pressed", self._callback_click)

        self.gesture_press.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
        self.gesture_press.set_touch_only(True)
        self.gesture_press.connect("pressed", self._callback)
Exemple #8
0
    def popup(self, x, y, controller=None, button=3):

        self.create_context_menu(self.widget)

        if Gtk.get_major_version() == 4:
            if not x and not y:
                x = y = 0

            self.popup_menu.set_halign(Gtk.Align.START)
            self.popup_menu.set_offset(x, y)
            self.popup_menu.set_pointing_to(Gdk.Rectangle(x, y, 1, 1))
            self.popup_menu.popup()
            return

        try:
            if controller:
                sequence = controller.get_current_sequence()
                event = controller.get_last_event(sequence)
            else:
                event = None

            self.popup_menu.popup_at_pointer(event)

        except (AttributeError, TypeError):
            time = Gtk.get_current_event_time()
            self.popup_menu.popup(None, None, None, None, button, time)
Exemple #9
0
    def _pack_children(self):

        self._remove_tab_label()
        self._remove_close_button()

        if sys.platform == "darwin":
            # Left align close button on macOS
            self._add_close_button()

        if Gtk.get_major_version() == 4:
            self.eventbox = Gtk.Box()
        else:
            self.eventbox = Gtk.EventBox()

        self.box = Gtk.Box()
        self.box.set_spacing(6)

        self.add(self.eventbox)
        self.eventbox.add(self.box)
        self.eventbox.show()

        if self.centered:
            self.set_halign(Gtk.Align.CENTER)
        else:
            self.set_halign(Gtk.Align.FILL)

        self.box.add(self.status_image)
        self.box.add(self.label)
        self.box.add(self.hilite_image)
        self.box.show()

        if sys.platform != "darwin":
            self._add_close_button()
Exemple #10
0
def get_libs_version_string():
    """Get a string describing the versions of important libs.

    >>> type(get_libs_version_string()) == str
    True

    """
    versions = [
        ("Python", "{major}.{minor}.{micro}".format(
            major=sys.version_info.major,
            minor=sys.version_info.minor,
            micro=sys.version_info.micro,
        )),
        ("GTK", "{major}.{minor}.{micro}".format(
            major=Gtk.get_major_version(),
            minor=Gtk.get_minor_version(),
            micro=Gtk.get_micro_version(),
        )),
        ("GdkPixbuf", GdkPixbuf.PIXBUF_VERSION),
        ("Cairo", cairo.cairo_version_string()),  # NOT cairo.version
        ("GLib", "{major}.{minor}.{micro}".format(
            major=GLib.MAJOR_VERSION,
            minor=GLib.MINOR_VERSION,
            micro=GLib.MICRO_VERSION,
        )),
    ]
    return ", ".join([" ".join(t) for t in versions])
Exemple #11
0
def main():
    """
    Main function that starts everything
    """
    if is_wayland() and gdk_backend().lower() != 'x11' and not is_wayland_compatibility_on():
        warn = """
                    [!]
        Looks like you are in Wayland session
        Please run Ulauncher with env var
        GDK_BACKEND set to 'x11' like this:

        GDK_BACKEND=x11 ulauncher
        """
        print(warn, file=sys.stderr)
        sys.exit(1)

    # start DBus loop
    DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus()
    instance = bus.request_name(DBUS_SERVICE)

    if instance != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
        toggle_window = dbus.SessionBus().get_object(DBUS_SERVICE, DBUS_PATH).get_dbus_method("toggle_window")
        toggle_window()
        return

    _create_dirs()

    options = get_options()
    setup_logging(options)
    logger = logging.getLogger('ulauncher')
    logger.info('Ulauncher version %s' % get_version())
    logger.info("GTK+ %s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()))
    logger.info("Is Wayland: %s" % is_wayland())
    logger.info("Wayland compatibility: %s" % ('on' if is_wayland_compatibility_on() else 'off'))

    # log uncaught exceptions
    def except_hook(exctype, value, tb):
        logger.error("Uncaught exception", exc_info=(exctype, value, tb))

    sys.excepthook = except_hook

    window = UlauncherWindow.get_instance()
    UlauncherDbusService(window)
    if not options.hide_window:
        window.show()

    if Settings.get_instance().get_property('show-indicator-icon'):
        AppIndicator.get_instance().show()

    # workaround to make Ctrl+C quiting the app
    signal_handler = SignalHandler(window)
    gtk_thread = run_async(Gtk.main)()
    try:
        while gtk_thread.is_alive() and not signal_handler.killed():
            time.sleep(0.5)
    except KeyboardInterrupt:
        logger.warn('On KeyboardInterrupt')
    finally:
        Gtk.main_quit()
Exemple #12
0
    def _get_sys_information(self):
        """
        Get relevant system information.
        """
        if hasattr(os, "uname"):
            operatingsystem = os.uname()[0]
            distribution = os.uname()[2]
        else:
            operatingsystem = sys.platform
            distribution = " "

        return "Python version: %s \n"\
               "BSDDB version: %s \n"\
               "Gramps version: %s \n"\
               "LANG: %s\n"\
               "OS: %s\n"\
               "Distribution: %s\n\n"\
               "GTK version    : %s\n"\
               "gobject version: %s\n"\
               "cairo version  : %s"\
               % (str(sys.version).replace('\n',''),
                  str(bsddb.__version__) + " " + str(bsddb.db.version()),
                  str(VERSION),
                  get_env_var('LANG',''),
                  operatingsystem,
                  distribution,
                  '%d.%d.%d' % (Gtk.get_major_version(),
                            Gtk.get_minor_version(), Gtk.get_micro_version()),
                  '%d.%d.%d' % GObject.pygobject_version,
                  cairo.version_info)
    def __init__(self, button, parent, chooser_type="file", selected_function=None):

        self.parent = parent
        self.button = button
        self.chooser_type = chooser_type
        self.selected_function = selected_function
        self.path = ""

        box = Gtk.Box()
        box.set_spacing(6)
        self.icon = Gtk.Image.new()

        if chooser_type == "folder":
            self.icon.set_property("icon-name", "folder-symbolic")

        elif chooser_type == "image":
            self.icon.set_property("icon-name", "image-x-generic-symbolic")

        else:
            self.icon.set_property("icon-name", "text-x-generic-symbolic")

        self.label = Gtk.Label.new(_("(None)"))
        box.add(self.icon)
        box.add(self.label)

        if Gtk.get_major_version() == 4:
            self.button.set_child(box)
        else:
            self.button.add(box)
            self.button.show_all()

        self.button.connect("clicked", self.open_file_chooser)
def save_file(parent, callback, callback_data=None, initialdir="~", initialfile="", title=None):

    try:
        self = Gtk.FileChooserNative.new(
            parent=parent,
            title=title,
            action=Gtk.FileChooserAction.SAVE
        )
    except AttributeError:
        self = Gtk.FileChooserDialog(
            parent=parent,
            title=title,
            action=Gtk.FileChooserAction.SAVE
        )
        self.add_buttons(_("_Cancel"), Gtk.ResponseType.CANCEL, _("_Save"), Gtk.ResponseType.ACCEPT)

    global active_chooser
    active_chooser = self

    self.connect("response", _on_selected, callback, callback_data)
    self.set_modal(True)
    self.set_select_multiple(False)

    if Gtk.get_major_version() == 3:
        self.set_show_hidden(True)

    _set_filechooser_folder(self, initialdir)
    self.set_current_name(initialfile)
    self.show()
    def make_zoom_out(self, *_args):
        def calc_zoom_out(w_h):
            return w_h + w_h * self.actual_zoom / 100 - w_h * self.zoom_factor / 100

        import gc

        if self.picture is None or self.picture_data is None:
            return

        width = self.picture_data.get_width()
        height = self.picture_data.get_height()

        self.actual_zoom -= self.zoom_factor

        if calc_zoom_out(width) < 10 or calc_zoom_out(height) < 10:
            self.actual_zoom += self.zoom_factor
            return

        picture_zoomed = self.picture_data.scale_simple(
            calc_zoom_out(width), calc_zoom_out(height),
            GdkPixbuf.InterpType.BILINEAR)

        if Gtk.get_major_version() == 4:
            self.picture.set_pixbuf(picture_zoomed)
        else:
            self.picture.set_from_pixbuf(picture_zoomed)

        del picture_zoomed
        gc.collect()
    def make_zoom_in(self, *_args, zoom=None):
        def calc_zoom_in(w_h):
            return w_h + w_h * self.actual_zoom / 100 + w_h * self.zoom_factor / 100

        import gc

        if self.picture is None or self.picture_data is None or self.actual_zoom > 100:
            return

        width = self.picture_data.get_width()
        height = self.picture_data.get_height()

        if zoom:
            self.actual_zoom = 0
            picture_zoomed = self.picture_data

        else:
            self.actual_zoom += self.zoom_factor
            picture_zoomed = self.picture_data.scale_simple(
                calc_zoom_in(width), calc_zoom_in(height),
                GdkPixbuf.InterpType.BILINEAR)

        if Gtk.get_major_version() == 4:
            self.picture.set_pixbuf(picture_zoomed)
        else:
            self.picture.set_from_pixbuf(picture_zoomed)

        del picture_zoomed
        gc.collect()
Exemple #17
0
def scrolled_window(view):
    scrolled_window = Gtk.ScrolledWindow()
    scrolled_window.add(
        view
    ) if Gtk.get_major_version() == 3 else scrolled_window.set_child(view)
    view.update()
    return scrolled_window
Exemple #18
0
    def __init__(self, baud_rate, *args, **kwargs):
        self.selected_port = ''
        self.baud_rate = baud_rate
        self.builder = Gtk.Builder()
        my_dir = os.path.dirname(__file__)
        self.builder.add_from_file(os.path.join(my_dir, "PyxbMainWin.glade"))

        self.win = self.builder.get_object("PyxbMainWin")
        "top-level widget for whole window"
        self.close_btn = self.builder.get_object("btnClose")
        assert isinstance(self.close_btn, Gtk.Button)
        self.ports_list = self.builder.get_object("liststore1")
        "model for device list"
        assert isinstance(self.ports_list, Gtk.TreeModel)
        self.ports_view = self._init_ports_view()
        "view for device list"
        assert isinstance(self.ports_view, Gtk.TreeView)

        self.chkSerial = self.builder.get_object("chkSerial")
        assert isinstance(self.chkSerial, Gtk.ToggleButton)
        self.chkUSB = self.builder.get_object("chkUSB")
        assert isinstance(self.chkUSB, Gtk.ToggleButton)
        self.chooser = GtkPortChooser(self.ports_list, self.ports_view,
                                      self.chkSerial,
                                      self.chkUSB,
                                      self)
        self.chooser.updateList()
        self.stg_notebook = self.builder.get_object("settings_notebook")
        assert isinstance(self.stg_notebook, Gtk.Notebook)
        self.page1_child = self.builder.get_object("stg_pg1_child")
        assert isinstance(self.page1_child, Gtk.Grid)

        self.page2_child = self._add_new_notebook_page("Network1")
        self.page3_child = self._add_new_notebook_page("Network2")

        self.text_view = self.builder.get_object("textview1")
        "Text output box"
        assert isinstance(self.text_view, Gtk.TextView)

        #make the standard close box for window work
        #for some reason bad things happen if we try do this with handlers dict below
        self.win.connect("delete-event", Gtk.main_quit)

        #connect action handlers to code objects
        handlers = {
            #close button
            "onCloseAction": Gtk.main_quit,
            #toggle checkbox on device listing
            "onSerialToggled": self.chooser.onSerialToggled,
            "onUSBToggled": self.chooser.onUSBToggled,
            #pick a specific device
            "onSelectDevice": self.chooser.onPortChosen,
        }
        self.builder.connect_signals(handlers)

        self.chooser.updateList()
        buff = self.text_view.get_buffer()
        buff.insert_at_cursor("{}.{}.{}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()))

        self.win.show_all()
Exemple #19
0
    def __init__(self, app):
        """Create the necessary objects and settings.

        Args:
            app: The main vimiv application to interact with.
        """
        super().__init__(app)
        datadir = os.path.join(GLib.get_user_data_dir(), "vimiv")
        os.makedirs(datadir, exist_ok=True)
        self.filename = os.path.join(datadir, "vimiv.log")
        self.terminal = sys.stderr
        # Redirect stderr in debug mode so it is written to the log file as well
        if app.debug:
            sys.stderr = self
        # Create a new log file at startup
        with open(self.filename, "w") as f:
            f.write("Vimiv log written to "
                    + self.filename.replace(os.getenv("HOME"), "~")
                    + "\n")
        self.write_separator()
        # Header containing version and Gtk version
        information = self.get_component(Information)
        self.write_message("Version", information.get_version())
        self.write_message("Python", sys.version.split()[0])
        gtk_version = str(Gtk.get_major_version()) + "." \
            + str(Gtk.get_minor_version()) + "." \
            + str(Gtk.get_micro_version())
        self.write_message("GTK", gtk_version)
        self.write_separator()
        # Start time
        self.write_message("Started", "time")
def gtk_version():
    '''
    returns float of the major and minor parts of the GTK version
    e.g. return float(3.10)
    '''

    return float(str(Gtk.get_major_version()) + "." + str(Gtk.get_minor_version()))
Exemple #21
0
def main(root_path, filename):
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    print "GTK+ version:", gtk_version
    editorstate.gtk_version = gtk_version
    try:
        editorstate.mlt_version = mlt.LIBMLT_VERSION
    except:
        editorstate.mlt_version = "0.0.99" # magic string for "not found"

    # Create user folders if need and determine if were using xdg or dotfile userf folders.
    userfolders.init()

    # Set paths.
    respaths.set_paths(root_path)

    # Load editor prefs and list of recent projects
    editorpersistance.load()
    
    # Init translations module with translations data
    translations.init_languages()
    translations.load_filters_translations()
    mlttransitions.init_module()

    # Init gtk threads
    Gdk.threads_init()
    Gdk.threads_enter()

    # Themes
    if editorpersistance.prefs.theme != appconsts.LIGHT_THEME:
        Gtk.Settings.get_default().set_property("gtk-application-prefer-dark-theme", True)
        if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME:
            gui.apply_gtk_css()

    repo = mlt.Factory().init()
    processutils.prepare_mlt_repo(repo)
    
    # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs 
    locale.setlocale(locale.LC_NUMERIC, 'C')

    # Check for codecs and formats on the system
    mltenv.check_available_features(repo)
    renderconsumer.load_render_profiles()

    # Load filter and compositor descriptions from xml files.
    mltfilters.load_filters_xml(mltenv.services)
    mlttransitions.load_compositors_xml(mltenv.transitions)

    # Create list of available mlt profiles
    mltprofiles.load_profile_list()

    appconsts.SAVEFILE_VERSION = projectdata.SAVEFILE_VERSION

    global linker_window
    linker_window = MediaLinkerWindow()

    if filename != NO_PROJECT_AT_LAUNCH:
        linker_window.load_project(filename)

    Gtk.main()
    Gdk.threads_leave()
Exemple #22
0
    def __init__(self, frame):

        self.frame = frame
        self.dialog = Gtk.AboutDialog(
            comments=config.summary,
            copyright=config.copyright,
            license_type=Gtk.License.GPL_3_0,
            version=config.version + "  •  GTK " + config.gtk_version,
            website=config.website_url,
            authors=self.AUTHORS.splitlines(),
            translator_credits=self.TRANSLATORS + config.translations_url)
        set_dialog_properties(self.dialog, frame.MainWindow)
        main_icon = get_icon("n")

        if not main_icon:
            self.dialog.set_logo_icon_name(config.application_id)

        if Gtk.get_major_version() == 4:
            self.dialog.connect("close-request", lambda x: x.destroy())

            if main_icon:
                icon_data = ICON_THEME.lookup_by_gicon(main_icon, 128, 2, 0, 0)
                self.dialog.set_logo(icon_data)
        else:
            self.dialog.connect("response", lambda x, _y: x.destroy())

        # Override link handler with our own
        self.dialog.connect("activate-link", lambda x, url: open_uri(url))
Exemple #23
0
    def undock(self, widget):
        """ remove the widget from the leaf-notebook
            if this was the only widget, remove this leaf from its owner """

        gtk_version = (Gtk.get_major_version(), Gtk.get_minor_version())
        if gtk_version >= (3, 16):
            self.book.detach_tab(widget)
        else:
            # To not destroy accidentally our panel widget we need to add a reference to it
            # https://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Container.html#Gtk.Container.remove
            widget._ref()
            self.book.remove(widget)

        for i, (widget_, title, id) in enumerate(self.panels):
            if widget_ == widget:
                break
        else:
            raise KeyError("No %s in %s" % (widget, self))
        del self.panels[i]

        if self.book.get_n_pages() == 0:
            parent = self.get_parent()
            while not isinstance(parent, PyDockComposite):
                parent = parent.get_parent()
            parent.removeComponent(self)
            self._del()

        return title, id
Exemple #24
0
    def do_startup(self):
        Gtk.Application.do_startup(self)

        if self.purge_recent:
            items = recent_manager.get_items()
            for item in items:
                uri = item.get_uri()
                if item.get_application_info("pychess"):
                    recent_manager.remove_item(uri)

        self.git_rev = ""

        self.initGlade(self.log_viewer)
        self.addPerspectives()
        self.handleArgs(self.chess_file)
        create_task(checkversion())

        self.loaded_cids = {}
        self.saved_cids = {}
        self.terminated_cids = {}

        log.info("PyChess %s %s git %s" %
                 (VERSION_NAME, VERSION, self.git_rev))
        log.info("Command line args: '%s'" % self.chess_file)
        log.info("Platform: %s" % platform.platform())
        log.info("Python version: %s.%s.%s" % sys.version_info[0:3])
        log.info("Pyglib version: %s.%s.%s" % GLib.pyglib_version)
        log.info("Gtk version: %s.%s.%s" %
                 (Gtk.get_major_version(), Gtk.get_minor_version(),
                  Gtk.get_micro_version()))
    def _get_sys_information(self):
        """
        Get relevant system information.
        """
        distribution = ""  # print nothing if there's nothing to print
        if hasattr(os, "uname"):
            distribution = "Distribution: %s\n" % os.uname()[2]

        sqlite = ''
        if __debug__:
            sqlite = "sqlite version: %s (%s) \n" % (sqlite3_version_str,
                                                     sqlite3_py_version_str)

        return "Gramps version: %s \n"\
               "Python version: %s \n"\
               "BSDDB version: %s \n"\
               "%s"\
               "LANG: %s\n"\
               "OS: %s\n"\
               "%s\n"\
               "GTK version    : %s\n"\
               "gobject version: %s\n"\
               "cairo version  : %s"\
               % (str(VERSION),
                  str(sys.version).replace('\n',''),
                  BSDDB_STR,
                  sqlite,
                  get_env_var('LANG',''),
                  platform.system(),
                  distribution,
                  '%d.%d.%d' % (Gtk.get_major_version(),
                                Gtk.get_minor_version(),
                                Gtk.get_micro_version()),
                  '%d.%d.%d' % GObject.pygobject_version,
                  cairo.version_info)
Exemple #26
0
def check_gtk_version():
    """ Check GTK version """
    # Check desired GTK Version
    major_needed = int(GTK_VERSION_NEEDED.split(".")[0])
    minor_needed = int(GTK_VERSION_NEEDED.split(".")[1])
    micro_needed = int(GTK_VERSION_NEEDED.split(".")[2])

    # Check system GTK Version
    major = Gtk.get_major_version()
    minor = Gtk.get_minor_version()
    micro = Gtk.get_micro_version()

    # Cnchi will be called from our liveCD that already
    # has the latest GTK version. This is here just to
    # help testing Cnchi in our environment.
    wrong_gtk_version = False
    if major_needed > major:
        wrong_gtk_version = True
    if major_needed == major and minor_needed > minor:
        wrong_gtk_version = True
    if major_needed == major and minor_needed == minor and micro_needed > micro:
        wrong_gtk_version = True

    if wrong_gtk_version:
        text = "Detected GTK version {0}.{1}.{2} but version>={3} is needed."
        text = text.format(major, minor, micro, GTK_VERSION_NEEDED)
        logging.info(text)
        return False
    else:
        logging.info("Using GTK v{0}.{1}.{2}".format(major, minor, micro))

    return True
 def shortcuts_dialog():
     if Gtk.get_major_version() >= 3 and Gtk.get_minor_version() >= 20:
         builder = Gtk.Builder()
         builder.add_from_resource('/org/gnome/TwoFactorAuth/shortcuts.ui')
         shortcuts = builder.get_object("shortcuts")
         return shortcuts
     return None
Exemple #28
0
    def do_startup(self):
        Gtk.Application.do_startup(self)
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        action = Gio.SimpleAction.new("stations", None)
        action.connect("activate", self.stations_cb)
        self.add_action(action)

        action = Gio.SimpleAction.new("preferences", None)
        action.connect("activate", self.prefs_cb)
        self.add_action(action)

        action = Gio.SimpleAction.new("about", None)
        action.connect("activate", self.about_cb)
        self.add_action(action)

        action = Gio.SimpleAction.new("quit", None)
        action.connect("activate", self.quit_cb)
        self.add_action(action)

        if Gtk.get_major_version() > 3 or Gtk.get_minor_version() >= 20:
            menu = self.get_app_menu()
            it = menu.iterate_item_links(menu.get_n_items() - 1)
            assert(it.next())
            last_section = it.get_value()
            shortcuts_item = Gio.MenuItem.new(_('Keyboard Shortcuts'), 'win.show-help-overlay')
            last_section.prepend_item(shortcuts_item)
    def _get_sys_information(self):
        """
        Get relevant system information.
        """
        distribution = "" # print nothing if there's nothing to print
        if hasattr(os, "uname"):
            distribution = "Distribution: %s\n" % os.uname()[2]

        sqlite = "sqlite version: %s (%s) \n" % (sqlite3_version_str,
                                                 sqlite3_py_version_str)

        return "Gramps version: %s \n"\
               "Python version: %s \n"\
               "BSDDB version: %s \n"\
               "%s"\
               "LANG: %s\n"\
               "OS: %s\n"\
               "%s\n"\
               "GTK version    : %s\n"\
               "gobject version: %s\n"\
               "cairo version  : %s"\
               % (str(VERSION),
                  str(sys.version).replace('\n',''),
                  BSDDB_STR,
                  sqlite,
                  get_env_var('LANG',''),
                  platform.system(),
                  distribution,
                  '%d.%d.%d' % (Gtk.get_major_version(),
                                Gtk.get_minor_version(),
                                Gtk.get_micro_version()),
                  '%d.%d.%d' % GObject.pygobject_version,
                  cairo.version_info)
    def _get_sys_information(self):
        """
        Get relevant system information.
        """
        if hasattr(os, "uname"):
            operatingsystem = os.uname()[0]
            distribution = os.uname()[2]
        else:
            operatingsystem = sys.platform
            distribution = " "

        return "Python version: %s \n"\
               "BSDDB version: %s \n"\
               "Gramps version: %s \n"\
               "LANG: %s\n"\
               "OS: %s\n"\
               "Distribution: %s\n\n"\
               "GTK version    : %s\n"\
               "gobject version: %s\n"\
               "cairo version  : %s"\
               % (str(sys.version).replace('\n',''),
                  BSDDB_STR,
                  str(VERSION),
                  get_env_var('LANG',''),
                  operatingsystem,
                  distribution,
                  '%d.%d.%d' % (Gtk.get_major_version(), 
                            Gtk.get_minor_version(), Gtk.get_micro_version()),
                  '%d.%d.%d' % GObject.pygobject_version,
                  cairo.version_info)
Exemple #31
0
 def send_bugreport(self):
     """
     Return None if successful. Return the urllib2 execption if failure.
     """
     try:
         windowsversion = str(sys.getwindowsversion())
     except AttributeError:
         windowsversion = "(not running ms windows)"
     buf = self.g_tw.get_buffer()
     description = buf.get_text(buf.get_start_iter(), buf.get_end_iter(),
                                False)
     data = urllib.urlencode({
         'email': self.g_email.get_text(),
         'version': buildinfo.VERSION_STRING,
         'revision_id': buildinfo.REVISION_ID,
         #'pygtk_version': "pygi",
         'gtk': "(%s.%s.%s)" % (Gtk.get_major_version(),
                                      Gtk.get_minor_version(),
                                      Gtk.get_micro_version()),
         'sys.version': sys.version,
         'sys.platform': sys.platform,
         'windowsversion': windowsversion,
         'short_description': self.g_description.get_text(),
         'description': description,
         'traceback': self.m_error_text,
     })
     try:
         urllib2.urlopen("http://www.solfege.org/crashreport/", data)
     except urllib2.HTTPError, e:
         print "HTTPError:", e
Exemple #32
0
def message_dialog(parent, title, message, callback=None):

    self = Gtk.MessageDialog(transient_for=parent,
                             message_type=Gtk.MessageType.INFO,
                             buttons=Gtk.ButtonsType.OK,
                             destroy_with_parent=True,
                             modal=True,
                             text=title,
                             secondary_text=message)

    if not callback:

        def callback(dialog, *_args):
            dialog.destroy()

    self.connect("response", callback)

    if Gtk.get_major_version() == 4:
        label = self.get_message_area().get_last_child()
    else:
        label = self.get_message_area().get_children()[-1]

    label.set_selectable(True)

    self.present_with_time(Gdk.CURRENT_TIME)
Exemple #33
0
def get_libs_version_string():
    """Get a string describing the versions of important libs.

    >>> type(get_libs_version_string()) == str
    True

    """
    versions = [
        ("Python", "{major}.{minor}.{micro}".format(
            major = sys.version_info.major,
            minor = sys.version_info.minor,
            micro = sys.version_info.micro,
        )),
        ("GTK", "{major}.{minor}.{micro}".format(
            major = Gtk.get_major_version(),
            minor = Gtk.get_minor_version(),
            micro = Gtk.get_micro_version(),
        )),
        ("GdkPixbuf", GdkPixbuf.PIXBUF_VERSION),
        ("Cairo", cairo.cairo_version_string()),  # NOT cairo.version
        ("GLib", "{major}.{minor}.{micro}".format(
            major = GLib.MAJOR_VERSION,
            minor = GLib.MINOR_VERSION,
            micro = GLib.MICRO_VERSION,
        )),
    ]
    return ", ".join([" ".join(t) for t in versions])
Exemple #34
0
    def do_startup(self):
        Gtk.Application.do_startup(self)

        if self.purge_recent:
            items = recent_manager.get_items()
            for item in items:
                uri = item.get_uri()
                if item.get_application_info("pychess"):
                    recent_manager.remove_item(uri)

        self.git_rev = ""

        self.initGlade(self.log_viewer)
        self.addPerspectives()
        self.handleArgs(self.chess_file)
        create_task(checkversion())

        self.loaded_cids = {}
        self.saved_cids = {}
        self.terminated_cids = {}

        log.info("PyChess %s %s git %s" % (VERSION_NAME, VERSION, self.git_rev))
        log.info("Command line args: '%s'" % self.chess_file)
        log.info("Platform: %s" % platform.platform())
        log.info("Python version: %s.%s.%s" % sys.version_info[0:3])
        log.info("Pyglib version: %s.%s.%s" % GLib.pyglib_version)
        log.info("Gtk version: %s.%s.%s" % (Gtk.get_major_version(),
                                            Gtk.get_minor_version(),
                                            Gtk.get_micro_version()))
	def __init__(self, config_file=None):
		super(KingPhisherClientApplication, self).__init__()
		self.logger = logging.getLogger('KingPhisher.Client.Application')
		# log version information for debugging purposes
		self.logger.debug("gi.repository GLib version: {0}".format('.'.join(map(str, GLib.glib_version))))
		self.logger.debug("gi.repository GObject version: {0}".format('.'.join(map(str, GObject.pygobject_version))))
		self.logger.debug("gi.repository Gtk version: {0}.{1}.{2}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()))
		if tools.has_vte:
			self.logger.debug("gi.repository VTE version: {0}".format(tools.Vte._version))
		if graphs.has_matplotlib:
			self.logger.debug("matplotlib version: {0}".format(graphs.matplotlib.__version__))
		self.set_property('application-id', 'org.king-phisher.client')
		self.set_property('register-session', True)
		self.config_file = (config_file or CONFIG_FILE_PATH)
		"""The file containing the King Phisher client configuration."""
		self.config = None
		"""The primary King Phisher client configuration."""
		self.main_window = None
		"""The primary top-level :py:class:`~.MainApplicationWindow` instance."""
		self.rpc = None
		"""The :py:class:`~.KingPhisherRPCClient` instance for the application."""
		self._ssh_forwarder = None
		"""The SSH forwarder responsible for tunneling RPC communications."""
		self.style_provider = None
		try:
			self.load_config(load_defaults=True)
		except IOError:
			self.logger.critical('failed to load the client configuration')
			raise

		self.connect('window-added', self.signal_window_added)
		self.actions = {}
		self._create_actions()
Exemple #36
0
    def prepare_content_display(item, textview=None):
        if textview is None:
            text_view = Gtk.TextView()
        else:
            text_view = textview

        text_view.set_name('storyview') # For CSS

        # Border sizes
        if Gtk.get_major_version() == 3 and Gtk.get_minor_version() >= 20:
            text_view.set_left_margin(12)
            text_view.set_right_margin(12)
            text_view.set_bottom_margin(5)
            text_view.set_top_margin(5)
        else:
            text_view.set_border_window_size(Gtk.TextWindowType.LEFT, 10)
            text_view.set_border_window_size(Gtk.TextWindowType.RIGHT, 12)  # Slightly more than left due to scroll bar
            text_view.set_border_window_size(Gtk.TextWindowType.TOP, 5)
            text_view.set_border_window_size(Gtk.TextWindowType.TOP, 5)

        text_view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
        text_view.set_editable(False)
        text_view.set_cursor_visible(False)

        text_buffer = Gtk.TextBuffer()
        text_view.set_buffer(text_buffer)

        if item:
            TextFormat.headline(item.title, text_buffer)
            TextFormat.description(item.description, text_buffer)
            TextFormat.article(item.article, text_buffer)
        return text_view
    def generate_menu(self):
        # Settings section
        settings_content = Gio.Menu.new()
        settings_content.append_item(
            Gio.MenuItem.new(_("Settings"), "app.settings"))
        self.is_dark_mode_menu = Gio.MenuItem.new(_("Night mode"),
                                                  "app.night_mode")
        settings_content.append_item(self.is_dark_mode_menu)
        settings_section = Gio.MenuItem.new_section(None, settings_content)
        self.menu.append_item(settings_section)

        # Help section
        help_content = Gio.Menu.new()
        if Gtk.get_major_version() >= 3 and Gtk.get_minor_version() >= 20:
            help_content.append_item(
                Gio.MenuItem.new(_("Shortcuts"), "app.shortcuts"))

        help_content.append_item(Gio.MenuItem.new(_("About"), "app.about"))
        help_content.append_item(Gio.MenuItem.new(_("Quit"), "app.quit"))
        help_section = Gio.MenuItem.new_section(None, help_content)
        self.menu.append_item(help_section)

        self.dark_mode_action = Gio.SimpleAction.new("night_mode", None)
        self.dark_mode_action.connect("activate", self.enable_dark_mode)
        self.add_action(self.dark_mode_action)

        self.settings_action = Gio.SimpleAction.new("settings", None)
        self.settings_action.connect("activate", self.on_settings)
        self.settings_action.set_enabled(not self.locked)
        self.add_action(self.settings_action)

        if Gtk.get_major_version() >= 3 and Gtk.get_minor_version() >= 20:
            action = Gio.SimpleAction.new("shortcuts", None)
            action.connect("activate", self.on_shortcuts)
            self.add_action(action)

        action = Gio.SimpleAction.new("about", None)
        action.connect("activate", self.on_about)
        self.add_action(action)

        action = Gio.SimpleAction.new("quit", None)
        action.connect("activate", self.on_quit)
        self.add_action(action)
        self.refresh_menu_night_mode()
        if not show_app_menu():
            self.set_app_menu(self.menu)
            logging.debug("Adding gnome shell menu")
def main(root_path, force_launch=False):
    init_dirs_if_needed()
    
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    editorstate.gtk_version = gtk_version
    try:
        editorstate.mlt_version = mlt.LIBMLT_VERSION
    except:
        editorstate.mlt_version = "0.0.99" # magic string for "not found"
        
    # Set paths.
    respaths.set_paths(root_path)

    # Load editor prefs and list of recent projects
    editorpersistance.load()
    
    # Init translations module with translations data
    translations.init_languages()
    translations.load_filters_translations()
    mlttransitions.init_module()

    # Init gtk threads
    Gdk.threads_init()
    Gdk.threads_enter()

    repo = mlt.Factory().init()

    # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs 
    locale.setlocale(locale.LC_NUMERIC, 'C')

    # Check for codecs and formats on the system
    mltenv.check_available_features(repo)
    renderconsumer.load_render_profiles()

    # Load filter and compositor descriptions from xml files.
    mltfilters.load_filters_xml(mltenv.services)
    mlttransitions.load_compositors_xml(mltenv.transitions)

    # Create list of available mlt profiles
    mltprofiles.load_profile_list()

    global render_queue
    render_queue = RenderQueue()
    render_queue.load_render_items()

    global batch_window
    batch_window = BatchRenderWindow()

    if render_queue.error_status != None:
        primary_txt = _("Error loading render queue items!")
        secondary_txt = _("Message:\n") + render_queue.get_error_status_message()
        dialogutils.warning_message(primary_txt, secondary_txt, batch_window.window)

    DBusGMainLoop(set_as_default=True)
    global _dbus_service
    _dbus_service = BatchRenderDBUSService()

    Gtk.main()
    Gdk.threads_leave()
Exemple #39
0
    def __init__(self):
        self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL, title=_("Ask for permissions"))
        self.window.set_transient_for(mainwindow())
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        gtk_version = (Gtk.get_major_version(), Gtk.get_minor_version())
        if gtk_version >= (3, 12):
            vbox.props.margin_start = 9
            vbox.props.margin_end = 9
        else:
            vbox.props.margin_left = 9
            vbox.props.margin_right = 9
        vbox.props.margin_bottom = 9
        self.window.add(vbox)
        uistuff.keepWindowSize("externalsdialog", self.window, (320, 240), uistuff.POSITION_CENTER)

        label = Gtk.Label(_("Some of PyChess features needs your permission to download external programs"))
        vbox.pack_start(label, True, True, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("database querying needs scoutfish"))
        check_button.set_active(conf.get("download_scoutfish", False))
        check_button.connect("toggled", lambda w: conf.set("download_scoutfish", w.get_active()))
        box.add(check_button)
        link = "https://github.com/pychess/scoutfish"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("database opening tree needs chess_db"))
        check_button.set_active(conf.get("download_chess_db", False))
        check_button.connect("toggled", lambda w: conf.set("download_chess_db", w.get_active()))
        box.add(check_button)
        link = "https://github.com/pychess/chess_db"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("ICC lag compensation needs timestamp"))
        check_button.set_active(conf.get("download_timestamp", False))
        check_button.connect("toggled", lambda w: conf.set("download_timestamp", w.get_active()))
        box.add(check_button)
        link = "http://download.chessclub.com/timestamp/"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        check_button = Gtk.CheckButton(_("Don't show this dialog on startup."))
        check_button.set_active(conf.get("dont_show_externals_at_startup", False))
        check_button.connect("toggled", lambda w: conf.set("dont_show_externals_at_startup", w.get_active()))
        vbox.pack_start(check_button, True, True, 0)

        buttonbox = Gtk.ButtonBox()
        close_button = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
        close_button.connect("clicked", self.on_close_clicked)
        self.window.connect("delete_event", lambda w, a: self.window.destroy())
        buttonbox.add(close_button)
        vbox.pack_start(buttonbox, False, False, 0)
    def __init__(self):
        self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL, title=_("Ask for permissions"))
        self.window.set_transient_for(mainwindow())
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        gtk_version = (Gtk.get_major_version(), Gtk.get_minor_version())
        if gtk_version >= (3, 12):
            vbox.props.margin_start = 9
            vbox.props.margin_end = 9
        else:
            vbox.props.margin_left = 9
            vbox.props.margin_right = 9
        vbox.props.margin_bottom = 9
        self.window.add(vbox)
        uistuff.keepWindowSize("externalsdialog", self.window, (320, 240), uistuff.POSITION_CENTER)

        label = Gtk.Label(_("Some of PyChess features needs your permission to download external programs"))
        vbox.pack_start(label, True, True, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("database querying needs scoutfish"))
        check_button.set_active(conf.get("download_scoutfish", False))
        check_button.connect("toggled", lambda w: conf.set("download_scoutfish", w.get_active()))
        box.add(check_button)
        link = "https://github.com/pychess/scoutfish"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("database opening tree needs chess_db"))
        check_button.set_active(conf.get("download_chess_db", False))
        check_button.connect("toggled", lambda w: conf.set("download_chess_db", w.get_active()))
        box.add(check_button)
        link = "https://github.com/pychess/chess_db"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        box = Gtk.Box()
        check_button = Gtk.CheckButton(_("ICC lag compensation needs timestamp"))
        check_button.set_active(conf.get("download_timestamp", False))
        check_button.connect("toggled", lambda w: conf.set("download_timestamp", w.get_active()))
        box.add(check_button)
        link = "https://www.chessclub.com/user/resources/icc/timestamp"
        link_button = Gtk.LinkButton(link, link)
        box.add(link_button)
        vbox.pack_start(box, False, False, 0)

        check_button = Gtk.CheckButton(_("Don't show this dialog on startup."))
        check_button.set_active(conf.get("dont_show_externals_at_startup", False))
        check_button.connect("toggled", lambda w: conf.set("dont_show_externals_at_startup", w.get_active()))
        vbox.pack_start(check_button, True, True, 0)

        buttonbox = Gtk.ButtonBox()
        close_button = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
        close_button.connect("clicked", self.on_close_clicked)
        self.window.connect("delete_event", lambda w, a: self.window.destroy())
        buttonbox.add(close_button)
        vbox.pack_start(buttonbox, False, False, 0)
def gtk_version():
    '''
    returns float of the major and minor parts of the GTK version
    e.g. return float(3.10)
    '''

    return float(
        str(Gtk.get_major_version()) + "." + str(Gtk.get_minor_version()))
Exemple #42
0
def apply_gtk_css():
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(),
                                Gtk.get_minor_version(),
                                Gtk.get_micro_version())
    if Gtk.get_major_version() == 3 and Gtk.get_minor_version() == 22:
        print "Gtk version is " + gtk_version + ", Flowblade theme is available."
    else:
        print "Gtk version is " + gtk_version + ", Flowblade theme only available for Gtk 3.22"
        return

    provider = Gtk.CssProvider.new()
    display = Gdk.Display.get_default()
    screen = display.get_default_screen()
    Gtk.StyleContext.add_provider_for_screen(screen, provider,
                                             Gtk.STYLE_PROVIDER_PRIORITY_USER)

    provider.load_from_path(respaths.ROOT_PATH + "/res/css/gtk-dark-fix.css")
Exemple #43
0
def apply_gtk_css():
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    if Gtk.get_major_version() == 3 and Gtk.get_minor_version() >= 22:
        print "Gtk version is " + gtk_version + ", Flowblade theme is available."
    else:
        print "Gtk version is " + gtk_version + ", Flowblade theme only available for Gtk >= 3.22"
        editorpersistance.prefs.theme = appconsts.LIGHT_THEME
        editorpersistance.save()
        return False
        
    provider = Gtk.CssProvider.new()
    display = Gdk.Display.get_default()
    screen = display.get_default_screen()
    Gtk.StyleContext.add_provider_for_screen (screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
    provider.load_from_path(respaths.ROOT_PATH + "/res/css/gtk-flowblade-dark.css")

    return True
Exemple #44
0
def dialog_show(dialog):

    dialog.present_with_time(Gdk.CURRENT_TIME)

    if Gtk.get_major_version() == 3:
        dialog.get_window().set_functions(Gdk.WMFunction.RESIZE
                                          | Gdk.WMFunction.MOVE
                                          | Gdk.WMFunction.CLOSE)
Exemple #45
0
def gtk_version_newer_than(major=3, minor=0, micro=0):
    _major = Gtk.get_major_version()
    _minor = Gtk.get_minor_version()
    _micro = Gtk.get_micro_version()

    return (_major > major) or \
           (_major == major and _minor > minor) or \
           (_major == major and _minor == minor and _micro >= micro)
def test_can_remove_all_controllers(view):
    ctrl = (Gtk.EventControllerMotion.new(view) if Gtk.get_major_version() == 3
            else Gtk.EventControllerMotion.new())
    view.add_controller(ctrl)

    view.remove_all_controllers()

    assert ctrl.get_propagation_phase() == Gtk.PropagationPhase.NONE
def choose_image(parent,
                 callback,
                 callback_data=None,
                 initialdir="~",
                 title=_("Select an Image"),
                 multiple=False):
    def on_update_image_preview(chooser):
        path = chooser.get_preview_filename()

        try:
            image_data = GdkPixbuf.Pixbuf.new_from_file(path)

            maxwidth, maxheight = 300.0, 700.0
            width, height = image_data.get_width(), image_data.get_height()
            scale = min(maxwidth / width, maxheight / height)

            if scale < 1:
                width, height = int(width * scale), int(height * scale)
                image_data = image_data.scale_simple(
                    width, height, GdkPixbuf.InterpType.BILINEAR)

            preview.set_from_pixbuf(image_data)
            chooser.set_preview_widget_active(True)

        except Exception:
            chooser.set_preview_widget_active(False)

    global ACTIVE_CHOOSER  # pylint:disable=global-statement
    try:
        self = ACTIVE_CHOOSER = Gtk.FileChooserNative(
            transient_for=parent,
            title=title,
            action=Gtk.FileChooserAction.OPEN)
    except AttributeError:
        self = ACTIVE_CHOOSER = Gtk.FileChooserDialog(
            transient_for=parent,
            title=title,
            action=Gtk.FileChooserAction.OPEN)
        self.add_buttons(_("_Cancel"), Gtk.ResponseType.CANCEL, _("_Open"),
                         Gtk.ResponseType.ACCEPT)

    self.connect("response", _on_selected, callback, callback_data)
    self.set_modal(True)

    if Gtk.get_major_version() == 3:
        # Display network shares
        self.set_local_only(False)

        # Image preview
        self.connect("update-preview", on_update_image_preview)

        preview = Gtk.Image()
        self.set_preview_widget(preview)

    self.set_select_multiple(multiple)

    _set_filechooser_folder(self, initialdir)
    self.show()
def main(root_path, filename):
    # This the main for launched process, this is reached via 'flowblademediaimport' laucher file
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(),
                                Gtk.get_minor_version(),
                                Gtk.get_micro_version())
    print "GTK+ version:", gtk_version
    editorstate.gtk_version = gtk_version
    try:
        editorstate.mlt_version = mlt.LIBMLT_VERSION
    except:
        editorstate.mlt_version = "0.0.99"  # magic string for "not found"

    # Read the XDG_* variables etc.
    userfolders.init()

    # Set paths.
    respaths.set_paths(root_path)

    # Load editor prefs and list of recent projects
    editorpersistance.load()

    # Init translations module with translations data
    translations.init_languages()
    translations.load_filters_translations()
    mlttransitions.init_module()

    # Init gtk threads
    Gdk.threads_init()
    Gdk.threads_enter()

    # Themes
    if editorpersistance.prefs.theme != appconsts.LIGHT_THEME:
        Gtk.Settings.get_default().set_property(
            "gtk-application-prefer-dark-theme", True)
        if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME:
            gui.apply_gtk_css()

    repo = mlt.Factory().init()
    processutils.prepare_mlt_repo(repo)

    # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs
    locale.setlocale(locale.LC_NUMERIC, 'C')

    # Check for codecs and formats on the system
    mltenv.check_available_features(repo)
    renderconsumer.load_render_profiles()

    # Load filter and compositor descriptions from xml files.
    mltfilters.load_filters_xml(mltenv.services)
    mlttransitions.load_compositors_xml(mltenv.transitions)

    # Create list of available mlt profiles
    mltprofiles.load_profile_list()

    GLib.idle_add(_do_assets_write, filename)

    Gtk.main()
    Gdk.threads_leave()
    def show(self):

        self.update_current_file()
        self.dialog.present_with_time(Gdk.CURRENT_TIME)

        if Gtk.get_major_version() == 3:
            self.dialog.get_window().set_functions(Gdk.WMFunction.RESIZE
                                                   | Gdk.WMFunction.MOVE
                                                   | Gdk.WMFunction.CLOSE)
Exemple #50
0
def copy_text(text):

    if Gtk.get_major_version() == 4:
        clipboard = Gdk.Display.get_default().get_clipboard()
        clipboard.set(text)
        return

    clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
    clipboard.set_text(text, -1)
def format_exception_details(exc_type, exc_value, exc_traceback, error_uid=None):
	"""
	Format exception details to be show to a human. This should include enough
	information about the type of error that occurred and the system on which
	it was triggered to allow someone to attempt to debug and fix it. The first
	three parameters to this function directly correspond to the values
	returned from the :py:func:`sys.exc_info` function.

	:param exc_type: The type of the exception.
	:param exc_value: The exception instance.
	:param exc_traceback: The traceback object corresponding to the exception.
	:param error_uid: A unique identifier for this exception.
	:type error_uid: str, :py:class:`uuid.UUID`
	:return: A formatted message containing the details about the exception and environment.
	:rtype: str
	"""
	if isinstance(error_uid, uuid.UUID):
		error_uid = str(error_uid)
	elif error_uid is None:
		error_uid = 'N/A'
	elif not isinstance(error_uid, str):
		raise TypeError('error_uid must be an instance of either str, uuid.UUID or None')
	pversion = 'UNKNOWN'
	if its.on_linux:
		pversion = 'Linux: ' + ' '.join(platform.linux_distribution())
	elif its.on_windows:
		pversion = 'Windows: ' + ' '.join(platform.win32_ver())
		if its.frozen:
			pversion += ' (Frozen=True)'
		else:
			pversion += ' (Frozen=False)'
	exc_name = format_exception_name(exc_type)
	rpc_error_details = 'N/A (Not a remote RPC error)'
	if isinstance(exc_value, advancedhttpserver.RPCError) and exc_value.is_remote_exception:
		rpc_error_details = "Name: {0}".format(exc_value.remote_exception['name'])
		if exc_value.remote_exception.get('message'):
			rpc_error_details += " Message: '{0}'".format(exc_value.remote_exception['message'])
	current_tid = threading.current_thread().ident
	thread_info = (
		"{0: >4}{1} (alive={2} daemon={3})".format(('=> ' if thread.ident == current_tid else ''), thread.name, thread.is_alive(), thread.daemon) for thread in threading.enumerate()
	)
	thread_info = '\n'.join(thread_info)
	details = EXCEPTION_DETAILS_TEMPLATE.format(
		error_details=repr(exc_value),
		error_type=exc_name,
		error_uid=error_uid,
		rpc_error_details=rpc_error_details,
		king_phisher_version=version.version,
		platform_version=pversion,
		python_version="{0}.{1}.{2}".format(*sys.version_info),
		gtk_version="{0}.{1}.{2}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()),
		stack_trace=''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)),
		thread_info=thread_info,
		timezone=tzlocal.get_localzone().zone
	)
	details = details.strip() + '\n'
	return details
Exemple #52
0
 def reverse_order(self):
     """
     Reverse the order of the map. Only for Gtk 3.9+ does this signal
     rows_reordered, so to propagate the change to the view, you need to
     reattach the model to the view. 
     """
     self.GTK38PLUS = (Gtk.get_major_version(), Gtk.get_minor_version()) >= (3,8)
     self.__reverse = not self.__reverse
     top_node = self.tree[None]
     self._reverse_level(top_node)
def backend_gtk3agg_internal_check(x):
    try:
        from gi.repository import Gtk, Gdk, GObject
    except ImportError:
        return (False, "Requires pygobject to be installed.")

    if sys.version_info[0] >= 3:
        return (False, "gtk3agg does not work on Python 3")

    return (True, "version %s.%s.%s" % (Gtk.get_major_version(), Gtk.get_micro_version(), Gtk.get_minor_version()))
def main(root_path, filename):
    # This the main for launched process, this is reached via 'flowblademediaimport' laucher file
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    print "GTK+ version:", gtk_version
    editorstate.gtk_version = gtk_version
    try:
        editorstate.mlt_version = mlt.LIBMLT_VERSION
    except:
        editorstate.mlt_version = "0.0.99" # magic string for "not found"

    # Read the XDG_* variables etc.
    userfolders.init()
    
    # Set paths.
    respaths.set_paths(root_path)

    # Load editor prefs and list of recent projects
    editorpersistance.load()
    
    # Init translations module with translations data
    translations.init_languages()
    translations.load_filters_translations()
    mlttransitions.init_module()

    # Init gtk threads
    Gdk.threads_init()
    Gdk.threads_enter()

    # Themes
    if editorpersistance.prefs.theme != appconsts.LIGHT_THEME:
        Gtk.Settings.get_default().set_property("gtk-application-prefer-dark-theme", True)
        if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME:
            gui.apply_gtk_css()
            
    repo = mlt.Factory().init()
    processutils.prepare_mlt_repo(repo)
    
    # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs 
    locale.setlocale(locale.LC_NUMERIC, 'C')

    # Check for codecs and formats on the system
    mltenv.check_available_features(repo)
    renderconsumer.load_render_profiles()

    # Load filter and compositor descriptions from xml files.
    mltfilters.load_filters_xml(mltenv.services)
    mlttransitions.load_compositors_xml(mltenv.transitions)

    # Create list of available mlt profiles
    mltprofiles.load_profile_list()

    GLib.idle_add(_do_assets_write, filename)
    
    Gtk.main()
    Gdk.threads_leave()
Exemple #55
0
def single_render_main(root_path):
    # called from .../launch/flowbladesinglerender script
    gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version())
    editorstate.gtk_version = gtk_version
    try:
        editorstate.mlt_version = mlt.LIBMLT_VERSION
    except:
        editorstate.mlt_version = "0.0.99" # magic string for "not found"
        
    # Set paths.
    respaths.set_paths(root_path)

    # Load editor prefs and list of recent projects
    editorpersistance.load()
    
    # Init translations module with translations data
    translations.init_languages()
    translations.load_filters_translations()
    mlttransitions.init_module()

    # Init gtk threads
    Gdk.threads_init()
    Gdk.threads_enter()

    # Request dark them if so desired
    if editorpersistance.prefs.dark_theme == True:
        Gtk.Settings.get_default().set_property("gtk-application-prefer-dark-theme", True)

    repo = mlt.Factory().init()

    # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs 
    locale.setlocale(locale.LC_NUMERIC, 'C')

    # Check for codecs and formats on the system
    mltenv.check_available_features(repo)
    renderconsumer.load_render_profiles()

    # Load filter and compositor descriptions from xml files.
    mltfilters.load_filters_xml(mltenv.services)
    mlttransitions.load_compositors_xml(mltenv.transitions)

    # Create list of available mlt profiles
    mltprofiles.load_profile_list()

    global single_render_window
    single_render_window = SingleRenderWindow()

    global single_render_thread
    single_render_thread = SingleRenderThread()
    single_render_thread.start()

    Gtk.main()
    Gdk.threads_leave()
def backend_gtk3cairo_internal_check(x):
    try:
        import cairo
    except ImportError:
        return (False, "Requires cairo to be installed.")

    try:
        from gi.repository import Gtk, Gdk, GObject
    except ImportError:
        return (False, "Requires pygobject to be installed.")

    return (True, "version %s.%s.%s" % (Gtk.get_major_version(), Gtk.get_micro_version(), Gtk.get_minor_version()))
    def generate_menu(self):
        # Settings section
        settings_content = Gio.Menu.new()
        settings_content.append_item(
            Gio.MenuItem.new(_("Settings"), "app.settings"))
        settings_section = Gio.MenuItem.new_section(None, settings_content)
        self.menu.append_item(settings_section)

        # Help section
        help_content = Gio.Menu.new()
        if Gtk.get_major_version() >= 3 and Gtk.get_minor_version() >= 20:
            help_content.append_item(Gio.MenuItem.new(
                _("Shortcuts"), "app.shortcuts"))

        help_content.append_item(Gio.MenuItem.new(_("About"), "app.about"))
        help_content.append_item(Gio.MenuItem.new(_("Quit"), "app.quit"))
        help_section = Gio.MenuItem.new_section(None, help_content)
        self.menu.append_item(help_section)

        self.settings_action = Gio.SimpleAction.new("settings", None)
        self.settings_action.connect("activate", self.on_settings)
        self.settings_action.set_enabled(not self.locked)
        self.add_action(self.settings_action)

        if Gtk.get_major_version() >= 3 and Gtk.get_minor_version() >= 20:
            action = Gio.SimpleAction.new("shortcuts", None)
            action.connect("activate", self.on_shortcuts)
            self.add_action(action)

        action = Gio.SimpleAction.new("about", None)
        action.connect("activate", self.on_about)
        self.add_action(action)

        action = Gio.SimpleAction.new("quit", None)
        action.connect("activate", self.on_quit)
        self.add_action(action)

        if is_gnome():
            self.set_app_menu(self.menu)
            logging.debug("Adding gnome shell menu")
 def run(self, etype, evalue, etraceback):
     text = "".join(traceback.format_exception(etype, evalue, etraceback))
     gtk_version = "%s.%s.%s" % (Gtk.get_major_version(),
                                 Gtk.get_minor_version(),
                                 Gtk.get_micro_version())
     info = "\n\nPlatform: %s\nPython: %s\nGTK+:%s\n\n" % (platform.platform(),
                                                           platform.python_version(),
                                                           gtk_version)
     self._textview.get_buffer().set_text(text)
     clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), 
                                               Gdk.SELECTION_CLIPBOARD)
     clipboard.set_text(text+info, -1)
     Gtk.MessageDialog.run(self)