예제 #1
0
파일: keymap.py 프로젝트: prodigeni/thus
    def setkb(self):
        subprocess.check_call(["setxkbmap", "-layout", self.keyboard_layout, "-variant", self.keyboard_variant])

        # It makes no sense try loadkeys here (it's console)
        # subprocess.check_call(['loadkeys', self.keyboard_layout])
        with misc.raised_privileges():
            subprocess.check_call(["localectl", "set-keymap", "--no-convert", self.keyboard_layout])
예제 #2
0
    def setkb(self):
        subprocess.check_call([
            'setxkbmap', '-layout', self.keyboard_layout, "-variant",
            self.keyboard_variant
        ])

        with misc.raised_privileges():
            subprocess.check_call(
                ['kbctl', '--set-layout', self.keyboard_layout])
예제 #3
0
파일: updater.py 프로젝트: Llumex03/Cnchi
    def unzip_and_copy(self, zip_path, dst_dir):
        """ Unzip (decompress) a zip file using zipfile standard module """
        import zipfile

        with zipfile.ZipFile(zip_path) as zip_file:
            for member in zip_file.infolist():
                zip_file.extract(member, dst_dir)
                full_path = os.path.join(dst_dir, member.filename)
                dst_full_path = os.path.join("/usr/share/cnchi", full_path.split("/tmp/Cnchi-master/")[1])
                if os.path.isfile(dst_full_path):
                    if dst_full_path in self.md5s:
                        md5 = get_md5_from_file(full_path)
                        if self.md5s[dst_full_path] == md5:
                            #print(full_path, dst_full_path, md5)
                            try:
                                with misc.raised_privileges():
                                    shutil.copyfile(full_path, dst_full_path)
                            except FileNotFoundError:
                                logging.error(_("Can't copy %s to %s"), full_path, dst_full_path)
예제 #4
0
파일: cnchi.py 프로젝트: prescott66/Cnchi
def update_cnchi():
    """ Runs updater function to update cnchi to the latest version if necessary """
    upd = updater.Updater(force_update=cmd_line.update)

    if upd.update():
        #remove_temp_files()
        if cmd_line.update:
            # Remove -uu and --update options from new call
            new_argv = []
            for argv in sys.argv:
                if argv != "-uu" and argv != "--update":
                    new_argv.append(argv)
        else:
            new_argv = sys.argv

        print(_("Program updated! Restarting..."))

        # Run another instance of Cnchi (which will be the new version)
        with misc.raised_privileges():
            os.execl(sys.executable, *([sys.executable] + new_argv))
        sys.exit(0)
예제 #5
0
파일: cnchi.py 프로젝트: prescott66/Cnchi
def update_cnchi():
    """ Runs updater function to update cnchi to the latest version if necessary """
    upd = updater.Updater(force_update=cmd_line.update)

    if upd.update():
        #remove_temp_files()
        if cmd_line.update:
            # Remove -uu and --update options from new call
            new_argv = []
            for argv in sys.argv:
                if argv != "-uu" and argv != "--update":
                    new_argv.append(argv)
        else:
            new_argv = sys.argv

        print(_("Program updated! Restarting..."))

        # Run another instance of Cnchi (which will be the new version)
        with misc.raised_privileges():
            os.execl(sys.executable, *([sys.executable] + new_argv))
        sys.exit(0)
예제 #6
0
    def unzip_and_copy(self, zip_path, dst_dir):
        """ Unzip (decompress) a zip file using zipfile standard module """
        import zipfile

        with zipfile.ZipFile(zip_path) as zip_file:
            for member in zip_file.infolist():
                zip_file.extract(member, dst_dir)
                full_path = os.path.join(dst_dir, member.filename)
                dst_full_path = os.path.join(
                    "/usr/share/cnchi",
                    full_path.split("/tmp/Cnchi-master/")[1])
                if os.path.isfile(dst_full_path):
                    if dst_full_path in self.md5s:
                        md5 = get_md5_from_file(full_path)
                        if self.md5s[dst_full_path] == md5:
                            #print(full_path, dst_full_path, md5)
                            try:
                                with misc.raised_privileges():
                                    shutil.copyfile(full_path, dst_full_path)
                            except FileNotFoundError:
                                logging.error(_("Can't copy %s to %s"),
                                              full_path, dst_full_path)
예제 #7
0
파일: i18n.py 프로젝트: Acidburn0zzz/Cnchi
def get_languages(language_list="data/languagelist.data.gz", current_language_index=-1, only_installable=False):
    import gzip
    #import icu

    current_language = "English"

    if only_installable:
        from apt.cache import Cache
        #workaround for an issue where euid != uid and the
        #apt cache has not yet been loaded causing a SystemError
        #when libapt-pkg tries to load the Cache the first time.
        with misc.raised_privileges():
            cache = Cache()

    languagelist = gzip.open(language_list)
    language_display_map = {}
    i = 0
    for line in languagelist:
        line = utf8(line)
        if line == '' or line == '\n':
            continue
        code, name, trans = line.strip('\n').split(':')[1:]
        if code in ('C', 'dz', 'km'):
            i += 1
            continue
        # KDE fails to round-trip strings containing U+FEFF ZERO WIDTH
        # NO-BREAK SPACE, and we don't care about the NBSP anyway, so strip
        # it.
        #   https://bugs.launchpad.net/bugs/1001542
        #   (comment #5 and on)
        trans = trans.strip(" \ufeff")

        if only_installable:
            pkg_name = 'language-pack-%s' % code
            #special case these
            if pkg_name.endswith('_CN'):
                pkg_name = 'language-pack-zh-hans'
            elif pkg_name.endswith('_TW'):
                pkg_name = 'language-pack-zh-hant'
            elif pkg_name.endswith('_NO'):
                pkg_name = pkg_name.split('_NO')[0]
            elif pkg_name.endswith('_BR'):
                pkg_name = pkg_name.split('_BR')[0]
            try:
                pkg = cache[pkg_name]
                if not (pkg.installed or pkg.candidate):
                    i += 1
                    continue
            except KeyError:
                i += 1
                continue

        language_display_map[trans] = (name, code)
        if i == current_language_index:
            current_language = trans

        i += 1
    languagelist.close()

    if only_installable:
        del cache

    #try:
        # Note that we always collate with the 'C' locale.  This is far
        # from ideal.  But proper collation always requires a specific
        # language for its collation rules (languages frequently have
        # custom sorting).  This at least gives us common sorting rules,
        # like stripping accents.
        #collator = icu.Collator.createInstance(icu.Locale('C'))
    #except:
    #       collator = None

    collator = None

    def compare_choice(x):
        if language_display_map[x][1] == 'C':
            return None  # place C first
        if collator:
            try:
                return collator.getCollationKey(x).getByteArray()
            except:
                pass
        # Else sort by unicode code point, which isn't ideal either,
        # but also has the virtue of sorting like-glyphs together
        return x

    sorted_choices = sorted(language_display_map, key=compare_choice)

    return current_language, sorted_choices, language_display_map
예제 #8
0
    def run(self):
        """ Run thread """

        # Wait until there is an Internet connection available
        while not misc.has_connection():
            if self.settings.get('stop_all_threads'):
                return
            time.sleep(1)  # Delay

        if not os.path.exists(self.reflector_script):
            logging.warning(_("Can't find update mirrors script"))
            return

        # Uncomment Antergos mirrors and comment out auto selection so rankmirrors can find the best mirror.

        autoselect = "http://mirrors.antergos.com/$repo/$arch"

        if os.path.exists(self.antergos_mirrorlist):
            with open(self.antergos_mirrorlist) as mirrors:
                lines = [x.strip() for x in mirrors.readlines()]

            for i in range(len(lines)):
                if lines[i].startswith("Server") and autoselect in lines[i]:
                    # Comment out auto selection
                    lines[i] = "#" + lines[i]
                elif lines[i].startswith(
                        "#Server") and autoselect not in lines[i]:
                    # Uncomment Antergos mirror
                    lines[i] = lines[i].lstrip("#")

            with misc.raised_privileges():
                # Backup original file
                shutil.copy(self.antergos_mirrorlist,
                            self.antergos_mirrorlist + ".cnchi_backup")
                # Write new one
                with open(self.antergos_mirrorlist, 'w') as mirrors:
                    mirrors.write("\n".join(lines) + "\n")

        # Run rankmirrors command
        try:
            with misc.raised_privileges():
                self.rankmirrors_pid = subprocess.Popen(
                    [self.reflector_script]).pid

        except subprocess.CalledProcessError as err:
            logging.error(_("Couldn't execute auto mirror selection"))

        # Check arch mirrorlist against mirror status data, remove any bad mirrors.
        if _use_requests and os.path.exists(self.arch_mirrorlist):
            # Use session to avoid silly warning
            # See https://github.com/kennethreitz/requests/issues/1882
            with requests.Session() as session:
                status = session.get(self.arch_mirror_status).json()
                mirrors = status['urls']

            with open(self.arch_mirrorlist) as arch_mirrors:
                lines = [x.strip() for x in arch_mirrors.readlines()]

            for i in range(len(lines)):
                server_uncommented = lines[i].startswith("Server")
                server_commented = lines[i].startswith("#Server")
                if server_commented or server_uncommented:
                    url = lines[i].split('=')[1].strip()
                    check = self.check_mirror_status(mirrors, url)
                    if not check and server_uncommented:
                        # Bad mirror, comment it
                        lines[i] = "#" + lines[i]
                    if check and server_commented:
                        # It's a good mirror, uncomment it
                        lines[i] = lines[i].lstrip("#")

            with misc.raised_privileges():
                # Backup original file
                shutil.copy(self.arch_mirrorlist,
                            self.arch_mirrorlist + ".cnchi_backup")
                # Write new one
                with open(self.arch_mirrorlist, 'w') as arch_mirrors:
                    arch_mirrors.write("\n".join(lines) + "\n")

        logging.debug(_("Auto mirror selection has been run successfully"))
예제 #9
0
파일: slides.py 프로젝트: g97iulio1609/thus
    def manage_events_from_cb_queue(self):
        """ This function is called from cnchi.py with a timeout function
            We should do as less as possible here, we want to maintain our
            queue message as empty as possible """
        if self.fatal_error:
            return False

        while self.callback_queue.empty() is False:
            try:
                event = self.callback_queue.get_nowait()
            except queue.Empty:
                return True

            if event[0] == 'percent':
                self.progress_bar.set_fraction(event[1])
            elif event[0] == 'global_percent':
                self.show_global_progress_bar_if_hidden()
                self.global_progress_bar.set_fraction(event[1])
            elif event[0] == 'pulse':
                self.do_progress_pulse()
            elif event[0] == 'stop_pulse':
                self.stop_pulse()
            elif event[0] == 'finished':
                logging.info(event[1])
                self.should_pulse = False

                # Warn user about GRUB and ask if we should open wiki page.
                if not self.settings.get('bootloader_ok'):
                    import webbrowser
                    self.boot_warn = _(
                        "IMPORTANT: There may have been a problem with the Grub(2) bootloader\n"
                        "installation which could prevent your system from booting properly. Before\n"
                        "rebooting, you may want to verify whether or not GRUB(2) is installed and\n"
                        "configured. The Arch Linux Wiki contains troubleshooting information:\n"
                        "\thttps://wiki.archlinux.org/index.php/GRUB\n"
                        "\nWould you like to view the wiki page now?")
                    response = show.question(self.boot_warn)
                    if response == Gtk.ResponseType.YES:
                        webbrowser.open(
                            'https://wiki.archlinux.org/index.php/GRUB')

                self.set_message(self.install_ok)
                response = show.question(self.install_ok)

                if response == Gtk.ResponseType.YES:
                    logging.shutdown()
                    self.reboot()
                else:
                    tmp_files = [
                        ".setup-running", ".km-running",
                        "setup-pacman-running", "setup-mkinitcpio-running",
                        ".tz-running", ".setup", "thus.log"
                    ]
                    for t in tmp_files:
                        p = os.path.join("/tmp", t)
                        if os.path.exists(p):
                            # TODO: some of these tmp files are created with sudo privileges
                            # (this should be fixed) meanwhile, we need sudo privileges to remove them
                            with misc.raised_privileges():
                                os.remove(p)
                    self.callback_queue.task_done()
                    logging.shutdown()
                    os._exit(0)

                return False
            elif event[0] == 'error':
                self.callback_queue.task_done()
                # A fatal error has been issued. We empty the queue
                self.empty_queue()
                self.fatal_error = True
                show.fatal_error(event[1])
                # Ask if user wants to retry
                res = show.question(_("Do you want to retry?"))
                if res == GTK_RESPONSE_YES:
                    # Restart installation process
                    logging.debug("Restarting installation process...")
                    p = self.settings.get('installer_thread_call')

                    self.process = installation_process.InstallationProcess(
                        self.settings, self.callback_queue, p['mount_devices'],
                        p['fs_devices'], p['ssd'], p['alternate_package_list'],
                        p['blvm'])

                    self.process.start()
                    return True
                else:
                    self.fatal_error = True
                    return False
            elif event[0] == 'debug':
                logging.debug(event[1])
            elif event[0] == 'warning':
                logging.warning(event[1])
            else:
                logging.info(event[1])
                self.set_message(event[1])

            self.callback_queue.task_done()

        return True
예제 #10
0
    def setkb(self):
        subprocess.check_call(['setxkbmap', '-layout', self.keyboard_layout, "-variant", self.keyboard_variant])

        with misc.raised_privileges():
            subprocess.check_call(['localectl', 'set-keymap', '--no-convert', self.keyboard_layout])
예제 #11
0
    def manage_events_from_cb_queue(self):
        """ This function is called from cnchi.py with a timeout function
            We should do as less as possible here, we want to maintain our
            queue message as empty as possible """
        if self.fatal_error:
            return False

        while self.callback_queue.empty() is False:
            try:
                event = self.callback_queue.get_nowait()
            except queue.Empty:
                return True

            if event[0] == 'percent':
                self.progress_bar.set_fraction(event[1])
            elif event[0] == 'global_percent':
                self.show_global_progress_bar_if_hidden()
                self.global_progress_bar.set_fraction(event[1])
            elif event[0] == 'pulse':
                self.do_progress_pulse()
            elif event[0] == 'stop_pulse':
                self.stop_pulse()
            elif event[0] == 'finished':
                logging.info(event[1])
                self.should_pulse = False

                # Warn user about GRUB and ask if we should open wiki page.
                if not self.settings.get('bootloader_ok'):
                    import webbrowser
                    self.boot_warn = _("IMPORTANT: There may have been a problem with the Grub(2) bootloader\n"
                                       "installation which could prevent your system from booting properly. Before\n"
                                       "rebooting, you may want to verify whether or not GRUB(2) is installed and\n"
                                       "configured. The Arch Linux Wiki contains troubleshooting information:\n"
                                       "\thttps://wiki.archlinux.org/index.php/GRUB\n"
                                       "\nWould you like to view the wiki page now?")
                    response = show.question(self.boot_warn)
                    if response == Gtk.ResponseType.YES:
                        webbrowser.open('https://wiki.archlinux.org/index.php/GRUB')

                self.set_message(self.install_ok)
                response = show.question(self.install_ok)

                if response == Gtk.ResponseType.YES:
                    logging.shutdown()
                    self.reboot()
                else:
                    tmp_files = [".setup-running", ".km-running", "setup-pacman-running", "setup-mkinitcpio-running", ".tz-running", ".setup", "thus.log"]
                    for t in tmp_files:
                        p = os.path.join("/tmp", t)
                        if os.path.exists(p):
                            # TODO: some of these tmp files are created with sudo privileges
                            # (this should be fixed) meanwhile, we need sudo privileges to remove them
                            with misc.raised_privileges():
                                os.remove(p)
                    self.callback_queue.task_done()
                    logging.shutdown()
                    os._exit(0)

                return False
            elif event[0] == 'error':
                self.callback_queue.task_done()
                # A fatal error has been issued. We empty the queue
                self.empty_queue()
                self.fatal_error = True
                show.fatal_error(event[1])
                # Ask if user wants to retry
                res = show.question(_("Do you want to retry?"))
                if res == GTK_RESPONSE_YES:
                    # Restart installation process
                    logging.debug("Restarting installation process...")
                    p = self.settings.get('installer_thread_call')

                    self.process = installation_process.InstallationProcess(
                        self.settings,
                        self.callback_queue,
                        p['mount_devices'],
                        p['fs_devices'],
                        p['ssd'],
                        p['alternate_package_list'],
                        p['blvm'])

                    self.process.start()
                    return True
                else:
                    self.fatal_error = True
                    return False
            elif event[0] == 'debug':
                logging.debug(event[1])
            elif event[0] == 'warning':
                logging.warning(event[1])
            else:
                logging.info(event[1])
                self.set_message(event[1])

            self.callback_queue.task_done()

        return True
예제 #12
0
파일: slides.py 프로젝트: prodigeni/thus
    def manage_events_from_cb_queue(self):
        """ This function is called from cnchi.py with a timeout function
            We should do as less as possible here, we want to maintain our
            queue message as empty as possible """
        if self.fatal_error:
            return False

        while self.callback_queue.empty() is False:
            try:
                event = self.callback_queue.get_nowait()
            except queue.Empty:
                return True

            if event[0] == "percent":
                self.progress_bar.set_fraction(event[1])
            elif event[0] == "global_percent":
                self.show_global_progress_bar_if_hidden()
                self.global_progress_bar.set_fraction(event[1])
            elif event[0] == "pulse":
                self.do_progress_pulse()
            elif event[0] == "stop_pulse":
                self.stop_pulse()
            elif event[0] == "finished":
                logging.info(event[1])
                self.should_pulse = False
                self.set_message(self.install_ok)
                response = show.question(self.install_ok)
                if response == Gtk.ResponseType.YES:
                    self.reboot()
                else:
                    tmp_files = [
                        ".setup-running",
                        ".km-running",
                        "setup-pacman-running",
                        "setup-mkinitcpio-running",
                        ".tz-running",
                        ".setup",
                        "thus.log",
                    ]
                    for t in tmp_files:
                        p = os.path.join("/tmp", t)
                        if os.path.exists(p):
                            # TODO: some of these tmp files are created with sudo privileges
                            # (this should be fixed) meanwhile, we need sudo privileges to remove them
                            with misc.raised_privileges():
                                os.remove(p)
                    self.callback_queue.task_done()
                    os._exit(0)

                return False
            elif event[0] == "error":
                self.callback_queue.task_done()
                # A fatal error has been issued. We empty the queue
                self.empty_queue()
                self.fatal_error = True
                show.fatal_error(event[1])
                # Ask if user wants to retry
                res = show.question(_("Do you want to retry?"))
                if res == GTK_RESPONSE_YES:
                    # Restart installation process
                    logging.debug("Restarting installation process...")
                    p = self.settings.get("installer_thread_call")

                    self.process = installation_process.InstallationProcess(
                        self.settings,
                        self.callback_queue,
                        p["mount_devices"],
                        p["fs_devices"],
                        p["ssd"],
                        p["alternate_package_list"],
                        p["blvm"],
                    )

                    self.process.start()
                    return True
                else:
                    self.fatal_error = True
                    return False
            elif event[0] == "debug":
                logging.debug(event[1])
            elif event[0] == "warning":
                logging.warning(event[1])
            else:
                logging.info(event[1])
                self.set_message(event[1])

            self.callback_queue.task_done()

        return True
예제 #13
0
    def run(self):
        """ Run thread """

        # Wait until there is an Internet connection available
        while not misc.has_connection():
            if self.settings.get('stop_all_threads'):
                return
            time.sleep(1)  # Delay

        if not os.path.exists(self.reflector_script):
            logging.warning(_("Can't find update mirrors script"))
            return

        # Uncomment Antergos mirrors and comment out auto selection so rankmirrors can find the best mirror.

        autoselect = "http://mirrors.antergos.com/$repo/$arch"

        if os.path.exists(self.antergos_mirrorlist):
            with open(self.antergos_mirrorlist) as mirrors:
                lines = [x.strip() for x in mirrors.readlines()]

            for i in range(len(lines)):
                if lines[i].startswith("Server") and autoselect in lines[i]:
                    # Comment out auto selection
                    lines[i] = "#" + lines[i]
                elif lines[i].startswith("#Server") and autoselect not in lines[i]:
                    # Uncomment Antergos mirror
                    lines[i] = lines[i].lstrip("#")

            with misc.raised_privileges():
                # Backup original file
                shutil.copy(self.antergos_mirrorlist, self.antergos_mirrorlist + ".cnchi_backup")
                # Write new one
                with open(self.antergos_mirrorlist, 'w') as mirrors:
                    mirrors.write("\n".join(lines) + "\n")

        # Run rankmirrors command
        try:
            with misc.raised_privileges():
                self.rankmirrors_pid = subprocess.Popen([self.reflector_script]).pid

        except subprocess.CalledProcessError as err:
            logging.error(_("Couldn't execute auto mirror selection"))

        # Check arch mirrorlist against mirror status data, remove any bad mirrors.
        if _use_requests and os.path.exists(self.arch_mirrorlist):
            # Use session to avoid silly warning
            # See https://github.com/kennethreitz/requests/issues/1882
            with requests.Session() as session:
                status = session.get(self.arch_mirror_status).json()
                mirrors = status['urls']

            with open(self.arch_mirrorlist) as arch_mirrors:
                lines = [x.strip() for x in arch_mirrors.readlines()]

            for i in range(len(lines)):
                server_uncommented = lines[i].startswith("Server")
                server_commented = lines[i].startswith("#Server")
                if server_commented or server_uncommented:
                    url = lines[i].split('=')[1].strip()
                    check = self.check_mirror_status(mirrors, url)
                    if not check and server_uncommented:
                        # Bad mirror, comment it
                        lines[i] = "#" + lines[i]
                    if check and server_commented:
                        # It's a good mirror, uncomment it
                        lines[i] = lines[i].lstrip("#")

            with misc.raised_privileges():
                # Backup original file
                shutil.copy(self.arch_mirrorlist, self.arch_mirrorlist + ".cnchi_backup")
                # Write new one
                with open(self.arch_mirrorlist, 'w') as arch_mirrors:
                    arch_mirrors.write("\n".join(lines) + "\n")

        logging.debug(_("Auto mirror selection has been run successfully"))
예제 #14
0
파일: i18n.py 프로젝트: prescott66/Cnchi
def get_languages(language_list="data/languagelist.data.gz",
                  current_language_index=-1,
                  only_installable=False):
    import gzip
    #import icu

    current_language = "English"

    if only_installable:
        from apt.cache import Cache
        #workaround for an issue where euid != uid and the
        #apt cache has not yet been loaded causing a SystemError
        #when libapt-pkg tries to load the Cache the first time.
        with misc.raised_privileges():
            cache = Cache()

    languagelist = gzip.open(language_list)
    language_display_map = {}
    i = 0
    for line in languagelist:
        line = utf8(line)
        if line == '' or line == '\n':
            continue
        code, name, trans = line.strip('\n').split(':')[1:]
        if code in ('C', 'dz', 'km'):
            i += 1
            continue
        # KDE fails to round-trip strings containing U+FEFF ZERO WIDTH
        # NO-BREAK SPACE, and we don't care about the NBSP anyway, so strip
        # it.
        #   https://bugs.launchpad.net/bugs/1001542
        #   (comment #5 and on)
        trans = trans.strip(" \ufeff")

        if only_installable:
            pkg_name = 'language-pack-%s' % code
            #special case these
            if pkg_name.endswith('_CN'):
                pkg_name = 'language-pack-zh-hans'
            elif pkg_name.endswith('_TW'):
                pkg_name = 'language-pack-zh-hant'
            elif pkg_name.endswith('_NO'):
                pkg_name = pkg_name.split('_NO')[0]
            elif pkg_name.endswith('_BR'):
                pkg_name = pkg_name.split('_BR')[0]
            try:
                pkg = cache[pkg_name]
                if not (pkg.installed or pkg.candidate):
                    i += 1
                    continue
            except KeyError:
                i += 1
                continue

        language_display_map[trans] = (name, code)
        if i == current_language_index:
            current_language = trans

        i += 1
    languagelist.close()

    if only_installable:
        del cache

    #try:
    # Note that we always collate with the 'C' locale.  This is far
    # from ideal.  But proper collation always requires a specific
    # language for its collation rules (languages frequently have
    # custom sorting).  This at least gives us common sorting rules,
    # like stripping accents.
    #collator = icu.Collator.createInstance(icu.Locale('C'))
    #except:
    #       collator = None

    collator = None

    def compare_choice(x):
        if language_display_map[x][1] == 'C':
            return None  # place C first
        if collator:
            try:
                return collator.getCollationKey(x).getByteArray()
            except:
                pass
        # Else sort by unicode code point, which isn't ideal either,
        # but also has the virtue of sorting like-glyphs together
        return x

    sorted_choices = sorted(language_display_map, key=compare_choice)

    return current_language, sorted_choices, language_display_map