Beispiel #1
0
 def __init__(self):
     Gtk.init_check(sys.argv)
     # create empty dialog
     self.dia_xml = Gtk.Builder()
     self.dia_xml.set_translation_domain("apturl")
     self.dia_xml.add_from_file('/usr/share/apturl/apturl-gtk.ui')
     self.dia = self.dia_xml.get_object('confirmation_dialog')
     self.dia.realize()
     self.backend = get_backend(self.dia)
     self.backend.connect("action-done", self._on_backend_done)
Beispiel #2
0
 def __init__(self):
     Gtk.init_check(sys.argv)
     # create empty dialog
     self.dia_xml = Gtk.Builder()
     self.dia_xml.set_translation_domain("apturl")
     self.dia_xml.add_from_file(APTURL_UI_FILE)
     self.dia = self.dia_xml.get_object('confirmation_dialog')
     self.dia.start_available = lambda: Gtk.main_quit()
     self.dia.start_error = lambda: Gtk.main_quit()
     self.dia.exit = lambda: Gtk.main_quit()
     self.dia.realize()
     self.require_update = False
Beispiel #3
0
 def __init__(self):
     Gtk.init_check(sys.argv)
     # create empty dialog
     self.dia_xml = Gtk.Builder()
     self.dia_xml.set_translation_domain("apturl")
     self.dia_xml.add_from_file(APTURL_UI_FILE)
     self.dia = self.dia_xml.get_object('confirmation_dialog')
     self.dia.start_available = lambda: Gtk.main_quit()
     self.dia.start_error = lambda: Gtk.main_quit()
     self.dia.exit = lambda: Gtk.main_quit()
     self.dia.realize()
     self.require_update = False
Beispiel #4
0
def main(options, indicator_class):
    exitcode = constants.EXCODE_GENERAL_ERROR

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    gtk_avail = True
    try:
        Gtk.init_check()
    except RuntimeError as error:
        gtk_avail = False
        print(_("Initialization of GTK+ failed: %s") % error)

    if gtk_avail:
        sbdgui = SBackupdIndicatorApp(options)
        exitcode = sbdgui.main(indicator_class)

    return exitcode
Beispiel #5
0
 def __init__(self, shutdown):
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self.shutdown = shutdown
     if not Gtk.init_check()[0]:
         sys.stderr.write("Gtk+ init failed. Make sure DISPLAY variable is set.\n")
         gtkthread.quit.set()
Beispiel #6
0
 def __init__(self, shutdown):
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self.shutdown = shutdown
     if not Gtk.init_check()[0]:
         sys.stderr.write("Gtk+ init failed. Make sure DISPLAY variable is set.\n")
         gtkthread.quit.set()
Beispiel #7
0
def require_Gtk():
    """
    Make sure Gtk is properly initialized.

    :raises RuntimeError: if Gtk can not be properly initialized
    """
    # if we attempt to create any GUI elements with no X server running the
    # program will just crash, so let's make a way to catch this case:
    if not Gtk.init_check(None)[0]:
        raise RuntimeError(_("X server not connected!"))
Beispiel #8
0
def require_Gtk():
    """
    Make sure Gtk is properly initialized.

    :raises RuntimeError: if Gtk can not be properly initialized
    """
    # if we attempt to create any GUI elements with no X server running the
    # program will just crash, so let's make a way to catch this case:
    if not Gtk.init_check(None)[0]:
        raise RuntimeError(_("X server not connected!"))
    def run(self):
        (success, args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        if Gtk.main_level() > 0:
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")
            while Gtk.main_level() > 0:
                time.sleep(2)

            sys.exit(0)

        while not self._currentAction:
            self._currentAction = self._instantiateAction(self._actions[0])
            if not self._currentAction:
                self._actions.pop(0)

            if not self._actions:
                return

        self._currentAction.initialize()
        self._currentAction.refresh()

        self._currentAction.window.set_beta(not self._isFinal)
	#nkwin7 add by yuwan
        #self._currentAction.window.set_property("distribution", self._distributionText().upper())
        self._currentAction.window.set_property("distribution", self._distributionText())
        #nkwin7 done

        # Set some program-wide settings.
        settings = Gtk.Settings.get_default()
        settings.set_property("gtk-font-name", "Cantarell")
        settings.set_property("gtk-icon-theme-name", "gnome")


        # nkwin7 add by yuwan
        # Apply the application stylesheet
	provider = Gtk.CssProvider()
	provider.load_from_path("/usr/share/anaconda/anaconda-gtk.css")
	Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
	         Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
	#nkwin7 done

        self._currentAction.window.show_all()

        # Do this at the last possible minute.
        unbusyCursor()

        Gtk.main()
Beispiel #10
0
    def run(self):
        (success, args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        if Gtk.main_level() > 0:
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")
            while Gtk.main_level() > 0:
                time.sleep(2)

            sys.exit(0)

        while not self._currentAction:
            self._currentAction = self._instantiateAction(self._actions[0])
            if not self._currentAction:
                self._actions.pop(0)

            if not self._actions:
                return

        self._currentAction.initialize()
        self._currentAction.entry_logger()
        self._currentAction.refresh()

        self._currentAction.window.set_beta(not self._isFinal)
        self._currentAction.window.set_property(
            "distribution",
            self._distributionText().upper())

        # Set some program-wide settings.
        settings = Gtk.Settings.get_default()
        settings.set_property("gtk-font-name", "Cantarell")
        settings.set_property("gtk-icon-theme-name", "gnome")

        # Apply the application stylesheet
        provider = Gtk.CssProvider()
        provider.load_from_path("/usr/share/anaconda/anaconda-gtk.css")
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        self._currentAction.window.show_all()

        # Do this at the last possible minute.
        unbusyCursor()

        Gtk.main()
Beispiel #11
0
def main(argv):
    code = 1
    use_gui, _ = Gtk.init_check(argv)
    
    # insert display device parameters as first arguments
    # this controls the format of the pixbuf that ghostscript will deliver
    # see display_sync for details
    
    # fast
    CAIRO_FORMAT_RGB24  = gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_LAST | \
                          gs.DISPLAY_DEPTH_8 | gs.DISPLAY_LITTLEENDIAN
    
    # interesting
    SEPARATION_FORMAT = gs.DISPLAY_COLORS_SEPARATION | gs.DISPLAY_ALPHA_NONE | \
                        gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN
    
    # if there are spot colors they are mixed into the cmyk values
    CMYK_FORMAT = gs.DISPLAY_COLORS_CMYK | gs.DISPLAY_ALPHA_NONE | \
                  gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN
    
    dformat = "-dDisplayFormat=%d" % \
            ( CAIRO_FORMAT_RGB24 | gs.DISPLAY_TOPFIRST )
    
    nargv = [argv[0], dformat] + argv[1:]
    
    #run Ghostscript 
    try:
        instance = gs.new_instance()
        gs.set_stdio(instance, gsdll_stdin, gsdll_stdout, gsdll_stderr)
        if use_gui:
            gs.set_display_callback(instance, c.byref(display))
        code = gs.init_with_args(instance, nargv)
        if code == 0:
            code = gs.run_string(instance, start_string)
        code1 = gs.exit(instance)
        if code == 0 or code == gs.e_Quit:
            code = code1
        if code == gs.e_Quit:
            code = 0 # user executed 'quit'
        gs.delete_instance(instance)
    except gs.GhostscriptError as e:
        code = e.code
        sys.stderr.write(e.message)
    finally:
        exit_status = 0;
        if code in [0, gs.e_Info, gs.e_Quit]:
            pass
        elif code == gs.e_Fatal:
            exit_status = 1
        else:
            exit_status = 255
    return exit_status
Beispiel #12
0
def require_Gtk(min_version=2):
    """
    Make sure Gtk is properly initialized.

    :raises RuntimeError: if Gtk can not be properly initialized
    """
    if _has_Gtk < min_version:
        raise RuntimeError('Module gi.repository.Gtk not available!')
    if _has_Gtk == 2:
        logging.getLogger(__name__).warn(
            _("Missing runtime dependency GTK 3. Falling back to GTK 2 "
              "for password prompt"))
    from gi.repository import Gtk
    # if we attempt to create any GUI elements with no X server running the
    # program will just crash, so let's make a way to catch this case:
    if not Gtk.init_check(None)[0]:
        raise RuntimeError(_("X server not connected!"))
    return Gtk
Beispiel #13
0
def main():
    ''' Indeed: main program. '''
    if len(sys.argv) > 2:
        print("Usage: lpf-gui [package]")
        sys.exit(2)
    elif len(sys.argv) == 2:
        try:
            subprocess.call([here('lpf'), 'update', sys.argv[1]])
        except subprocess.CalledProcessError:
            pass
    if not Gtk.init_check()[0]:
        print(
            "Unable to init xserver, so we can't start graphic interface, you can try using lpf from command line"
        )
        return
    builder = Gtk.Builder()
    builder.add_from_file(here("lpf-gui.ui"))
    Handler(builder)
    Gtk.main()
Beispiel #14
0
def require_Gtk(min_version=2):
    """
    Make sure Gtk is properly initialized.

    :raises RuntimeError: if Gtk can not be properly initialized
    """
    if not (_in_X or _in_Wayland):
        raise RuntimeError('Not in X or Wayland session.')
    if _has_Gtk < min_version:
        raise RuntimeError('Module gi.repository.Gtk not available!')
    if _has_Gtk == 2:
        logging.getLogger(__name__).warn(
            _("Missing runtime dependency GTK 3. Falling back to GTK 2 "
              "for password prompt"))
    from gi.repository import Gtk
    # if we attempt to create any GUI elements with no X server running the
    # program will just crash, so let's make a way to catch this case:
    if not Gtk.init_check(None)[0]:
        raise RuntimeError(_("X server not connected!"))
    return Gtk
Beispiel #15
0
def has_display():
    """
    Tests to see if Python is currently running with gtk 
    """
    # FIXME: currently, Gtk.init_check() requires all strings
    # in argv, and we might have unicode.
    temp, sys.argv = sys.argv, sys.argv[:1]
    try:
        from gi.repository import Gtk
        from gi.repository import Gdk
    except:
        return False

    try:
        test = Gtk.init_check(temp) and \
            Gdk.Display.get_default()
        sys.argv = temp
        return bool(test)
    except:
        sys.argv = temp
        return False
Beispiel #16
0
def has_display():
    """
    Tests to see if Python is currently running with gtk 
    """
    # FIXME: currently, Gtk.init_check() requires all strings
    # in argv, and we might have unicode.
    temp, sys.argv = sys.argv, sys.argv[:1]
    try:
        from gi.repository import Gtk
        from gi.repository import Gdk
    except:
        return False

    try:
        test = Gtk.init_check(temp) and \
            Gdk.Display.get_default()
        sys.argv = temp
        return bool(test)
    except:
        sys.argv = temp
        return False
Beispiel #17
0
    def getByGUI():
        from gi.repository import Gtk
        ok,eh = Gtk.init_check()
        if not ok: return False

        win = Gtk.Window()
        vbox = Gtk.VBox(False,2)
        win.add(vbox)
        def lbl(s):
            vbox.pack_start(Gtk.Label(s),True,True,2)
        lbl(bit)
        lbl(data.name)
        lbl(badtype)
        lbl("What type is that?")
        ent = Gtk.Entry()
        vbox.pack_start(ent,True,True,2)
        btn = Gtk.Button.new_with_label("OK")
        fail = Gtk.Button.new_with_label("Fail")
        fail.connect('clicked',Gtk.main_quit)
        def yay(*a):
            nonlocal mimetype
            test = ent.get_text()
            if '/' in test:
                mimetype = test
                Gtk.main_quit()
            else:
                Gtk.MessageDialog(win,
                                  Gtk.DialogFlags.MODAL |
                                  Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                  Gtk.MessageType.ERROR,
                                  Gtk.ButtonsType.CLOSE,
                                  "The type "+repr(test)+" wasn't good.").show_all()
        ent.connect('activate',yay)
        btn.connect('clicked',yay)
        win.show_all()
        Gtk.main()
        return True
Beispiel #18
0
    def __init__(self):

        #-- Check gtk --#
        if not Gtk.init_check()[0]:
            script_name = os.path.basename(__file__)
            print("[{}]: Failed to initialize gtk".format(script_name))
            sys.exit()

        #-- Create Window --#
        Gtk.Window.__init__(self, title="AlterISO GUI Helper")

        #-- Set window icon --#
        _window_icon = "images/icon/color/AlterV5-Icon-Colored-vector.svg"
        self.set_icon_from_file(os.path.join(root_dir, _window_icon))

        #-- Create Dict --#
        self.dict = {}
        arch_list = Gtk.ListStore(int, str)
        arch_list_num = 0

        for arch in "x86_64", "i686":
            dict = {}

            for value in "kernel", "locale":
                liststore = Gtk.ListStore(int, str)
                liststore_num = 0

                with open("{}/system/{}-{}".format(root_dir, value, arch)) as f:
                    for i in [value.strip().split()[-1] for value in f.readlines() if not "#" in value and value != "\n"]:
                        liststore.append([liststore_num, i])
                        liststore_num += 1

                dict[value] = liststore
            
            liststore = Gtk.ListStore(int, str)
            liststore_num = 0
            command = "{}/channel.sh --nobuiltin --arch {} show".format(script_dir, arch)
            command_obj = shlex.split(command)
            proc = subprocess.Popen(command_obj, stdout=subprocess.PIPE, text=True)
            
            for values in sorted(proc.stdout.read().strip().split()):
                liststore.append([liststore_num, values])
                liststore_num += 1
            
            dict["channel"] = liststore
        
            self.dict[arch] = dict
            arch_list.append([arch_list_num, arch])
            arch_list_num += 1

        #-- Create Widget --#
        # arch
        arch_label = Gtk.Label(label="Architecture")
        self.arch_combo = Gtk.ComboBox.new_with_model_and_entry(arch_list)
        self.arch_combo.set_entry_text_column(1)
        self.arch_combo.set_active(0)
        self.arch_combo.connect("changed", self.on_arch_combo_changed)
        self.default_arch = self.arch_combo.get_model()[self.arch_combo.get_active_iter()][1]
        arch_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        arch_box.set_homogeneous(True)
        arch_box.pack_start(arch_label, True, True, 0)
        arch_box.pack_start(self.arch_combo, True, True, 0)

        # kernel
        kernel_label = Gtk.Label(label="Kernel")
        kernel_list = self.dict[self.default_arch]["kernel"]
        self.kernel_combo = Gtk.ComboBox.new_with_model_and_entry(kernel_list)
        self.kernel_combo.set_entry_text_column(1)
        self.kernel_combo.set_active(0)
        kernel_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        kernel_box.set_homogeneous(True)
        kernel_box.pack_start(kernel_label, True, True, 0)
        kernel_box.pack_start(self.kernel_combo, True, True, 0)
        
        # locale
        locale_label = Gtk.Label(label="Locale")
        locale_list = self.dict[self.default_arch]["locale"]
        self.locale_combo = Gtk.ComboBox.new_with_model_and_entry(locale_list)
        self.locale_combo.set_entry_text_column(1)
        self.locale_combo.set_active(0)
        locale_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        locale_box.set_homogeneous(True)
        locale_box.pack_start(locale_label, True, True, 0)
        locale_box.pack_start(self.locale_combo, True, True, 0)

        # channel
        channel_label = Gtk.Label(label="Channel")
        channel_list = self.dict[self.default_arch]["channel"]
        self.channel_combo = Gtk.ComboBox.new_with_model_and_entry(channel_list)
        self.channel_combo.set_entry_text_column(1)

        for i in range(len(self.channel_combo.get_model())):
            if "xfce" == self.channel_combo.get_model()[i][1]:
                self.channel_combo.set_active(i)
                break
        else:
            self.channel_combo.set_active(0)
        
        channel_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        channel_box.set_homogeneous(True)
        channel_box.pack_start(channel_label, True, True, 0)
        channel_box.pack_start(self.channel_combo, True, True, 0)

        # compression
        comp_label = Gtk.Label(label="Compression")
        comp_list = Gtk.ListStore(int, str)
        comp_list_num = 0

        for i in "gzip", "lz4", "lzma", "lzo", "xz", "zstd":
            comp_list.append([comp_list_num, i])
            comp_list_num += 1

        self.comp_combo = Gtk.ComboBox.new_with_model_and_entry(comp_list)
        self.comp_combo.set_entry_text_column(1)
        self.comp_combo.set_active(5)
        comp_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        comp_box.set_homogeneous(True)
        comp_box.pack_start(comp_label, True, True, 0)
        comp_box.pack_start(self.comp_combo, True, True, 0)

        # boot splash
        boot_splash_label = Gtk.Label(label="Boot Splash")
        self.boot_splash_button_enable = Gtk.RadioButton.new_with_label_from_widget(None, "Enable")
        self.boot_splash_button_disable = Gtk.RadioButton.new_with_mnemonic_from_widget(self.boot_splash_button_enable, "Disable")
        sub_boot_splash_box = Gtk.Box(spacing=5)
        sub_boot_splash_box.set_homogeneous(True)
        sub_boot_splash_box.pack_start(self.boot_splash_button_enable, True, True, 0)
        sub_boot_splash_box.pack_start(self.boot_splash_button_disable, True, True, 0)
        boot_splash_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        boot_splash_box.set_homogeneous(True)
        boot_splash_box.pack_start(boot_splash_label, True, True, 0)
        boot_splash_box.pack_start(sub_boot_splash_box, True, True, 0)

        # username
        username_label = Gtk.Label(label="Username")
        self.username_entry = Gtk.Entry()
        self.username_entry.set_text("alter")
        username_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        username_box.set_homogeneous(True)
        username_box.pack_start(username_label, True, True, 0)
        username_box.pack_start(self.username_entry, True, True, 0)

        # password
        password_label = Gtk.Label(label="Password")
        self.password_entry = Gtk.Entry()
        self.password_entry.set_visibility(False)
        self.password_entry.set_text("alter")
        self.password_button = Gtk.Button.new_with_label("Show Password")
        self.password_button.connect("clicked", self.on_password_clicked)
        password_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        password_box.set_homogeneous(True)
        password_box.pack_start(password_label, True, True, 0)
        password_box.pack_start(self.password_entry, True, True, 0)
        password_box.pack_start(self.password_button, True, True, 0)

        # extra_option
        extra_option_label = Gtk.Label(label="Extra build options: Additional command line options")
        self.extra_option_entry = Gtk.Entry()
        self.extra_option_entry.set_text("")
        extra_option_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        extra_option_box.set_homogeneous(True)
        extra_option_box.pack_start(extra_option_label, True, True, 0)
        extra_option_box.pack_start(self.extra_option_entry, True, True, 0)
        
        # reset
        reset_button = Gtk.Button.new_with_label("Reset")
        reset_button.connect("clicked", self.on_reset_clicked)

        # build
        build_button = Gtk.Button.new_with_label("Build")
        build_button.connect("clicked", self.on_build_clicked)

        # exit
        exit_button = Gtk.Button.new_with_label("Exit")
        exit_button.connect("clicked", self.on_exit_clicked)

        util_box = Gtk.Box(spacing=5)
        util_box.set_homogeneous(True)
        util_box.pack_start(reset_button, True, True, 0)
        util_box.pack_start(build_button, True, True, 0)
        util_box.pack_start(exit_button, True, True, 0)

        
        #-- Create Layout --#
        # layout 1
        layout_1 = Gtk.Box(spacing=5)
        layout_1.pack_start(arch_box, True, True, 0)
        layout_1.pack_start(kernel_box, True, True, 0)
        layout_1.pack_start(locale_box, True, True, 0)
        layout_1.pack_start(channel_box, True, True, 0)

        # layout 2
        layout_2 = Gtk.Grid()
        layout_2.set_column_spacing(5)
        layout_2.set_column_homogeneous(True)
        layout_2.attach(comp_box, 0, 0, 1, 2)
        layout_2.attach(boot_splash_box, 1, 0, 1, 2)
        layout_2.attach(username_box, 2, 0, 1, 2)
        layout_2.attach(password_box, 3, 0, 1, 3)

        # layout 3
        layout_3 = Gtk.Grid()
        layout_3.set_column_spacing(5)
        layout_3.set_column_homogeneous(True)
        layout_3.attach(extra_option_box, 4, 0, 1, 3)


        # sub layout
        sub_layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
        sub_layout.pack_start(layout_1, True, True, 5)
        sub_layout.pack_start(layout_2, True, True, 5)
        sub_layout.pack_start(layout_3, True, True, 5)
        sub_layout.pack_start(util_box,  True, True, 5)
        
        # main layout
        main_layout = Gtk.Box(spacing=5)
        main_layout.pack_start(sub_layout, True, True, 5)
        self.add(main_layout)
Beispiel #19
0
def run(receivers, args, find_receiver, find_device):
    assert receivers
    assert args.device

    device_name = args.device.lower()

    dev = None
    for dev in find_device(receivers, device_name):
        if dev.ping():
            break
        dev = None

    if not dev:
        raise Exception("no online device found matching '%s'" % device_name)

    if not args.setting:  # print all settings, so first set them all up
        if not dev.settings:
            raise Exception('no settings for %s' % dev.name)
        _configuration.attach_to(dev)
        _settings.apply_all_settings(dev)
        print(dev.name, '(%s) [%s:%s]' % (dev.codename, dev.wpid, dev.serial))
        for s in dev.settings:
            print('')
            _print_setting(s)
        return

    setting_name = args.setting.lower()
    setting = _settings_templates.check_feature_setting(dev, setting_name)
    if not setting and dev.descriptor and dev.descriptor.settings:
        for sclass in dev.descriptor.settings:
            if sclass.register and sclass.name == setting_name:
                try:
                    setting = sclass.build(dev)
                except Exception:
                    setting = None
    if setting is None:
        raise Exception("no setting '%s' for %s" % (args.setting, dev.name))

    if args.value_key is None:
        setting.apply()
        _print_setting(setting)
        return

    remote = False
    if Gtk.init_check()[0]:  # can Gtk be initialized?
        APP_ID = 'io.github.pwr_solaar.solaar'
        application = Gtk.Application.new(
            APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
        application.register()
        remote = application.get_is_remote()

    # if the Solaar UI is running don't save configuration here
    result, message, value = set(dev, setting, args, not remote)
    if message is not None:
        print(message)
        if result is None:
            raise Exception("%s: failed to set value '%s' [%r]" %
                            (setting.name, str(value), value))

    # if the Solaar UI is running tell it to also perform the set
    if remote:
        argl = ['config', dev.serial or dev.unitId, setting.name]
        argl.extend([
            a for a in [args.value_key, args.extra_subkey, args.extra2]
            if a is not None
        ])
        application.run(_yaml.safe_dump(argl))
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \
                or (issubclass(ty, OSError) and value.errno == errno.EIO):
            # hardware fault or '[Errno 5] Input/Output error'
            hw_error_msg = _("The installation was stopped due to what "
                             "seems to be a problem with your hardware. "
                             "The exact error message is:\n\n%s.\n\n "
                             "The installer will now terminate.") % str(value)
            self.intf.messageWindow(_("Hardware error occured"), hw_error_msg)
            sys.exit(0)
        else:
            try:
                from gi.repository import Gtk

                # XXX: Gtk stopped raising RuntimeError if it fails to
                # initialize. Horay! But will it stay like this? Let's be
                # cautious and raise the exception on our own to work in both
                # cases
                initialized = Gtk.init_check(None)[0]
                if not initialized:
                    raise RuntimeError()

                if Gtk.main_level() > 0:
                    # main loop is running, don't crash it by running another one
                    # potentially from a different thread
                    log.debug("Gtk running, queuing exception handler to the "
                              "main loop")
                    GLib.idle_add(self.run_handleException, dump_info)
                else:
                    log.debug("Gtk not running, starting Gtk and running "
                              "exception handler in it")
                    super(AnacondaExceptionHandler,
                          self).handleException(dump_info)

            except RuntimeError:
                log.debug("Gtk cannot be initialized")
                # X not running (Gtk cannot be initialized)
                if threadMgr.in_main_thread():
                    log.debug("In the main thread, running exception handler")
                    print "An unknown error has occured, look at the "\
                        "/tmp/anaconda-tb* file(s) for more details"
                    # in the main thread, run exception handler
                    super(AnacondaExceptionHandler,
                          self).handleException(dump_info)
                else:
                    log.debug("In a non-main thread, sending a message with "
                              "exception data")
                    # not in the main thread, just send message with exception
                    # data and let message handler run the exception handler in
                    # the main thread
                    exc_info = dump_info.exc_info
                    hubQ.send_exception(
                        (exc_info.type, exc_info.value, exc_info.stack))
    def __init__(self, datadir=None, logdir=None):
        DistUpgradeView.__init__(self)
        self.logdir = logdir
        if not datadir or datadir == '.':
            localedir=os.path.join(os.getcwd(),"mo")
            gladedir=os.getcwd()
        else:
            localedir="/usr/share/locale/"
            gladedir=os.path.join(datadir, "gtkbuilder")

        # check if we have a display etc
        Gtk.init_check(sys.argv)

        try:
            locale.bindtextdomain("ubuntu-release-upgrader",localedir)
            gettext.textdomain("ubuntu-release-upgrader")
        except Exception as e:
            logging.warning("Error setting locales (%s)" % e)

        SimpleGtkbuilderApp.__init__(self,
                                     gladedir+"/DistUpgrade.ui",
                                     "ubuntu-release-upgrader")

        icons = Gtk.IconTheme.get_default()
        try:
            self.window_main.set_default_icon(icons.load_icon("system-software-update", 32, 0))
        except GObject.GError as e:
            logging.debug("error setting default icon, ignoring (%s)" % e)
            pass

        # terminal stuff
        self.create_terminal()

        self.prev_step = 0 # keep a record of the latest step
        # we don't use this currently
        #self.window_main.set_keep_above(True)
        self.icontheme = Gtk.IconTheme.get_default()
        self._webkit_view = None
        self.window_main.realize()
        self.window_main.get_window().set_functions(Gdk.WMFunction.MOVE)
        self._opCacheProgress = GtkOpProgress(self.progressbar_cache)
        self._acquireProgress = GtkAcquireProgressAdapter(self)
        self._cdromProgress = GtkCdromProgressAdapter(self)
        self._installProgress = GtkInstallProgressAdapter(self)
        # details dialog
        self.details_list = Gtk.TreeStore(GObject.TYPE_STRING)
        column = Gtk.TreeViewColumn("")
        render = Gtk.CellRendererText()
        column.pack_start(render, True)
        column.add_attribute(render, "markup", 0)
        self.treeview_details.append_column(column)
        self.details_list.set_sort_column_id(0, Gtk.SortType.ASCENDING)
        self.treeview_details.set_model(self.details_list)
        # lp: #1072460
        self.dialog_changes.set_resizable(False)
        def _activated(w):
            # the *current* expanded state which will change after the signal
            expanded = self.expander_details.get_expanded()
            self.dialog_changes.set_resizable(not expanded)
        self.expander_details.connect("activate", _activated)
        # FIXME: portme
        # Use italic style in the status labels
        #attrlist=Pango.AttrList()
        #attr = Pango.AttrStyle(Pango.Style.ITALIC, 0, -1)
        #attr = Pango.AttrScale(Pango.SCALE_SMALL, 0, -1)
        #attrlist.insert(attr)
        #self.label_status.set_property("attributes", attrlist)
        # reasonable fault handler
        sys.excepthook = self._handleException
Beispiel #22
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # pygiaio 3.14rev16 switched to fontconfig for PangoCairo. As this results
    # in 100% CPU under win7 revert it. Maybe we need to update the
    # cache in the windows installer for it to work... but for now revert.
    if is_windows():
        os.environ['PANGOCAIRO_BACKEND'] = 'win32'
        os.environ["GTK_CSD"] = "0"

    # disable for consistency and trigger events seem a bit flaky here
    if is_osx():
        os.environ["GTK_OVERLAY_SCROLLING"] = "0"

    # make sure GdkX11 doesn't get used under Windows
    if os.name == "nt":
        sys.modules["gi.repository.GdkX11"] = None

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")
    gi.require_version('Soup', '2.4')

    from gi.repository import Gtk, Soup
    from quodlibet.qltk import ThemeOverrider, gtk_version

    # Work around missing annotation in older libsoup (Ubuntu 14.04 at least)
    message = Soup.Message()
    try:
        message.set_request(None, Soup.MemoryUse.COPY, b"")
    except TypeError:
        orig = Soup.Message.set_request

        def new_set_request(self, content_type, req_use, req_body):
            return orig(self, content_type, req_use, req_body, len(req_body))

        Soup.Message.set_request = new_set_request

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv = Gtk.init_check(sys.argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")
    sys.argv = list(argv)

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings(
        'ignore', '.*Stock items are deprecated.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except AttributeError:
        # older pygobject
        pass
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    css_override = ThemeOverrider()

    # CSS overrides
    if os.name == "nt":
        # somehow borders are missing under Windows & Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            .menu {
                border: 1px solid @borders;
            }
        """)
        css_override.register_provider("", style_provider)

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        css_override.register_provider("", style_provider)

    if gtk_version[:2] >= (3, 20):
        # https://bugzilla.gnome.org/show_bug.cgi?id=761435
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            spinbutton, button {
                min-height: 1.8rem;
            }

            .view button {
                min-height: 2.0rem;
            }

            entry {
                min-height: 2.4rem;
            }
        """)
        css_override.register_provider("Adwaita", style_provider)
        css_override.register_provider("HighContrast", style_provider)

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
Beispiel #23
0
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")
        exception_lines = traceback.format_exception(*dump_info.exc_info)
        log.debug("\n".join(exception_lines))

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \
                or (issubclass(ty, OSError) and value.errno == errno.EIO):
            # hardware fault or '[Errno 5] Input/Output error'
            hw_error_msg = _("The installation was stopped due to what "
                             "seems to be a problem with your hardware. "
                             "The exact error message is:\n\n%s.\n\n "
                             "The installer will now terminate.") % str(value)
            self.intf.messageWindow(_("Hardware error occured"), hw_error_msg)
            sys.exit(0)
        else:
            try:
                from gi.repository import Gtk

                # XXX: Gtk stopped raising RuntimeError if it fails to
                # initialize. Horay! But will it stay like this? Let's be
                # cautious and raise the exception on our own to work in both
                # cases
                initialized = Gtk.init_check(None)[0]
                if not initialized:
                    raise RuntimeError()

                if Gtk.main_level() > 0:
                    # main loop is running, don't crash it by running another one
                    # potentially from a different thread
                    log.debug("Gtk running, queuing exception handler to the "
                             "main loop")
                    GLib.idle_add(self.run_handleException, dump_info)
                else:
                    log.debug("Gtk not running, starting Gtk and running "
                             "exception handler in it")
                    super(AnacondaExceptionHandler, self).handleException(
                                                            dump_info)

            except (RuntimeError, ImportError):
                log.debug("Gtk cannot be initialized")
                # X not running (Gtk cannot be initialized)
                if threadMgr.in_main_thread():
                    log.debug("In the main thread, running exception handler")
                    if (issubclass (ty, CmdlineError)):

                        cmdline_error_msg = _("\nThe installation was stopped due to "
                                              "incomplete spokes detected while running "
                                              "in non-interactive cmdline mode. Since there "
                                              "can not be any questions in cmdline mode, "
                                              "edit your kickstart file and retry "
                                              "installation.\nThe exact error message is: "
                                              "\n\n%s.\n\nThe installer will now terminate.") % str(value)

                        # since there is no UI in cmdline mode and it is completely
                        # non-interactive, we can't show a message window asking the user
                        # to acknowledge the error; instead, print the error out and sleep
                        # for a few seconds before exiting the installer
                        print(cmdline_error_msg)
                        time.sleep(10)
                        sys.exit(0)
                    else:
                        print("\nAn unknown error has occured, look at the "
                               "/tmp/anaconda-tb* file(s) for more details")
                        # in the main thread, run exception handler
                        super(AnacondaExceptionHandler, self).handleException(
                                                                dump_info)
                else:
                    log.debug("In a non-main thread, sending a message with "
                             "exception data")
                    # not in the main thread, just send message with exception
                    # data and let message handler run the exception handler in
                    # the main thread
                    exc_info = dump_info.exc_info
                    hubQ.send_exception((exc_info.type,
                                         exc_info.value,
                                         exc_info.stack))
Beispiel #24
0
import functools
import os
import signal
import tempfile

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, GObject, Gtk

from pystray import _base

from . import notify_dbus


# Make sure Gtk works
if not Gtk.init_check()[0]:
   raise ImportError('Gtk could not be initialised')


def mainloop(f):
    """Marks a function to be executed in the main loop.

    The function will be scheduled to be executed later in the mainloop.

    :param callable f: The function to execute. Its return value is discarded.
    """
    @functools.wraps(f)
    def inner(*args, **kwargs):
        def callback(*args, **kwargs):
            """A callback that executes  ``f`` and then returns ``False``.
            """
Beispiel #25
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # pygiaio 3.14rev16 switched to fontconfig for PangoCairo. As this results
    # in 100% CPU under win7 revert it. Maybe we need to update the
    # cache in the windows installer for it to work... but for now revert.
    if is_windows():
        environ['PANGOCAIRO_BACKEND'] = 'win32'
        environ["GTK_CSD"] = "0"

    # disable for consistency and trigger events seem a bit flaky here
    if config.getboolean("settings", "scrollbar_always_visible"):
        environ["GTK_OVERLAY_SCROLLING"] = "0"

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")
    gi.require_version('Soup', '2.4')

    from gi.repository import Gtk
    from quodlibet.qltk import ThemeOverrider, gtk_version

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv[:] = Gtk.init_check(argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings(
        'ignore', '.*Stock items are deprecated.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    css_override = ThemeOverrider()

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        css_override.register_provider("", style_provider)

    if gtk_version[:2] >= (3, 20):
        # https://bugzilla.gnome.org/show_bug.cgi?id=761435
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            spinbutton, button {
                min-height: 1.8rem;
            }

            .view button {
                min-height: 2.0rem;
            }

            entry {
                min-height: 2.4rem;
            }

            entry.cell {
                min-height: 0;
            }
        """)
        css_override.register_provider("Adwaita", style_provider)
        css_override.register_provider("HighContrast", style_provider)

        # https://github.com/quodlibet/quodlibet/issues/2541
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            treeview.view.separator {
                min-height: 2px;
                color: @borders;
            }
        """)
        css_override.register_provider("Ambiance", style_provider)
        css_override.register_provider("Radiance", style_provider)
        # https://github.com/quodlibet/quodlibet/issues/2677
        css_override.register_provider("Clearlooks-Phenix", style_provider)

    if gtk_version[:2] >= (3, 18):
        # Hack to get some grab handle like thing for panes
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkPaned.vertical, paned.vertical >separator {
                -gtk-icon-source: -gtk-icontheme("view-more-symbolic");
                -gtk-icon-transform: rotate(90deg) scaleX(0.1) scaleY(3);
            }

            GtkPaned.horizontal, paned.horizontal >separator {
                -gtk-icon-source: -gtk-icontheme("view-more-symbolic");
                -gtk-icon-transform: rotate(0deg) scaleX(0.1) scaleY(3);
            }
        """)
        css_override.register_provider("", style_provider)

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
Beispiel #26
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # pygiaio 3.14rev16 switched to fontconfig for PangoCairo. As this results
    # in 100% CPU under win7 revert it. Maybe we need to update the
    # cache in the windows installer for it to work... but for now revert.
    if is_windows():
        os.environ['PANGOCAIRO_BACKEND'] = 'win32'

    # disable for consistency and trigger events seem a bit flaky here
    if is_osx():
        os.environ["GTK_OVERLAY_SCROLLING"] = "0"

    # make sure GdkX11 doesn't get used under Windows
    if os.name == "nt":
        sys.modules["gi.repository.GdkX11"] = None

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")
    gi.require_version('Soup', '2.4')

    from gi.repository import Gtk, Gdk

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv = Gtk.init_check(sys.argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")
    sys.argv = list(argv)

    # add Gtk.TreePath.__getitem__/__len__ for PyGObject 3.2
    try:
        Gtk.TreePath()[0]
    except TypeError:
        Gtk.TreePath.__getitem__ = lambda self, index: list(self)[index]
        Gtk.TreePath.__len__ = lambda self: self.get_depth()

    # GTK+ 3.4+ constants
    if not hasattr(Gdk, "BUTTON_PRIMARY"):
        Gdk.BUTTON_PRIMARY = 1
        Gdk.BUTTON_MIDDLE = 2
        Gdk.BUTTON_SECONDARY = 3

    if not hasattr(Gdk, "EVENT_PROPAGATE"):
        Gdk.EVENT_PROPAGATE = 0
        Gdk.EVENT_STOP = 1

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings(
        'ignore', '.*Stock items are deprecated.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except AttributeError:
        # older pygobject
        pass
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    # CSS overrides
    if os.name == "nt":
        # somehow borders are missing under Windows & Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data("""
            .menu {
                border: 1px solid @borders;
            }
        """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data("""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \
                or (issubclass(ty, OSError) and value.errno == errno.EIO):
            # hardware fault or '[Errno 5] Input/Output error'
            hw_error_msg = _("The installation was stopped due to what "
                             "seems to be a problem with your hardware. "
                             "The exact error message is:\n\n%s.\n\n "
                             "The installer will now terminate.") % str(value)
            self.intf.messageWindow(_("Hardware error occured"), hw_error_msg)
            sys.exit(0)
        else:
            try:
                from gi.repository import Gtk

                # XXX: Gtk stopped raising RuntimeError if it fails to
                # initialize. Horay! But will it stay like this? Let's be
                # cautious and raise the exception on our own to work in both
                # cases
                initialized = Gtk.init_check(None)[0]
                if not initialized:
                    raise RuntimeError()

                if Gtk.main_level() > 0:
                    # main loop is running, don't crash it by running another one
                    # potentially from a different thread
                    log.debug("Gtk running, queuing exception handler to the "
                             "main loop")
                    GLib.idle_add(self.run_handleException, dump_info)
                else:
                    log.debug("Gtk not running, starting Gtk and running "
                             "exception handler in it")
                    super(AnacondaExceptionHandler, self).handleException(
                                                            dump_info)

            except RuntimeError:
                log.debug("Gtk cannot be initialized")
                # X not running (Gtk cannot be initialized)
                if threadMgr.in_main_thread():
                    log.debug("In the main thread, running exception handler")
                    print "An unknown error has occured, look at the "\
                        "/tmp/anaconda-tb* file(s) for more details"
                    # in the main thread, run exception handler
                    super(AnacondaExceptionHandler, self).handleException(
                                                            dump_info)
                else:
                    log.debug("In a non-main thread, sending a message with "
                             "exception data")
                    # not in the main thread, just send message with exception
                    # data and let message handler run the exception handler in
                    # the main thread
                    exc_info = dump_info.exc_info
                    hubQ.send_exception((exc_info.type,
                                         exc_info.value,
                                         exc_info.stack))
Beispiel #28
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    if config.getboolean("settings", "pangocairo_force_fontconfig") and \
            "PANGOCAIRO_BACKEND" not in environ:
        environ["PANGOCAIRO_BACKEND"] = "fontconfig"

    # disable for consistency and trigger events seem a bit flaky here
    if config.getboolean("settings", "scrollbar_always_visible"):
        environ["GTK_OVERLAY_SCROLLING"] = "0"

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")
    gi.require_version('Soup', '2.4')
    gi.require_version('PangoCairo', "1.0")

    from gi.repository import Gtk
    from quodlibet.qltk import ThemeOverrider, gtk_version

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv[:] = Gtk.init_check(argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings('ignore', '.*Stock items are deprecated.*',
                            Warning)
    warnings.filterwarnings('ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', r'.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    css_override = ThemeOverrider()

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        css_override.register_provider("", style_provider)

    if gtk_version[:2] >= (3, 20):
        # https://bugzilla.gnome.org/show_bug.cgi?id=761435
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            spinbutton, button {
                min-height: 22px;
            }

            .view button {
                min-height: 24px;
            }

            entry {
                min-height: 28px;
            }

            entry.cell {
                min-height: 0;
            }
        """)
        css_override.register_provider("Adwaita", style_provider)
        css_override.register_provider("HighContrast", style_provider)

        # https://github.com/quodlibet/quodlibet/issues/2541
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            treeview.view.separator {
                min-height: 2px;
                color: @borders;
            }
        """)
        css_override.register_provider("Ambiance", style_provider)
        css_override.register_provider("Radiance", style_provider)
        # https://github.com/quodlibet/quodlibet/issues/2677
        css_override.register_provider("Clearlooks-Phenix", style_provider)
        # https://github.com/quodlibet/quodlibet/issues/2997
        css_override.register_provider("Breeze", style_provider)

    if gtk_version[:2] >= (3, 18):
        # Hack to get some grab handle like thing for panes
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkPaned.vertical, paned.vertical >separator {
                -gtk-icon-source: -gtk-icontheme("view-more-symbolic");
                -gtk-icon-transform: rotate(90deg) scaleX(0.1) scaleY(3);
            }

            GtkPaned.horizontal, paned.horizontal >separator {
                -gtk-icon-source: -gtk-icontheme("view-more-symbolic");
                -gtk-icon-transform: rotate(0deg) scaleX(0.1) scaleY(3);
            }
        """)
        css_override.register_provider("", style_provider)

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
Beispiel #29
0
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")
        exception_lines = traceback.format_exception(*dump_info.exc_info)
        log.critical("\n".join(exception_lines))

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        try:
            gi.require_version("Gtk", "3.0")

            from gi.repository import Gtk

            # XXX: Gtk stopped raising RuntimeError if it fails to
            # initialize. Horay! But will it stay like this? Let's be
            # cautious and raise the exception on our own to work in both
            # cases
            initialized = Gtk.init_check(None)[0]
            if not initialized:
                raise RuntimeError()

            # Attempt to grab the GUI initializing lock, do not block
            if not self._gui_lock.acquire(False):
                # the graphical interface is running, don't crash it by
                # running another one potentially from a different thread
                log.debug(
                    "Gtk running, queuing exception handler to the main loop")
                run_in_loop(self._main_loop_handleException, dump_info)
            else:
                log.debug(
                    "Gtk not running, starting Gtk and running exception handler in it"
                )
                self._main_loop_handleException(dump_info)

        except (RuntimeError, ImportError, ValueError):
            log.debug("Gtk cannot be initialized")
            # X not running (Gtk cannot be initialized)
            if threadMgr.in_main_thread():
                log.debug("In the main thread, running exception handler")
                if issubclass(ty,
                              NonInteractiveError) or not self._interactive:
                    if issubclass(ty, NonInteractiveError):
                        cmdline_error_msg = _(
                            "\nThe installation was stopped due to an "
                            "error which occurred while running in "
                            "non-interactive cmdline mode. Since there "
                            "cannot be any questions in cmdline mode, edit "
                            "your kickstart file and retry installation. "
                            "\nThe exact error message is: \n\n%s. \n\nThe "
                            "installer will now terminate.") % str(value)
                    else:
                        cmdline_error_msg = _(
                            "\nRunning in cmdline mode, no interactive "
                            "debugging allowed.\nThe exact error message is: "
                            "\n\n%s.\n\nThe installer will now terminate."
                        ) % str(value)

                    # since there is no UI in cmdline mode and it is completely
                    # non-interactive, we can't show a message window asking the user
                    # to acknowledge the error; instead, print the error out and sleep
                    # for a few seconds before exiting the installer
                    print(cmdline_error_msg)
                    time.sleep(180)
                    sys.exit(1)
                else:
                    print("\nAn unknown error has occured, look at the "
                          "/tmp/anaconda-tb* file(s) for more details")
                    # in the main thread, run exception handler
                    self._main_loop_handleException(dump_info)
            else:
                log.debug(
                    "In a non-main thread, sending a message with exception data"
                )
                # not in the main thread, just send message with exception
                # data and let message handler run the exception handler in
                # the main thread
                exc_info = dump_info.exc_info
                # new Simpleline package is now used in TUI. Look if Simpleline is
                # initialized or if this is some fallback from GTK or other stuff.
                if App.is_initialized():
                    # if Simpleline is initialized enqueue exception there
                    loop = App.get_event_loop()
                    loop.enqueue_signal(
                        ExceptionSignal(App.get_scheduler(),
                                        exception_info=exc_info))
                else:
                    hubQ.send_exception(
                        (exc_info.type, exc_info.value, exc_info.stack))
Beispiel #30
0
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")
        exception_lines = traceback.format_exception(*dump_info.exc_info)
        log.critical("\n".join(exception_lines))

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \
                or (issubclass(ty, OSError) and value.errno == errno.EIO):
            # hardware fault or '[Errno 5] Input/Output error'
            hw_error_msg = _("The installation was stopped due to what "
                             "seems to be a problem with your hardware. "
                             "The exact error message is:\n\n%s.\n\n "
                             "The installer will now terminate.") % str(value)
            self.intf.messageWindow(_("Hardware error occurred"), hw_error_msg)
            sys.exit(0)
        else:
            try:
                from gi.repository import Gtk

                # XXX: Gtk stopped raising RuntimeError if it fails to
                # initialize. Horay! But will it stay like this? Let's be
                # cautious and raise the exception on our own to work in both
                # cases
                initialized = Gtk.init_check(None)[0]
                if not initialized:
                    raise RuntimeError()

                # Attempt to grab the GUI initializing lock, do not block
                if not self._gui_lock.acquire(False):
                    # the graphical interface is running, don't crash it by
                    # running another one potentially from a different thread
                    log.debug("Gtk running, queuing exception handler to the "
                              "main loop")
                    GLib.idle_add(self.run_handleException, dump_info)
                else:
                    log.debug("Gtk not running, starting Gtk and running "
                              "exception handler in it")
                    super(AnacondaExceptionHandler,
                          self).handleException(dump_info)

            except (RuntimeError, ImportError):
                log.debug("Gtk cannot be initialized")
                # X not running (Gtk cannot be initialized)
                if threadMgr.in_main_thread():
                    log.debug("In the main thread, running exception handler")
                    if issubclass(ty, CmdlineError) or not self._interactive:
                        if issubclass(ty, CmdlineError):
                            cmdline_error_msg = _(
                                "\nThe installation was stopped due to "
                                "incomplete spokes detected while running "
                                "in non-interactive cmdline mode. Since there "
                                "cannot be any questions in cmdline mode, "
                                "edit your kickstart file and retry "
                                "installation.\nThe exact error message is: "
                                "\n\n%s.\n\nThe installer will now terminate."
                            ) % str(value)
                        else:
                            cmdline_error_msg = _(
                                "\nRunning in cmdline mode, no interactive debugging "
                                "allowed.\nThe exact error message is: "
                                "\n\n%s.\n\nThe installer will now terminate."
                            ) % str(value)

                        # since there is no UI in cmdline mode and it is completely
                        # non-interactive, we can't show a message window asking the user
                        # to acknowledge the error; instead, print the error out and sleep
                        # for a few seconds before exiting the installer
                        print(cmdline_error_msg)
                        time.sleep(10)
                        sys.exit(1)
                    else:
                        print("\nAn unknown error has occured, look at the "
                              "/tmp/anaconda-tb* file(s) for more details")
                        # in the main thread, run exception handler
                        super(AnacondaExceptionHandler,
                              self).handleException(dump_info)
                else:
                    log.debug("In a non-main thread, sending a message with "
                              "exception data")
                    # not in the main thread, just send message with exception
                    # data and let message handler run the exception handler in
                    # the main thread
                    exc_info = dump_info.exc_info
                    hubQ.send_exception(
                        (exc_info.type, exc_info.value, exc_info.stack))
Beispiel #31
0
    def run(self):
        (success, _args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        # Check if the GUI lock has already been taken
        if self._gui_lock and not self._gui_lock.acquire(False):
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")

            anaconda_threading.threadMgr.wait_for_error_threads()
            sys.exit(1)

        try:
            # Apply a widget-scale to hidpi monitors
            self._widgetScale()

            while not self._currentAction:
                self._currentAction = self._instantiateAction(self._actions[0])
                if not self._currentAction:
                    self._actions.pop(0)

                if not self._actions:
                    return

            self._currentAction.initialize()
            self._currentAction.refresh()

            self._currentAction.window.set_beta(not self._isFinal)
            self._currentAction.window.set_property("distribution", self._distributionText().upper())

            # Set some program-wide settings.
            settings = Gtk.Settings.get_default()
            settings.set_property("gtk-font-name", "Cantarell")

            # Get the path to the application data
            data_path = os.environ.get("ANACONDA_DATA", "/usr/share/anaconda")

            # Apply the application stylesheet
            css_path = os.path.join(data_path, "anaconda-gtk.css")
            provider = Gtk.CssProvider()
            provider.load_from_path(css_path)
            Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

            # Add the application icons to the theme
            icon_path = os.path.join(data_path, "pixmaps")
            icon_theme = Gtk.IconTheme.get_default()
            icon_theme.append_search_path(icon_path)

            # Apply the custom stylesheet
            if conf.ui.custom_stylesheet:
                try:
                    provider = Gtk.CssProvider()
                    provider.load_from_path(conf.ui.custom_stylesheet)
                    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                            STYLE_PROVIDER_PRIORITY_CUSTOM)
                except GError as e:
                    log.error("Custom stylesheet %s failed to load:\n%s",
                              conf.ui.custom_stylesheet, e)

            # Look for updates to the stylesheet and apply them at a higher priority
            for updates_dir in ("updates", "product"):
                updates_css = "/run/install/%s/anaconda-gtk.css" % updates_dir
                if os.path.exists(updates_css):
                    provider = Gtk.CssProvider()
                    provider.load_from_path(updates_css)
                    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                            STYLE_PROVIDER_PRIORITY_UPDATES)

            self.mainWindow.setCurrentAction(self._currentAction)
            # the window corresponding to the ection should now be visible to the user
            self._currentAction.entered.emit(self._currentAction)

            # Do this at the last possible minute.
            unbusyCursor()
        # If anything went wrong before we start the Gtk main loop, release
        # the gui lock and re-raise the exception so that meh can take over
        except Exception:
            self._gui_lock.release()
            raise

        Gtk.main()
Beispiel #32
0
    def run(self):
        (success, args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        # Check if the GUI lock has already been taken
        if self._gui_lock and not self._gui_lock.acquire(False):
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")

            threads.threadMgr.wait_for_error_threads()
            sys.exit(1)

        try:
            # Apply a widget-scale to hidpi monitors
            self._widgetScale()

            while not self._currentAction:
                self._currentAction = self._instantiateAction(self._actions[0])
                if not self._currentAction:
                    self._actions.pop(0)

                if not self._actions:
                    return

            self._currentAction.initialize()
            self._currentAction.entry_logger()
            self._currentAction.refresh()

            self._currentAction.window.set_beta(not self._isFinal)
            self._currentAction.window.set_property("distribution", self._distributionText().upper())

            # Set some program-wide settings.
            settings = Gtk.Settings.get_default()
            settings.set_property("gtk-font-name", "Cantarell")
            settings.set_property("gtk-icon-theme-name", "gnome")

            # Apply the application stylesheet
            provider = Gtk.CssProvider()
            provider.load_from_path("/usr/share/anaconda/anaconda-gtk.css")
            Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

            # Apply the installclass stylesheet
            if self.instclass.stylesheet:
                provider = Gtk.CssProvider()
                provider.load_from_path(self.instclass.stylesheet)
                Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                        STYLE_PROVIDER_PRIORITY_INSTALLCLASS)

            # Look for updates to the stylesheet and apply them at a higher priority
            for updates_dir in ("updates", "product"):
                updates_css = "/run/install/%s/anaconda-gtk.css" % updates_dir
                if os.path.exists(updates_css):
                    provider = Gtk.CssProvider()
                    provider.load_from_path(updates_css)
                    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                            STYLE_PROVIDER_PRIORITY_UPDATES)

            self.mainWindow.setCurrentAction(self._currentAction)

            # Do this at the last possible minute.
            unbusyCursor()
        # If anything went wrong before we start the Gtk main loop, release
        # the gui lock and re-raise the exception so that meh can take over
        except Exception:
            self._gui_lock.release()
            raise

        Gtk.main()
Beispiel #33
0
def init_test_environ():

    set_dll_search_path()

    def dbus_launch_session():
        if os.name == "nt" or sys.platform == "darwin":
            return (-1, "")

        try:
            out = subprocess.check_output([
                "dbus-daemon", "--session", "--fork", "--print-address=1",
                "--print-pid=1"
            ])
        except (subprocess.CalledProcessError, OSError):
            return (-1, "")
        else:
            out = out.decode("utf-8")
            addr, pid = out.splitlines()
            return int(pid), addr

    pid, addr = dbus_launch_session()
    if pid >= 0:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = addr
        atexit.register(os.kill, pid, signal.SIGKILL)
    else:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = "."

    tests_builddir = os.path.abspath(
        os.environ.get('TESTS_BUILDDIR', os.path.dirname(__file__)))
    builddir = os.path.dirname(tests_builddir)
    tests_srcdir = os.path.abspath(os.path.dirname(__file__))
    srcdir = os.path.dirname(tests_srcdir)

    sys.path.insert(0, os.path.join(builddir, 'gi'))
    sys.path.insert(0, tests_srcdir)
    sys.path.insert(0, srcdir)
    sys.path.insert(0, tests_builddir)
    sys.path.insert(0, builddir)

    # force untranslated messages, as we check for them in some tests
    os.environ['LC_MESSAGES'] = 'C'
    os.environ['G_DEBUG'] = 'fatal-warnings fatal-criticals'
    if sys.platform == "darwin" or os.name == "nt":
        # gtk 3.22 has warnings and ciriticals on OS X, ignore for now.
        # On Windows glib will create an error dialog which will block tests
        # so it's never a good idea there to make things fatal.
        os.environ['G_DEBUG'] = ''

    # make Gio able to find our gschemas.compiled in tests/. This needs to be set
    # before importing Gio. Support a separate build tree, so look in build dir
    # first.
    os.environ['GSETTINGS_BACKEND'] = 'memory'
    os.environ['GSETTINGS_SCHEMA_DIR'] = tests_builddir
    os.environ['G_FILENAME_ENCODING'] = 'UTF-8'

    # Avoid accessibility dbus warnings
    os.environ['NO_AT_BRIDGE'] = '1'

    # A workaround for https://gitlab.gnome.org/GNOME/glib/-/issues/2251
    # The gtk4 a11y stack calls get_dbus_object_path() on the default app
    os.environ['GTK_A11Y'] = 'none'

    # Force the default theme so broken themes don't affect the tests
    os.environ['GTK_THEME'] = 'Adwaita'

    import gi
    gi.require_version("GIRepository", "2.0")
    from gi.repository import GIRepository
    repo = GIRepository.Repository.get_default()
    repo.prepend_library_path(os.path.join(tests_builddir))
    repo.prepend_search_path(tests_builddir)

    def try_require_version(namespace, version):
        try:
            gi.require_version(namespace, version)
        except ValueError:
            # prevent tests from running with the wrong version
            sys.modules["gi.repository." + namespace] = None

    # Optional
    try_require_version("Gtk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("Gdk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("GdkPixbuf", "2.0")
    try_require_version("Pango", "1.0")
    try_require_version("PangoCairo", "1.0")
    try_require_version("Atk", "1.0")

    # Required
    gi.require_versions({
        "GIMarshallingTests": "1.0",
        "Regress": "1.0",
        "GLib": "2.0",
        "Gio": "2.0",
        "GObject": "2.0",
    })

    # It's disabled for stable releases by default, this makes sure it's
    # always on for the tests.
    warnings.simplefilter('default', gi.PyGIDeprecationWarning)

    # Otherwise we crash on the first gtk use when e.g. DISPLAY isn't set
    try:
        from gi.repository import Gtk
    except ImportError:
        pass
    else:
        if Gtk._version == "4.0":
            res = Gtk.init_check()
        else:
            res = Gtk.init_check([])[0]
        if not res:
            raise RuntimeError("Gtk available, but Gtk.init_check() failed")
Beispiel #34
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # disable for consistency and trigger events seem a bit flaky here
    if is_osx():
        os.environ["GTK_OVERLAY_SCROLLING"] = "0"

    # make sure GdkX11 doesn't get used under Windows
    if os.name == "nt":
        sys.modules["gi.repository.GdkX11"] = None

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11

        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("GLib", "2.0")
    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("GObject", "2.0")
    gi.require_version("Pango", "1.0")
    gi.require_version("GdkPixbuf", "2.0")
    gi.require_version("Gio", "2.0")

    from gi.repository import Gtk, GObject, Gdk, GdkPixbuf

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv = Gtk.init_check(sys.argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")
    sys.argv = list(argv)

    # add Gtk.TreePath.__getitem__/__len__ for PyGObject 3.2
    try:
        Gtk.TreePath()[0]
    except TypeError:
        Gtk.TreePath.__getitem__ = lambda self, index: list(self)[index]
        Gtk.TreePath.__len__ = lambda self: self.get_depth()

    # GTK+ 3.4+ constants
    if not hasattr(Gdk, "BUTTON_PRIMARY"):
        Gdk.BUTTON_PRIMARY = 1
        Gdk.BUTTON_MIDDLE = 2
        Gdk.BUTTON_SECONDARY = 3

    if not hasattr(Gdk, "EVENT_PROPAGATE"):
        Gdk.EVENT_PROPAGATE = 0
        Gdk.EVENT_STOP = 1

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # On windows the default variants only do ANSI paths, so replace them.
    # In some typelibs they are replaced by default, in some don't..
    if os.name == "nt":
        for name in ["new_from_file_at_scale", "new_from_file_at_size", "new_from_file"]:
            cls = GdkPixbuf.Pixbuf
            setattr(cls, name, getattr(cls, name + "_utf8", name))

    # https://bugzilla.gnome.org/show_bug.cgi?id=670372
    if not hasattr(GdkPixbuf.Pixbuf, "savev"):
        GdkPixbuf.Pixbuf.savev = GdkPixbuf.Pixbuf.save

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings("ignore", ".*g_value_get_int.*", Warning)

    # some day... but not now
    warnings.filterwarnings("ignore", ".*Stock items are deprecated.*", Warning)
    warnings.filterwarnings("ignore", ".*:use-stock.*", Warning)
    warnings.filterwarnings("ignore", ".*The property GtkAlignment:[^\s]+ is deprecated.*", Warning)

    # Newer glib is noisy regarding deprecated signals/properties
    # even with stable releases.
    if is_release():
        warnings.filterwarnings("ignore", ".* It will be removed in a future version.", Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except AttributeError:
        # older pygobject
        pass
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    # CSS overrides
    if os.name == "nt":
        # somehow borders are missing under Windows & Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(
            """
            .menu {
                border: 1px solid @borders;
            }
        """
        )
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(
            """
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """
        )
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings("ignore", ".*g_value_get_int.*", Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["glib"] = None
    sys.modules["gobject"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version

    if pygobject_version < (3, 9):
        GObject.threads_init()
Beispiel #35
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # disable for consistency and trigger events seem a bit flaky here
    if is_osx():
        os.environ["GTK_OVERLAY_SCROLLING"] = "0"

    # make sure GdkX11 doesn't get used under Windows
    if os.name == "nt":
        sys.modules["gi.repository.GdkX11"] = None

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")

    from gi.repository import Gtk, Gdk

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv = Gtk.init_check(sys.argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")
    sys.argv = list(argv)

    # add Gtk.TreePath.__getitem__/__len__ for PyGObject 3.2
    try:
        Gtk.TreePath()[0]
    except TypeError:
        Gtk.TreePath.__getitem__ = lambda self, index: list(self)[index]
        Gtk.TreePath.__len__ = lambda self: self.get_depth()

    # GTK+ 3.4+ constants
    if not hasattr(Gdk, "BUTTON_PRIMARY"):
        Gdk.BUTTON_PRIMARY = 1
        Gdk.BUTTON_MIDDLE = 2
        Gdk.BUTTON_SECONDARY = 3

    if not hasattr(Gdk, "EVENT_PROPAGATE"):
        Gdk.EVENT_PROPAGATE = 0
        Gdk.EVENT_STOP = 1

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings('ignore', '.*Stock items are deprecated.*',
                            Warning)
    warnings.filterwarnings('ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except AttributeError:
        # older pygobject
        pass
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    # CSS overrides
    if os.name == "nt":
        # somehow borders are missing under Windows & Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data("""
            .menu {
                border: 1px solid @borders;
            }
        """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data("""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
Beispiel #36
0
    def run(self):
        (success, args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        # Check if the GUI lock has already been taken
        if self._gui_lock and not self._gui_lock.acquire(False):
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")

            # Loop forever, meh will call sys.exit() when it's done
            while True:
                time.sleep(10000)

        # Apply a widget-scale to hidpi monitors
        self._widgetScale()

        while not self._currentAction:
            self._currentAction = self._instantiateAction(self._actions[0])
            if not self._currentAction:
                self._actions.pop(0)

            if not self._actions:
                return

        self._currentAction.initialize()
        self._currentAction.entry_logger()
        self._currentAction.refresh()

        self._currentAction.window.set_beta(not self._isFinal)
        self._currentAction.window.set_property("distribution", self._distributionText().upper())

        # Set some program-wide settings.
        settings = Gtk.Settings.get_default()
        settings.set_property("gtk-font-name", "Cantarell")
        settings.set_property("gtk-icon-theme-name", "gnome")

        # Apply the application stylesheet
        provider = Gtk.CssProvider()
        provider.load_from_path("/usr/share/anaconda/anaconda-gtk.css")
        Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # Look for updates to the stylesheet and apply them at a higher priority
        for updates_dir in ("updates", "product"):
            updates_css = "/run/install/%s/anaconda-gtk.css" % updates_dir
            if os.path.exists(updates_css):
                provider = Gtk.CssProvider()
                provider.load_from_path(updates_css)
                Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider,
                        STYLE_PROVIDER_PRIORITY_UPDATES)

        # try to make sure a logo image is present
        self._assureLogoImage()

        self.mainWindow.setCurrentAction(self._currentAction)

        # Do this at the last possible minute.
        unbusyCursor()

        Gtk.main()
Beispiel #37
0
from pyanaconda.i18n import _

__all__ = ["ERROR_RAISE", "ERROR_CONTINUE", "ERROR_RETRY",
           "InvalidImageSizeError", "MissingImageError", "MediaUnmountError",
           "MediaMountError", "ScriptError", "CmdlineError",
           "errorHandler"]

# Only run the pango markup escape if the GUI is available
try:
    from gi.repository import Gtk

    # XXX: Gtk stopped raising RuntimeError if it fails to
    # initialize. Horay! But will it stay like this? Let's be
    # cautious and raise the exception on our own to work in both
    # cases
    initialized = Gtk.init_check(None)[0]
    if not initialized:
        raise RuntimeError()

    # If we don't do the check above this import will fail within _isys
    from pyanaconda.ui.gui.utils import escape_markup
except (RuntimeError, ImportError):
    escape_markup = lambda x: x

class InvalidImageSizeError(Exception):
    def __init__(self, message, filename):
        Exception.__init__(self, message)
        self.filename = filename

class MissingImageError(Exception):
    pass
Beispiel #38
0
def init_test_environ():
    # this was renamed in Python 3, provide backwards compatible name
    if sys.version_info[:2] == (2, 7):
        unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp

    if sys.version_info[0] == 3:
        unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex
        unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex

    def dbus_launch_session():
        if os.name == "nt" or sys.platform == "darwin":
            return (-1, "")

        try:
            out = subprocess.check_output([
                "dbus-daemon", "--session", "--fork", "--print-address=1",
                "--print-pid=1"])
        except (subprocess.CalledProcessError, OSError):
            return (-1, "")
        else:
            if sys.version_info[0] == 3:
                out = out.decode("utf-8")
            addr, pid = out.splitlines()
            return int(pid), addr

    pid, addr = dbus_launch_session()
    if pid >= 0:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = addr
        atexit.register(os.kill, pid, signal.SIGKILL)
    else:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = "."

    tests_builddir = os.path.abspath(os.environ.get('TESTS_BUILDDIR', os.path.dirname(__file__)))
    builddir = os.path.dirname(tests_builddir)
    tests_srcdir = os.path.abspath(os.path.dirname(__file__))
    srcdir = os.path.dirname(tests_srcdir)

    sys.path.insert(0, os.path.join(builddir, 'gi'))
    sys.path.insert(0, tests_srcdir)
    sys.path.insert(0, srcdir)
    sys.path.insert(0, tests_builddir)
    sys.path.insert(0, builddir)

    # force untranslated messages, as we check for them in some tests
    os.environ['LC_MESSAGES'] = 'C'
    os.environ['G_DEBUG'] = 'fatal-warnings fatal-criticals'
    if sys.platform == "darwin":
        # gtk 3.22 has warnings and ciriticals on OS X, ignore for now
        os.environ['G_DEBUG'] = ''

    # make Gio able to find our gschemas.compiled in tests/. This needs to be set
    # before importing Gio. Support a separate build tree, so look in build dir
    # first.
    os.environ['GSETTINGS_BACKEND'] = 'memory'
    os.environ['GSETTINGS_SCHEMA_DIR'] = tests_builddir
    os.environ['G_FILENAME_ENCODING'] = 'UTF-8'

    # Force the default theme so broken themes don't affect the tests
    os.environ['GTK_THEME'] = 'Adwaita'

    import gi
    gi.require_version("GIRepository", "2.0")
    from gi.repository import GIRepository
    repo = GIRepository.Repository.get_default()
    repo.prepend_library_path(os.path.join(tests_builddir))
    repo.prepend_library_path(os.path.join(tests_builddir, ".libs"))
    repo.prepend_search_path(tests_builddir)

    def try_require_version(namespace, version):
        try:
            gi.require_version(namespace, version)
        except ValueError:
            # prevent tests from running with the wrong version
            sys.modules["gi.repository." + namespace] = None

    # Optional
    try_require_version("Gtk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("Gdk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("GdkPixbuf", "2.0")
    try_require_version("Pango", "1.0")
    try_require_version("PangoCairo", "1.0")
    try_require_version("Atk", "1.0")

    # Required
    gi.require_versions({
        "GIMarshallingTests": "1.0",
        "Regress": "1.0",
        "GLib": "2.0",
        "Gio": "2.0",
        "GObject": "2.0",
    })

    # It's disabled for stable releases by default, this makes sure it's
    # always on for the tests.
    warnings.simplefilter('default', gi.PyGIDeprecationWarning)

    # Otherwise we crash on the first gtk use when e.g. DISPLAY isn't set
    try:
        from gi.repository import Gtk
    except ImportError:
        pass
    else:
        if Gtk._version == "4.0":
            res = Gtk.init_check()
        else:
            res = Gtk.init_check([])[0]
        if not res:
            raise RuntimeError("Gtk available, but Gtk.init_check() failed")
Beispiel #39
0
                print('filepath:', filepath)
                self.button.set_label("Stop")
                self.player.set_property("uri", "file://" + filepath)
                self.player.set_state(Gst.State.PLAYING)
            else:
                self.player.set_state(Gst.State.NULL)
                self.button.set_label("Start")

    def on_message(self, bus, message):
        '''
        '''
        # t = message.type
        # if t == Gst.MessageType.EOS:
        #     self.player.set_state(Gst.State.NULL)
        #     self.button.set_label("Start")
        # elif t == Gst.MessageType.ERROR:
        #     self.player.set_state(Gst.State.NULL)
        #     err, debug = message.parse_error()
        #     print("Error: %s" % err, debug)
        #     self.button.set_label("Start")


Gst.init(None)
if Gtk.init_check():
    GTK_Main()
    GObject.threads_init()
    loop = GObject.MainLoop()
    loop.run()
    # Gtk.main()
else:
    print('invalid Gtk.init_check')
Beispiel #40
0
    def run(self):
        (success, _args) = Gtk.init_check(None)
        if not success:
            raise RuntimeError("Failed to initialize Gtk")

        # Check if the GUI lock has already been taken
        if self._gui_lock and not self._gui_lock.acquire(False):
            # Gtk main loop running. That means python-meh caught exception
            # and runs its main loop. Do not crash Gtk by running another one
            # from a different thread and just wait until python-meh is
            # finished, then quit.
            unbusyCursor()
            log.error("Unhandled exception caught, waiting for python-meh to "\
                      "exit")

            anaconda_threading.threadMgr.wait_for_error_threads()
            sys.exit(1)

        try:
            # Apply a widget-scale to hidpi monitors
            self._widgetScale()

            while not self._currentAction:
                self._currentAction = self._instantiateAction(self._actions[0])
                if not self._currentAction:
                    self._actions.pop(0)

                if not self._actions:
                    return

            self._currentAction.initialize()
            self._currentAction.refresh()

            self._currentAction.window.set_beta(not self._isFinal)
            self._currentAction.window.set_property("distribution",
                                                    self._distributionText())

            # Set some program-wide settings.
            settings = Gtk.Settings.get_default()
            settings.set_property("gtk-font-name", "Cantarell")

            # Get the path to the application data
            data_path = os.environ.get("ANACONDA_DATA", "/usr/share/anaconda")

            # Apply the application stylesheet
            css_path = os.path.join(data_path, "anaconda-gtk.css")
            provider = Gtk.CssProvider()
            provider.load_from_path(css_path)
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

            # Add the application icons to the theme
            icon_path = os.path.join(data_path, "pixmaps")
            icon_theme = Gtk.IconTheme.get_default()
            icon_theme.append_search_path(icon_path)

            # Apply the custom stylesheet
            if conf.ui.custom_stylesheet:
                try:
                    provider = Gtk.CssProvider()
                    provider.load_from_path(conf.ui.custom_stylesheet)
                    Gtk.StyleContext.add_provider_for_screen(
                        Gdk.Screen.get_default(), provider,
                        STYLE_PROVIDER_PRIORITY_CUSTOM)
                except GError as e:
                    log.error("Custom stylesheet %s failed to load:\n%s",
                              conf.ui.custom_stylesheet, e)

            # Look for updates to the stylesheet and apply them at a higher priority
            for updates_dir in ("updates", "product"):
                updates_css = "/run/install/%s/anaconda-gtk.css" % updates_dir
                if os.path.exists(updates_css):
                    provider = Gtk.CssProvider()
                    provider.load_from_path(updates_css)
                    Gtk.StyleContext.add_provider_for_screen(
                        Gdk.Screen.get_default(), provider,
                        STYLE_PROVIDER_PRIORITY_UPDATES)

            self.mainWindow.setCurrentAction(self._currentAction)
            # the window corresponding to the ection should now be visible to the user
            self._currentAction.entered.emit(self._currentAction)

            # Do this at the last possible minute.
            unbusyCursor()
        # If anything went wrong before we start the Gtk main loop, release
        # the gui lock and re-raise the exception so that meh can take over
        except Exception:
            self._gui_lock.release()
            raise

        Gtk.main()
    def __init__(self, datadir=None, logdir=None):
        DistUpgradeView.__init__(self)
        self.logdir = logdir
        if not datadir or datadir == '.':
            localedir = os.path.join(os.getcwd(), "mo")
            gladedir = os.getcwd()
        else:
            localedir = "/usr/share/locale/"
            gladedir = os.path.join(datadir, "gtkbuilder")

        # check if we have a display etc
        Gtk.init_check(sys.argv)

        try:
            locale.bindtextdomain("ubuntu-release-upgrader", localedir)
            gettext.textdomain("ubuntu-release-upgrader")
        except Exception as e:
            logging.warning("Error setting locales (%s)" % e)

        SimpleGtkbuilderApp.__init__(self, gladedir + "/DistUpgrade.ui",
                                     "ubuntu-release-upgrader")

        icons = Gtk.IconTheme.get_default()
        try:
            self.window_main.set_default_icon(
                icons.load_icon("system-software-update", 32, 0))
        except GObject.GError as e:
            logging.debug("error setting default icon, ignoring (%s)" % e)
            pass

        # terminal stuff
        self.create_terminal()

        self.prev_step = 0  # keep a record of the latest step
        # we don't use this currently
        #self.window_main.set_keep_above(True)
        self.icontheme = Gtk.IconTheme.get_default()
        self._webkit_view = None
        self.window_main.realize()
        self.window_main.get_window().set_functions(Gdk.WMFunction.MOVE)
        self._opCacheProgress = GtkOpProgress(self.progressbar_cache)
        self._acquireProgress = GtkAcquireProgressAdapter(self)
        self._cdromProgress = GtkCdromProgressAdapter(self)
        self._installProgress = GtkInstallProgressAdapter(self)
        # details dialog
        self.details_list = Gtk.TreeStore(GObject.TYPE_STRING)
        column = Gtk.TreeViewColumn("")
        render = Gtk.CellRendererText()
        column.pack_start(render, True)
        column.add_attribute(render, "markup", 0)
        self.treeview_details.append_column(column)
        self.details_list.set_sort_column_id(0, Gtk.SortType.ASCENDING)
        self.treeview_details.set_model(self.details_list)
        # lp: #1072460
        self.dialog_changes.set_resizable(False)

        def _activated(w):
            # the *current* expanded state which will change after the signal
            expanded = self.expander_details.get_expanded()
            self.dialog_changes.set_resizable(not expanded)

        self.expander_details.connect("activate", _activated)
        # FIXME: portme
        # Use italic style in the status labels
        #attrlist=Pango.AttrList()
        #attr = Pango.AttrStyle(Pango.Style.ITALIC, 0, -1)
        #attr = Pango.AttrScale(Pango.SCALE_SMALL, 0, -1)
        #attrlist.insert(attr)
        #self.label_status.set_property("attributes", attrlist)
        # reasonable fault handler
        sys.excepthook = self._handleException
Beispiel #42
0
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        if issubclass(ty, blivet.errors.StorageError) and value.hardware_fault:
            hw_error_msg = _("The installation was stopped due to what "
                             "seems to be a problem with your hardware. "
                             "The exact error message is:\n\n%s.\n\n "
                             "The installer will now terminate.") % str(value)
            self.intf.messageWindow(_("Hardware error occured"), hw_error_msg)
            sys.exit(0)
        else:
            try:
                # pylint: disable-msg=E0611
                from gi.repository import Gtk

                # XXX: Gtk stopped raising RuntimeError if it fails to
                # initialize. Horay! But will it stay like this? Let's be
                # cautious and raise the exception on our own to work in both
                # cases
                (initialized, args) = Gtk.init_check(None)
                if not initialized:
                    raise RuntimeError()

                if Gtk.main_level() > 0:
                    # main loop is running, don't crash it by running another one
                    # potentially from a different thread
                    log.debug("Gtk running, queuing exception handler to the "
                              "main loop")
                    GLib.idle_add(self.run_handleException, dump_info)
                else:
                    log.debug("Gtk not running, starting Gtk and running "
                              "exception handler in it")
                    super(AnacondaExceptionHandler,
                          self).handleException(dump_info)

            except RuntimeError:
                log.debug("Gtk cannot be initialized")
                # X not running (Gtk cannot be initialized)
                if threadMgr.in_main_thread():
                    log.debug("In the main thread, running exception handler")
                    if (issubclass(ty, CmdlineError)):
                        cmdline_error_msg = _(
                            "\nThe installation was stopped due to an "
                            "error which occurred while running in "
                            "non-interactive cmdline mode. Since there can "
                            "not be any questions in cmdline mode, edit "
                            "your kickstart file and retry installation. "
                            "\nThe exact error message is: \n\n%s. \n\nThe "
                            "installer will now terminate.") % str(value)

                        # since there is no UI in cmdline mode and it is completely
                        # non-interactive, we can't show a message window asking the user
                        # to acknowledge the error; instead, print the error out and sleep
                        # for a few seconds before exiting the installer
                        print(cmdline_error_msg)
                        time.sleep(180)
                        sys.exit()
                    else:
                        print "An unknown error has occured, look at the "\
                            "/tmp/anaconda-tb* file(s) for more details"
                        # in the main thread, run exception handler
                        super(AnacondaExceptionHandler,
                              self).handleException(dump_info)
                else:
                    log.debug("In a non-main thread, sending a message with "
                              "exception data")
                    # not in the main thread, just send message with exception
                    # data and let message handler run the exception handler in
                    # the main thread
                    exc_info = dump_info.exc_info
                    hubQ.send_exception(
                        (exc_info.type, exc_info.value, exc_info.stack))
Beispiel #43
0
        if message:
            window = self.get_toplevel()
            show_message(window, *message)
    
    def action_help_about_handler(self, widget):
        window = self.get_toplevel()
        show_about_dialog(window)
    
if __name__ == '__main__':
    """ bootstrap the application """
    import sys
    import os
    from gi.repository import GObject, GdkPixbuf
    
    GObject.threads_init()
    use_gui, __ = Gtk.init_check(sys.argv)
    
    window = Gtk.Window()
    window.set_title(_('Multitoner'))
    multitoner_icon_filename = os.path.join(DIRECTORY, 'assets', 'images',
                                            'multitoner_icon.svg')
    multitoner_icon = GdkPixbuf.Pixbuf.new_from_file(multitoner_icon_filename)
    window.set_icon(multitoner_icon)
    
    window.set_position(Gtk.WindowPosition.CENTER)
    window.set_default_size(640, 480)
    window.set_has_resize_grip(True)
    # the theme should do so
    window.set_border_width(5)
    
    
Beispiel #44
0
from pyanaconda.i18n import _

__all__ = ["ERROR_RAISE", "ERROR_CONTINUE", "ERROR_RETRY",
           "InvalidImageSizeError", "MissingImageError", "MediaUnmountError",
           "MediaMountError", "ScriptError", "CmdlineError",
           "errorHandler"]

# Only run the pango markup escape if the GUI is available
try:
    from gi.repository import Gtk

    # XXX: Gtk stopped raising RuntimeError if it fails to
    # initialize. Horay! But will it stay like this? Let's be
    # cautious and raise the exception on our own to work in both
    # cases
    initialized = Gtk.init_check(None)[0]
    if not initialized:
        raise RuntimeError()

    # If we don't do the check above this import will fail within _isys
    from pyanaconda.ui.gui.utils import escape_markup
except (RuntimeError, ImportError):
    escape_markup = lambda x: x

class InvalidImageSizeError(Exception):
    def __init__(self, message, filename):
        Exception.__init__(self, message)
        self.filename = filename

class MissingImageError(Exception):
    pass
Beispiel #45
0
def animate_graph(graph, pos, offscreen, new_burst_halo, dpi):
    """Animates the bursts of an SVO network over time.

    The `new_burst_halo` and `dpi` arguments are not used.
    """
    frame = 0
    g = graph

    # counter to make sure Gtk exits
    max_count = len(interval_list) - 1
    current_interval = 0

    # make sure there is a directory to dump frames to
    if offscreen and not os.path.exists(r"./data/frames"):
        os.makedirs(r"./data/frames")

    # for machines without video cards, emulate a display to allow saving frames to disk
    if Gtk.init_check()[0] == False:
        print('Display not found. Starting virtual display.')
        _xvfb = Xvfb(width=1920, height=1080)
        _xvfb.start()

    # light grey for default states, edges black when bursting
    no_burst = [0.5, 0.5, 0.5, 0.25]  # Grey
    e_burst = [0, 0, 0, 1]  # Black
    e_no_burst = [0.5, 0.5, 0.5, 0.25]  # Grey

    # heatmap for burst hierarchies, from seaborn color palettes: https://seaborn.pydata.org/tutorial/color_palettes.html
    blue_heatmap = {
        **dict.fromkeys([0], [0.5, 0.5, 0.5, 0.25]),
        **dict.fromkeys([1, 2, 3], [
                            0.8978854286812764, 0.939038831218762, 0.977362552864283, 1
                        ]),
        **dict.fromkeys([4, 5, 6], [
                            0.828881199538639, 0.8937639369473279, 0.954725105728566, 1
                        ]),
        **dict.fromkeys([7, 8, 9], [
                            0.7506343713956171, 0.8478431372549019, 0.9282122260668974, 1
                        ]),
        **dict.fromkeys([10, 11, 12], [
                            0.6325259515570935, 0.7976470588235294, 0.8868742791234141, 1
                        ]),
        **dict.fromkeys([13, 14, 15], [
                            0.491764705882353, 0.7219684736639754, 0.8547789311803152, 1
                        ]),
        **dict.fromkeys([16, 17, 18], [
                            0.36159938485198, 0.6427374086889658, 0.8165782391387928, 1
                        ]),
        **dict.fromkeys([19, 20, 21], [
                            0.24816608996539793, 0.5618915801614763, 0.7709803921568628, 1
                        ]),
        **dict.fromkeys([22, 23, 24], [
                            0.15072664359861593, 0.4644521337946943, 0.7207843137254902, 1
                        ]),
        **dict.fromkeys([25, 26, 27], [
                            0.07481737793156479, 0.3732564398308343, 0.6552095347943099, 1
                        ]),
        **dict.fromkeys([28, 29, 30, 31, 32], [
                            0.03137254901960784, 0.28161476355247983, 0.5582622068435218, 1
                        ])
    }

    # initialize all vertices and edges to the not_bursting state
    state = g.new_vertex_property("vector<double>")
    for v in g.vertices():
        state[v] = no_burst

    e_state = g.new_edge_property("vector<double>")
    for e in g.edges():
        e_state[e] = e_no_burst

    # initialize graph properties for current state

    currently_new = g.new_vertex_property("bool")
    currently_new.a = False  # assigns False to all vertices
    current_v_name = g.new_vertex_property('string')
    current_edge_weight = g.new_edge_property("int")

    # gather properties from imported graph

    bursting = g.vertex_properties["bursting"]
    max_hierarchy = g.vertex_properties["max_hierarchy"]
    hierarchies = g.vertex_properties["hierarchies"]
    new_burst = g.vertex_properties["new_burst"]

    # check if a different graph layout has been supplied, otherwise collect default layout from graph object
    if pos:
        pos = pos
    else:
        pos = g.vertex_properties["pos"]

    e_bursting = g.edge_properties["e_bursting"]
    e_weights = g.edge_properties['e_weights']

    times = g.graph_properties["times"]
    interval_list = g.graph_properties["interval_list"]

    # make sure graph is not filtered
    g.set_vertex_filter(None)
    g.set_edge_filter(None)

    # this creates a GTK+ window with the initial graph layout
    if not offscreen:
        # creates pop-up interactive Gtk window
        win = GraphWindow(
            g,
            pos,
            geometry=(800, 800),
            edge_color=e_state,
            vertex_fill_color=state,
            vertex_halo=currently_new,
            vertex_halo_color=[0.8, 0, 0, 0.6],
            vertex_text=current_v_name,
            #edge_pen_width = g.edge_properties['current_edge_weight'],
            vertex_text_position=2,
            vertex_font_size=13,
            vertex_text_color='black',
            vertex_shape=g.vertex_properties['vertex_shape'])
    else:
        # for dumping frames to disk
        frame = 0
        win = Gtk.OffscreenWindow()
        win.set_default_size(800, 800)
        win.graph = GraphWidget(
            g,
            pos,
            edge_color=e_state,
            vertex_fill_color=state,
            vertex_halo=currently_new,
            vertex_halo_color=[0.8, 0, 0, 0.6],
            vertex_text=current_v_name,
            #edge_pen_width = g.edge_properties['current_edge_weight'],
            vertex_text_position=2,
            vertex_font_size=13,
            vertex_text_color='black',
            vertex_shape=g.vertex_properties['vertex_shape'])

        win.add(win.graph)

    # This function will be called repeatedly by the GTK+ main loop, updating vertex and edge states
    # according to their bursting status.

    def update_state():
        # Gtk needs these variables to be global
        global max_count, current_interval, g, frame, _xvfb

        # check for failed virtual display
        if Gtk.init_check()[0] == False:
            print('Virtual display failed, quitting.')
            Gtk.main_quit()
            return False

        # check if we've exhausted all timepoints
        if current_interval > max_count:
            Gtk.main_quit()
            return False

        # update state of vertices and edges using the index of the current interval to access property map masks
        for v in g.vertices():
            if bursting[v][current_interval] == True:
                current_v_name[v] = g.vertex_properties.vertex_name[v]
                if new_burst[v][current_interval] == True:
                    currently_new[v] = True
                else:
                    currently_new[v] = False

                # use current burst hierarchy to update state based on heatmap color palette
                h_colour = blue_heatmap[hierarchies[v][current_interval]]
                state[v] = h_colour
            else:
                state[v] = no_burst
                current_v_name[
                    v] = ''  # avoid drawing vertex labels if they aren't bursting
                currently_new[v] = False

        for e in g.edges():
            if e_bursting[e][current_interval] == True:
                current_edge_weight[e] = e_weights[e][current_interval]
                e_state[e] = e_burst
            else:
                e_state[e] = e_no_burst

        # slow down the windowed animation

        if not offscreen:
            time.sleep(0.5)

        # the following will force the re-drawing of the graph and issue a
        # re-drawing of the GTK window.

        win.graph.regenerate_surface()
        win.graph.queue_draw()

        # if doing an offscreen animation, dump frame to disk
        if offscreen:

            # names file based on current frame number
            this_filename = r'./data/frames/graph%06d.png' % frame

            pixbuf = win.get_pixbuf()
            pixbuf.savev(this_filename, 'png', ["x-dpi", "y-dpi"],
                         ["300", "300"])

            # add datetime to the frame just saved to disk
            with Image.open(this_filename) as im:
                try:
                    myfont = ImageFont.truetype("./Arial.ttf", 30)
                except:
                    myfont = ImageFont.load_default()

                width, height = im.size

                try:
                    date = datetime.datetime.fromtimestamp(
                        times[frame - 1]).strftime('%Y-%m-%d')
                    msg = str(date)
                except KeyError:
                    msg = "No time data for this slice"

                draw = ImageDraw.Draw(im)
                w, h = draw.textsize(msg, myfont)
                draw.text(((width - w) / 2, height / 50),
                          msg,
                          font=myfont,
                          fill="black")

                im.save(this_filename)
            frame += 1  # increment frame for file naming and date stamping

            # exit after dumping the final time interval frame
            if current_interval == max_count:
                Gtk.main_quit()
                return False

        # need to return True so that the main loop will call this function more
        # than once.
        current_interval += 1
        return True

    # bind the function above as an 'idle' callback
    cid = GLib.idle_add(update_state)

    # give the user the ability to stop the program by closing the window
    win.connect("delete_event", Gtk.main_quit)

    # actually show the window, and start the main loop
    win.show_all()
    Gtk.main()
Beispiel #46
0
def _init_gtk():
    """Call before using Gtk/Gdk"""

    import gi

    # pygiaio 3.14rev16 switched to fontconfig for PangoCairo. As this results
    # in 100% CPU under win7 revert it. Maybe we need to update the
    # cache in the windows installer for it to work... but for now revert.
    if is_windows():
        environ['PANGOCAIRO_BACKEND'] = 'win32'
        environ["GTK_CSD"] = "0"

    # disable for consistency and trigger events seem a bit flaky here
    if is_osx():
        environ["GTK_OVERLAY_SCROLLING"] = "0"

    # make sure GdkX11 doesn't get used under Windows
    if os.name == "nt":
        sys.modules["gi.repository.GdkX11"] = None

    try:
        # not sure if this is available under Windows
        gi.require_version("GdkX11", "3.0")
        from gi.repository import GdkX11
        GdkX11
    except (ValueError, ImportError):
        pass

    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("Pango", "1.0")
    gi.require_version('Soup', '2.4')

    from gi.repository import Gtk, Soup
    from quodlibet.qltk import ThemeOverrider, gtk_version

    # Work around missing annotation in older libsoup (Ubuntu 14.04 at least)
    message = Soup.Message()
    try:
        message.set_request(None, Soup.MemoryUse.COPY, b"")
    except TypeError:
        orig = Soup.Message.set_request

        def new_set_request(self, content_type, req_use, req_body):
            return orig(self, content_type, req_use, req_body, len(req_body))

        Soup.Message.set_request = new_set_request

    # PyGObject doesn't fail anymore when init fails, so do it ourself
    initialized, argv[:] = Gtk.init_check(argv)
    if not initialized:
        raise SystemExit("Gtk.init failed")

    # include our own icon theme directory
    theme = Gtk.IconTheme.get_default()
    theme_search_path = get_image_dir()
    assert os.path.exists(theme_search_path)
    theme.append_search_path(theme_search_path)

    # Force menu/button image related settings. We might show too many atm
    # but this makes sure we don't miss cases where we forgot to force them
    # per widget.
    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # some day... but not now
    warnings.filterwarnings(
        'ignore', '.*Stock items are deprecated.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*:use-stock.*', Warning)
    warnings.filterwarnings(
        'ignore', '.*The property GtkAlignment:[^\s]+ is deprecated.*',
        Warning)

    settings = Gtk.Settings.get_default()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        settings.set_property("gtk-button-images", True)
        settings.set_property("gtk-menu-images", True)
    if hasattr(settings.props, "gtk_primary_button_warps_slider"):
        # https://bugzilla.gnome.org/show_bug.cgi?id=737843
        settings.set_property("gtk-primary-button-warps-slider", True)

    # Make sure PyGObject includes support for foreign cairo structs
    try:
        gi.require_foreign("cairo")
    except AttributeError:
        # older pygobject
        pass
    except ImportError:
        print_e("PyGObject is missing cairo support")
        exit(1)

    css_override = ThemeOverrider()

    # CSS overrides
    if os.name == "nt":
        # somehow borders are missing under Windows & Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            .menu {
                border: 1px solid @borders;
            }
        """)
        css_override.register_provider("", style_provider)

    if sys.platform == "darwin":
        # fix duplicated shadows for popups with Gtk+3.14
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            GtkWindow {
                box-shadow: none;
            }
            .tooltip {
                border-radius: 0;
                padding: 0;
            }
            .tooltip.background {
                background-clip: border-box;
            }
            """)
        css_override.register_provider("", style_provider)

    if gtk_version[:2] >= (3, 20):
        # https://bugzilla.gnome.org/show_bug.cgi?id=761435
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(b"""
            spinbutton, button {
                min-height: 1.8rem;
            }

            .view button {
                min-height: 2.0rem;
            }

            entry {
                min-height: 2.4rem;
            }

            entry.cell {
                min-height: 0;
            }
        """)
        css_override.register_provider("Adwaita", style_provider)
        css_override.register_provider("HighContrast", style_provider)

    # https://bugzilla.gnome.org/show_bug.cgi?id=708676
    warnings.filterwarnings('ignore', '.*g_value_get_int.*', Warning)

    # blacklist some modules, simply loading can cause segfaults
    sys.modules["gtk"] = None
    sys.modules["gpod"] = None
    sys.modules["gnome"] = None

    from quodlibet.qltk import pygobject_version, gtk_version

    MinVersions.GTK.check(gtk_version)
    MinVersions.PYGOBJECT.check(pygobject_version)
Beispiel #47
0
    def update_state():
        # Gtk needs these variables to be global
        global max_count, current_interval, g, frame, _xvfb

        # check for failed virtual display
        if Gtk.init_check()[0] == False:
            print('Virtual display failed, quitting.')
            Gtk.main_quit()
            return False

        # check if we've exhausted all timepoints
        if current_interval > max_count:
            Gtk.main_quit()
            return False

        # update state of vertices and edges using the index of the current interval to access property map masks
        for v in g.vertices():
            if bursting[v][current_interval] == True:
                current_v_name[v] = g.vertex_properties.vertex_name[v]
                if new_burst[v][current_interval] == True:
                    currently_new[v] = True
                else:
                    currently_new[v] = False

                # use current burst hierarchy to update state based on heatmap color palette
                h_colour = blue_heatmap[hierarchies[v][current_interval]]
                state[v] = h_colour
            else:
                state[v] = no_burst
                current_v_name[
                    v] = ''  # avoid drawing vertex labels if they aren't bursting
                currently_new[v] = False

        for e in g.edges():
            if e_bursting[e][current_interval] == True:
                current_edge_weight[e] = e_weights[e][current_interval]
                e_state[e] = e_burst
            else:
                e_state[e] = e_no_burst

        # slow down the windowed animation

        if not offscreen:
            time.sleep(0.5)

        # the following will force the re-drawing of the graph and issue a
        # re-drawing of the GTK window.

        win.graph.regenerate_surface()
        win.graph.queue_draw()

        # if doing an offscreen animation, dump frame to disk
        if offscreen:

            # names file based on current frame number
            this_filename = r'./data/frames/graph%06d.png' % frame

            pixbuf = win.get_pixbuf()
            pixbuf.savev(this_filename, 'png', ["x-dpi", "y-dpi"],
                         ["300", "300"])

            # add datetime to the frame just saved to disk
            with Image.open(this_filename) as im:
                try:
                    myfont = ImageFont.truetype("./Arial.ttf", 30)
                except:
                    myfont = ImageFont.load_default()

                width, height = im.size

                try:
                    date = datetime.datetime.fromtimestamp(
                        times[frame - 1]).strftime('%Y-%m-%d')
                    msg = str(date)
                except KeyError:
                    msg = "No time data for this slice"

                draw = ImageDraw.Draw(im)
                w, h = draw.textsize(msg, myfont)
                draw.text(((width - w) / 2, height / 50),
                          msg,
                          font=myfont,
                          fill="black")

                im.save(this_filename)
            frame += 1  # increment frame for file naming and date stamping

            # exit after dumping the final time interval frame
            if current_interval == max_count:
                Gtk.main_quit()
                return False

        # need to return True so that the main loop will call this function more
        # than once.
        current_interval += 1
        return True
Beispiel #48
0
    def handleException(self, dump_info):
        """
        Our own handleException method doing some additional stuff before
        calling the original python-meh's one.

        :type dump_info: an instance of the meh.DumpInfo class
        :see: python-meh's ExceptionHandler.handleException

        """

        log.debug("running handleException")
        exception_lines = traceback.format_exception(*dump_info.exc_info)
        log.critical("\n".join(exception_lines))

        ty = dump_info.exc_info.type
        value = dump_info.exc_info.value

        try:
            gi.require_version("Gtk", "3.0")

            from gi.repository import Gtk

            # XXX: Gtk stopped raising RuntimeError if it fails to
            # initialize. Horay! But will it stay like this? Let's be
            # cautious and raise the exception on our own to work in both
            # cases
            initialized = Gtk.init_check(None)[0]
            if not initialized:
                raise RuntimeError()

            # Attempt to grab the GUI initializing lock, do not block
            if not self._gui_lock.acquire(False):
                # the graphical interface is running, don't crash it by
                # running another one potentially from a different thread
                log.debug("Gtk running, queuing exception handler to the " "main loop")
                GLib.idle_add(self._main_loop_handleException, dump_info)
            else:
                log.debug("Gtk not running, starting Gtk and running " "exception handler in it")
                self._main_loop_handleException(dump_info)

        except (RuntimeError, ImportError, ValueError):
            log.debug("Gtk cannot be initialized")
            # X not running (Gtk cannot be initialized)
            if threadMgr.in_main_thread():
                log.debug("In the main thread, running exception handler")
                if issubclass(ty, CmdlineError) or not self._interactive:
                    if issubclass(ty, CmdlineError):
                        cmdline_error_msg = _(
                            "\nThe installation was stopped due to "
                            "incomplete spokes detected while running "
                            "in non-interactive cmdline mode. Since there "
                            "cannot be any questions in cmdline mode, "
                            "edit your kickstart file and retry "
                            "installation.\nThe exact error message is: "
                            "\n\n%s.\n\nThe installer will now terminate."
                        ) % str(value)
                    else:
                        cmdline_error_msg = _(
                            "\nRunning in cmdline mode, no interactive debugging "
                            "allowed.\nThe exact error message is: "
                            "\n\n%s.\n\nThe installer will now terminate."
                        ) % str(value)

                    # since there is no UI in cmdline mode and it is completely
                    # non-interactive, we can't show a message window asking the user
                    # to acknowledge the error; instead, print the error out and sleep
                    # for a few seconds before exiting the installer
                    print(cmdline_error_msg)
                    time.sleep(10)
                    sys.exit(1)
                else:
                    print("\nAn unknown error has occured, look at the " "/tmp/anaconda-tb* file(s) for more details")
                    # in the main thread, run exception handler
                    self._main_loop_handleException(dump_info)
            else:
                log.debug("In a non-main thread, sending a message with " "exception data")
                # not in the main thread, just send message with exception
                # data and let message handler run the exception handler in
                # the main thread
                exc_info = dump_info.exc_info
                hubQ.send_exception((exc_info.type, exc_info.value, exc_info.stack))
Beispiel #49
0
def init_test_environ():
    # this was renamed in Python 3, provide backwards compatible name
    if sys.version_info[:2] == (2, 7):
        unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp

    if sys.version_info[0] == 3:
        unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex
        unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex

    def dbus_launch_session():
        if os.name == "nt" or sys.platform == "darwin":
            return (-1, "")

        try:
            out = subprocess.check_output([
                "dbus-daemon", "--session", "--fork", "--print-address=1",
                "--print-pid=1"
            ])
        except (subprocess.CalledProcessError, OSError):
            return (-1, "")
        else:
            if sys.version_info[0] == 3:
                out = out.decode("utf-8")
            addr, pid = out.splitlines()
            return int(pid), addr

    pid, addr = dbus_launch_session()
    if pid >= 0:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = addr
        atexit.register(os.kill, pid, signal.SIGKILL)
    else:
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = "."

    tests_builddir = os.path.abspath(
        os.environ.get('TESTS_BUILDDIR', os.path.dirname(__file__)))
    builddir = os.path.dirname(tests_builddir)
    tests_srcdir = os.path.abspath(os.path.dirname(__file__))
    srcdir = os.path.dirname(tests_srcdir)

    sys.path.insert(0, os.path.join(builddir, 'gi'))
    sys.path.insert(0, tests_srcdir)
    sys.path.insert(0, srcdir)
    sys.path.insert(0, tests_builddir)
    sys.path.insert(0, builddir)

    # force untranslated messages, as we check for them in some tests
    os.environ['LC_MESSAGES'] = 'C'
    os.environ['G_DEBUG'] = 'fatal-warnings fatal-criticals'
    if sys.platform == "darwin":
        # gtk 3.22 has warnings and ciriticals on OS X, ignore for now
        os.environ['G_DEBUG'] = ''

    # make Gio able to find our gschemas.compiled in tests/. This needs to be set
    # before importing Gio. Support a separate build tree, so look in build dir
    # first.
    os.environ['GSETTINGS_BACKEND'] = 'memory'
    os.environ['GSETTINGS_SCHEMA_DIR'] = tests_builddir
    os.environ['G_FILENAME_ENCODING'] = 'UTF-8'

    # Force the default theme so broken themes don't affect the tests
    os.environ['GTK_THEME'] = 'Adwaita'

    import gi
    gi.require_version("GIRepository", "2.0")
    from gi.repository import GIRepository
    repo = GIRepository.Repository.get_default()
    repo.prepend_library_path(os.path.join(tests_builddir))
    repo.prepend_library_path(os.path.join(tests_builddir, ".libs"))
    repo.prepend_search_path(tests_builddir)

    def try_require_version(namespace, version):
        try:
            gi.require_version(namespace, version)
        except ValueError:
            # prevent tests from running with the wrong version
            sys.modules["gi.repository." + namespace] = None

    # Optional
    try_require_version("Gtk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("Gdk", os.environ.get("TEST_GTK_VERSION", "3.0"))
    try_require_version("GdkPixbuf", "2.0")
    try_require_version("Pango", "1.0")
    try_require_version("PangoCairo", "1.0")
    try_require_version("Atk", "1.0")

    # Required
    gi.require_versions({
        "GIMarshallingTests": "1.0",
        "Regress": "1.0",
        "GLib": "2.0",
        "Gio": "2.0",
        "GObject": "2.0",
    })

    # It's disabled for stable releases by default, this makes sure it's
    # always on for the tests.
    warnings.simplefilter('default', gi.PyGIDeprecationWarning)

    # Otherwise we crash on the first gtk use when e.g. DISPLAY isn't set
    try:
        from gi.repository import Gtk
    except ImportError:
        pass
    else:
        if not Gtk.init_check([])[0]:
            raise RuntimeError("Gtk available, but Gtk.init_check() failed")