Beispiel #1
0
    def warningPrompt(self):
        choice = QMessageBox.warning \
            (self, 'RESET EVERYTHING?',
             "Reset Everything? \n\n This will reset your " + self.os_info['DESCRIPTION'] + " installation to its "
                                                                                            "factory defaults. Local user accounts and home directories will also be removed."
                                                                                            "\n\nAre you sure you\'d like to continue?",
             QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            self.logger.warning("auto reset chosen")
            self.getInstalledList()
            self.getMissingPackages()
            if UsefulTools().lineCount('apps-to-remove') > 0:
                self.getLocalUserList()
                self.findNonDefaultUsers()
                view = AppView(self)
                tip = "These packages will be removed"
                view.showView("apps-to-remove", "Packages To Remove", tip, True)
                view.show()
                QApplication.restoreOverrideCursor()

            else:
                UsefulTools().showMessage("Nothing left to remove",
                                          "All removable packages have already been removed, there are no more packages left",
                                          QMessageBox.Information)
                QApplication.restoreOverrideCursor()

        else:
            self.logger.info("auto reset cancelled")
Beispiel #2
0
 def addPPA(self, ppa):
     button = QtGui.qApp.focusWidget()
     index = self.table.indexAt(button.pos())
     if index.isValid() and ppa[index.row()][1]:
         try:
             QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
             x = str(ppa[index.row()])
             y = str(x[7:]).split(' ', 1)[0]
             entry = ('deb', y, self.codeName(), ['main'])
             self.sources.add(*entry)
             self.sources.save()
             p = subprocess.check_output([
                 'apt-key', 'adv', '--keyserver', 'keyserver.ubuntu.com',
                 '--recv-keys', ppa[index.row()][2]
             ])
             print p
             QtGui.QApplication.restoreOverrideCursor()
         except Exception as e:
             QtGui.QApplication.restoreOverrideCursor()
             UsefulTools().showMessage("Unable to fetch PPA key",
                                       "Error: {}".format(e),
                                       QtGui.QMessageBox.Critical)
         else:
             UsefulTools().showMessage(
                 "PPA added",
                 "This ppa has been successfully added to your sources list",
                 QtGui.QMessageBox.Information)
     else:
         UsefulTools().showMessage(
             "PPA not compatible",
             "This PPA is not compatible with your system because it's "
             "not available for {}".format(self.os_info['DESCRIPTION']),
             QtGui.QMessageBox.Information)
Beispiel #3
0
 def showMissings(self):
     QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
     self.getMissingPackages()
     if UsefulTools().lineCount('apps-to-install') > 0:
         text = "These were pre-installed packages that are missing but due for install"
         view_missing = AppView(self)
         view_missing.showView("apps-to-install", "Missing pre-installed packages", text, False)
         view_missing.show()
         QApplication.restoreOverrideCursor()
     else:
         QApplication.restoreOverrideCursor()
         UsefulTools().showMessage('No missing pre-installed packages', "Nothing to Show :-)",
                                   QMessageBox.Information)
Beispiel #4
0
 def filesExist(self, manifest, userlist):
     if not os.path.isfile(manifest):
         self.manifest = None
         UsefulTools().showMessage(
             "File Not Found",
             "Manifest could not be found, please choose a manifest for your system if you have one",
             QMessageBox.Critical,
             "without a system manifest, this program won't function")
     if not os.path.isfile(userlist):
         self.userlist = None
         UsefulTools().showMessage("File Not Found",
                                   "UserList could not be found",
                                   QMessageBox.Warning,
                                   "It isn't a really big deal")
Beispiel #5
0
    def __init__(self):
        super(Settings, self).__init__()
        self.directory = '.resetter/data'
        self.os_info = lsb_release.get_distro_information()
        self.euid = os.geteuid()
        self.version = UsefulTools().getVersion()
        self.checkForUpdate()
        self.detectRoot()
        logdir = '/var/log/resetter'
        if not os.path.exists(logdir):
            os.makedirs(logdir)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.manifests = '/usr/lib/resetter/data/manifests'
        self.userlists = '/usr/lib/resetter/data/userlists'
        if 'PKEXEC_UID' in os.environ:
            self.user = pwd.getpwuid(int(os.environ['PKEXEC_UID'])).pw_name
            working_dir = '/home/{}'.format(self.user)
            os.chdir(working_dir)
        elif self.euid == 0 and 'PKEXEC_UID' not in os.environ:
            self.user = os.environ['SUDO_USER']
        self.createDirs()
        os.chdir(self.directory)

        self.manifest = ("manifests/{}").format(self.detectOS()[0])
        self.userlist = ("userlists/{}").format(self.detectOS()[1])
        self.window_title = self.detectOS()[2]
        self.filesExist(self.manifest, self.userlist)
Beispiel #6
0
 def showMessage(self):
     title = 'Password did not meet complexity requirements'
     text = ("Make sure that your password contains:\n"
                 "At least 8 characters\n"
                 "At least one number\n"
                 "At least one uppercase letter")
     UsefulTools().showMessage(title, text, QMessageBox.Warning)
Beispiel #7
0
 def checkForUpdate(self):
     splash_pix = QtGui.QPixmap(
         '/usr/lib/resetter/data/icons/resetter-logo.svg')
     splash = QSplashScreen(
         splash_pix,
         QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
     splash.setMask(splash_pix.mask())
     splash.show()
     start = time.time()
     while time.time() - start < 0.3:
         qApp.processEvents()
     try:
         page = urllib.request.urlopen(
             'https://github.com/gaining/resetter/tags')
         soup = BeautifulSoup(page, 'html.parser')
         found_version = re.search('v(\d+\.)?(\d+\.)?(\d+)',
                                   str(soup.select('h4'))).group()[1:]
         current_version = StrictVersion(self.version)
         valid = self.validateSiteVersion(found_version)
         if valid is not None and valid > current_version:
             splash.close()
             msg = ("There's a new version of Resetter available.\n\n"
                    "Grab Resetter v{} at "
                    "github.com/gaining/Resetter/releases/latest".format(
                        valid))
             UsefulTools().showMessage("Update Available", msg,
                                       QMessageBox.Information)
         else:
             if valid is not None:
                 print("Running most recent version of Resetter")
     except urllib.request.URLError:
         pass
Beispiel #8
0
 def __init__(self, parent=None):
     super(About, self).__init__(parent)
     self.resize(550, 350)
     self.setWindowTitle("About")
     pixmap = QtGui.QPixmap(
         "/usr/lib/resetter/data/icons/resetter-logo.png")
     pixmap2 = pixmap.scaled(300, 91)
     about_font = QtGui.QFont()
     about_font.setBold(True)
     about_label = QtGui.QLabel(self)
     desc_label = QtGui.QLabel(self)
     desc_label.setAlignment(QtCore.Qt.AlignCenter)
     desc_label.setWordWrap(True)
     cr_label = QtGui.QLabel(self)
     cr_label.setAlignment(QtCore.Qt.AlignCenter)
     donate_label = QtGui.QLabel(self)
     donate_label.setAlignment(QtCore.Qt.AlignCenter)
     donate_label.setWordWrap(True)
     more_label = QtGui.QLabel(self)
     more_label.setAlignment(QtCore.Qt.AlignCenter)
     more_label.setWordWrap(True)
     donate_label.setToolTip("Right click to copy link")
     more_label.setToolTip("Right Click to copy link")
     version_label = QtGui.QLabel(self)
     version_label.setAlignment(QtCore.Qt.AlignCenter)
     about_label.setAlignment(QtCore.Qt.AlignCenter)
     cr_text = u"© 2018 Jonathan Soivilus"
     desc_text = "Built With PyQt\n\n " \
                 "This is a great utility software that will help you reset your linux installation its stock state" \
                 " among other things.".decode()
     version = UsefulTools().getVersion()
     version_text = "Version: {}-stable".format(version)
     donate_text = 'If you liked my project, please ' \
                   '<a href="https://github.com/gaining/Resetter/blob/master/DONATE.md">Donate </a>'
     more_text = 'To find out more about this project, please visit my github:' \
                 ' <a href="https://github.com/gaining/resetter"> Resetter</a>'
     about_label.setPixmap(pixmap2)
     desc_label.setText(desc_text)
     cr_label.setText(cr_text)
     donate_label.setText(donate_text)
     more_label.setText(more_text)
     version_label.setText(version_text)
     self.close_button = QtGui.QPushButton(self)
     self.close_button.setText("Close")
     self.close_button.setMaximumSize(QtCore.QSize(100, 30))
     self.close_button.clicked.connect(self.close)
     self.liscence_button = QtGui.QPushButton(self)
     self.liscence_button.setText("License")
     self.liscence_button.clicked.connect(self.showLicence)
     self.verticalLayout = QtGui.QVBoxLayout(self)
     self.verticalLayout.addWidget(about_label)
     self.verticalLayout.addWidget(desc_label)
     self.verticalLayout.addWidget(donate_label)
     self.verticalLayout.addWidget(more_label)
     self.verticalLayout.addWidget(version_label)
     self.verticalLayout.addWidget(cr_label)
     self.verticalLayout.addWidget(self.close_button, 0,
                                   QtCore.Qt.AlignRight)
     self.verticalLayout.addWidget(self.liscence_button, 0,
                                   QtCore.Qt.AlignRight)
Beispiel #9
0
    def editSources(self, title, tip):
        self.setWindowTitle(title)
        list_view = QListView(self)
        self.model = QtGui.QStandardItemModel(list_view)
        self.model.itemChanged.connect(self.setItems)
        self.setToolTip(tip)
        verticalLayout = QVBoxLayout(self)
        verticalLayout.addWidget(self.searchEditText)
        verticalLayout.addWidget(list_view)
        horizontalLayout = QHBoxLayout()
        horizontalLayout.setAlignment(QtCore.Qt.AlignRight)
        horizontalLayout.addWidget(self.label)
        horizontalLayout.addWidget(self.btDisable)
        horizontalLayout.addWidget(self.btnEnable)
        horizontalLayout.addWidget(self.btnRemove)
        horizontalLayout.addWidget(self.btnClose)
        verticalLayout.addLayout(horizontalLayout)
        mode = 0
        args = (self.model, list_view,  self.label, self.font, self.font2, mode)
        self.searchEditText.textChanged.connect(lambda: UsefulTools().searchItem(*args, self.searchEditText.text()))

        for dirpath, dirs, files in os.walk('/etc/apt/'):
            word = 'deb'
            for filename in fnmatch.filter(files, "*.list"):
                source_list = os.path.join(dirpath, filename)
                self.sourceslists.append(source_list)
                with open(source_list, "r") as sources:
                    for line in sources:
                        if line.startswith(word) or line.startswith('#') \
                                and line[2:].split(' ')[0][:3] == word:
                                item = QtGui.QStandardItem(line.strip())
                                item.setCheckable(True)
                                item.setCheckState(QtCore.Qt.Unchecked)
                                self.model.appendRow(item)
                    list_view.setModel(self.model)
Beispiel #10
0
    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error(
                "fixBroken() finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))

            choice_err = QMessageBox.warning \
                (self, "Problems encountered while attempting to clean up. ",
                       "Please run: <strong>sudo bash /usr/lib/resetter/data/scripts/fix-broken.sh</strong> on a terminal. "
                       "Once the task is completed, choose 'Yes' to continue.", QMessageBox.Yes | QMessageBox.No)
            if choice_err == QMessageBox.Yes:
                self.progress2.setRange(0, 1)
                self.progress2.setValue(1)
                self.labels[(3, 1)].setPixmap(self.pixmap2)
                self.unsetCursor()
                self.lbl1.setText("Done Cleanup")
                self.installPackages()
            else:
                UsefulTools().showMessage("Canceled",
                                          "You have chosen to abort",
                                          QMessageBox.Warning)
                QApplication.restoreOverrideCursor()
                self.finished()
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug(
                "Cleanup finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()
Beispiel #11
0
 def detectRoot(self):  # root detection function
     if self.euid != 0:
         print("Need to be root to run this program")
         UsefulTools().showMessage(
             "Permission Error", "You need to be root to run this program",
             QMessageBox.Warning,
             "You won't be able to run this program unless you're root, try running 'sudo resetter' from the terminal"
         )
         exit(1)
Beispiel #12
0
 def getInstalledList(self):
     try:
         self.logger.info("getting installed list...")
         p1 = subprocess.Popen(['dpkg', '--get-selections'], stdout=subprocess.PIPE, bufsize=1)
         result = p1.stdout
         with open("installed", "w") as output:
             for i, line in enumerate(result):
                 output.write(line.decode().split('\t', 1)[0] + '\n')
         self.logger.debug("installed list was generated with {} apps installed".format(i))
     except subprocess.CalledProcessError as e:
         self.logger.error("Error: {}".format(e.ouput), exc_info=True)
         UsefulTools().showMessage("Error", "Installed list failed to generate or may not be complete: {}".format(e),
                                   QMessageBox.Critical)
Beispiel #13
0
 def toggleSwitch(self):
     if self.switch is False:
         self.switch = True
         if self.count == 0:  # show warning message only once
             text = (
                 "Only use this option for single packages for which you're curious about. "
                 "<strong>Do not use the <i>Select All</i> option while this is checked</strong>"
             )
             UsefulTools().showMessage("warning", text,
                                       QtGui.QMessageBox.Warning)
         self.count += 1
     else:
         self.switch = False
Beispiel #14
0
 def showUserInfo(self):
     if not self.no_show:
         msg = "Please use these credentials the next time you log-in\n\n"
         msginf = ("USERNAME: <b>{}</b><br/> PASSWORD: <b>{}</b>".format(
             self.account.getUser(), self.account.getPassword()))
         msgd = ("If you deleted your old user account, "
                 "this account will be the only local user on your system")
         UsefulTools().showMessage("User Credentials", msg + msginf,
                                   QtGui.QMessageBox.Information, msgd)
         self.logger.info("Credential message info shown")
         self.rebootMessage()
     else:
         self.rebootMessage()
Beispiel #15
0
    def getOldKernels(self):
        try:
            self.logger.info("getting old kernels...")

            cmd = subprocess.check_output(['bash', '/usr/lib/resetter/data/scripts/remove-old-kernels.sh'])
            results = cmd.decode().splitlines(True)
            with open("Kernels", "w") as kernels:
                for line in results:
                    kernels.writelines(line)
            self.logger.info("getOldKernels() completed")
        except subprocess.CalledProcessError as e:
            self.logger.error("Error: {}".format(e.output))
            UsefulTools().showMessage("Error", "Error: {}".format(e.ouput), QMessageBox.Critical)
Beispiel #16
0
 def processManifest(self):
     try:
         self.logger.info("processing updated manifest...")
         with open(self.manifest) as f, open('processed-manifest', 'w') as output:
             for line in f:
                 line = line.split('\t', 1)[0]
                 if line.endswith('\n'):
                     line = line.strip()
                 output.write(line + '\n')
         self.logger.info("manifest processing complete")
         self.compareFiles()
     except Exception as e:
         self.logger.error("Manifest processing failed [{}]".format(e))
         UsefulTools().showMessage("Manifest Processing failed", e, QMessageBox.Critical)
Beispiel #17
0
 def showNonDefaultUsers(self):
     QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
     self.getLocalUserList()
     self.findNonDefaultUsers()
     if len(self.non_defaults) > 0:
         ndu = AppView(self)
         text = "These are non default users"
         ndu.showView(self.non_defaults, 'Non-default users and groups list', text, False)
         ndu.show()
         QApplication.restoreOverrideCursor()
     else:
         QApplication.restoreOverrideCursor()
         UsefulTools().showMessage("No non-default users or groups on your system found", "Nothing to show :-)",
                                   QMessageBox.Information)
Beispiel #18
0
 def getMissingPackages(self):
     self.getInstalledList()
     self.processManifest()
     try:
         black_list = ('linux-image', 'linux-headers', 'linux-generic', 'linux-kernel-generic',
                        'openjdk-7-jre', 'grub', 'linux-modules')
         with open("apps-to-install", "w") as output, open("installed", "r") as installed, \
                 open(self.manifest, "r") as man:
             diff = set(man).difference(installed)
             for line in diff:
                 if not any(s in line for s in black_list):
                     output.writelines(line)
     except Exception as e:
         UsefulTools().showMessage('Error', "Error generating removable package list. Please see details",
                                   QMessageBox.Information, "Error: {}".format(e))
Beispiel #19
0
 def showMessage(self, package):
     self.comboBox.clear()
     self.comboBox.addItem("Did you mean?")
     i = 0
     for p in self.cache:
         if p.shortname.startswith(package) and len(package) > 0 and i < 12:
             i += 1
             self.comboBox.addItem(p.shortname)
     if self.comboBox.count() > 1:
         self.comboBox.setVisible(True)
     msg = "The package that you've tried to add is not found in the cache"
     msgd = "If you've recently added a ppa containing this package, "\
                         "please use [EasyPPA - refresh sources] feature, "\
                         "then try adding the package again."
     UsefulTools().showMessage("Package not found", msg,
                               QMessageBox.Information, msgd)
Beispiel #20
0
 def compareFiles(self):
     try:
         black_list = (['linux-image', 'linux-headers', 'linux-generic', 'ca-certificates', 'pyqt4-dev-tools',
                        'python-apt', 'python-aptdaemon', 'python-qt4', 'python-qt4-doc', 'libqt',
                        'pyqt4-dev-tools', 'openjdk', 'python-sip', 'gksu', 'grub', 'linux-modules',
                        'python-bs4'])
         with open("apps-to-remove", "w") as output, open("installed", "r") as installed, \
                 open(self.manifest, "r") as pman:
             diff = set(installed).difference(pman)
             for line in diff:
                 if not any(s in line for s in black_list):
                     output.writelines(line)
     except Exception as e:
         self.logger.error("Error comparing files [{}]".format(e), exc_info=True)
         UsefulTools().showMessage("Error", "Error generating removable package list. Please see details",
                                   QMessageBox.Critical, detail=e)
Beispiel #21
0
 def detectOS(self):
     apt_locations = ('/usr/bin/apt', '/usr/lib/apt', '/etc/apt',
                      '/usr/local/bin/apt')
     if any(os.path.exists(f) for f in apt_locations):
         manifest = self.os_info['ID'] + self.os_info[
             'RELEASE'] + '.manifest'
         userlist = self.os_info['ID'] + self.os_info[
             'RELEASE'] + '-default-userlist'
         window_title = self.os_info['ID'] + ' Resetter'
         return manifest, userlist, window_title
     else:
         UsefulTools().showMessage(
             "APT Not Found",
             "APT could not be found, your distro does not appear to be Debian based.",
             QtGui.QMessageBox.Warning)
         exit(1)
Beispiel #22
0
 def run(self):
     lc = UsefulTools().lineCount(self.file_in)
     if lc > 0:
         loading = 0
         x = float(100) / lc
         with open(self.file_in) as packages:
             for pkg_name in packages:
                 try:
                     loading += x
                     self.pkg = self.cache[pkg_name.strip()]
                     if not self.install:
                         self.pkg.mark_delete(True, True)
                         print "{} will be removed".format(self.pkg)
                     else:
                         self.pkg.mark_install()
                         print "{} will be installed ".format(
                             self.pkg.shortname)
                     self.emit(
                         QtCore.SIGNAL('updateProgressBar(int, bool)'),
                         loading, self.isDone)
                 except (KeyError, SystemError) as error:
                     # if resolver cannot find a way to cleanly install packages, move it to the broken list
                     if self.pkg.is_inst_broken:
                         self.broken_list.append(self.pkg.fullname)
                         self.logger.critical("{}".format(error),
                                              exc_info=True)
                         continue
                     else:
                         text = "Error loading apps"
                         error2 = "Problems trying to install: {}\n{}".format(
                             self.pkg.fullname, error.message)
                         self.logger.critical("{} {}".format(error,
                                                             error2,
                                                             exc_info=True))
                         self.emit(
                             QtCore.SIGNAL('showError(QString, QString)'),
                             error2, text)
                         break
             self.thread1.start()
             self.thread2.start()
             self.installPackages()
             self.end_of_threads.emit()
     else:
         print "All removable packages are already removed"
         self.emit(QtCore.SIGNAL('updateProgressBar(int, bool)'), 100, True)
Beispiel #23
0
 def detectOS(self):
     apt_locations = ('/usr/bin/apt', '/usr/lib/apt', '/etc/apt',
                      '/usr/local/bin/apt')
     if any(os.path.exists(f) for f in apt_locations):
         manifest = '_'.join((self.os_info['ID'], self.os_info['RELEASE'],
                              self.desktop_environment,
                              platform.architecture()[0], '.manifest'))
         userlist = '_'.join((self.os_info['ID'], self.os_info['RELEASE'],
                              'default-userlist', self.desktop_environment,
                              platform.architecture()[0]))
         window_title = self.os_info['ID'] + ' Resetter'
         return manifest, userlist, window_title
     else:
         UsefulTools().showMessage(
             "APT Not Found",
             "APT could not be found, your distro does not appear to be Debian based.",
             QtGui.QMessageBox.Warning)
         exit(1)
Beispiel #24
0
 def checkForUpdate(self):
     try:
         page = urllib2.urlopen('https://github.com/gaining/Resetter/tags')
         soup = BeautifulSoup(page, 'html.parser')
         versions = soup.find('span', attrs={'class': 'tag-name'})
         versions_tag = str(versions).strip()
         site_version = versions_tag[24:].split('-', 1)[0]
         current_version = StrictVersion(self.version)
         if site_version > current_version:
             msg = ("There's a new version of Resetter available.\n\n"
                    "Grab Resetter v{} at "
                    "github.com/gaining/Resetter/releases/latest".format(
                        site_version))
             UsefulTools().showMessage("Update Available", msg,
                                       QtGui.QMessageBox.Information)
         else:
             print("Running most recent version of Resetter")
     except urllib2.URLError:
         pass
Beispiel #25
0
        self.getLocalUserList()
        self.getOldKernels()
        self.findNonDefaultUsers()
        custom_reset = AppWizard(self)
        custom_reset.show()
        QApplication.restoreOverrideCursor()

    def easyInstall(self):
        self.easy = EasyInstaller()
        self.easy.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = UiMainWindow()
    resetter_inst = 0
    for p in psutil.process_iter():
        if "resetter" in p.name():
            resetter_inst += 1
            if resetter_inst > 1:
                message = '{} is already running'.format(p.name())
                print(message)
                UsefulTools().showMessage('Already running', message, QMessageBox.Information)
                sys.exit(1)
    window.show()
    sys.exit(app.exec_())




Beispiel #26
0
    def showView(self,
                 data,
                 title,
                 tip,
                 start,
                 width=None,
                 height=None,
                 check_state=None):
        self.setWindowTitle(title)
        self.setToolTip(tip)
        self.cache = apt.Cache()
        self.resize(400, 400)
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(QtCore.Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                     | QDialogButtonBox.Ok)
        list_view = QListView(self)
        verticalLayout = QVBoxLayout(self)
        verticalLayout.addWidget(self.searchEditText)
        verticalLayout.addWidget(list_view)
        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.label)
        horizontalLayout.addWidget(buttonBox)
        verticalLayout.addLayout(horizontalLayout)
        if start:
            buttonBox.accepted.connect(self.startRemoval)
        else:
            buttonBox.accepted.connect(self.closeview)
        buttonBox.rejected.connect(self.closeview)
        model = QtGui.QStandardItemModel(list_view)
        mode = 1
        args = (model, list_view, self.label, self.font, self.font2, mode)
        self.searchEditText.textChanged.connect(lambda: UsefulTools(
        ).searchItem(*args, self.searchEditText.text()))
        self.file_in = data

        if type(data) is str:
            with open(data) as f:
                for line in f:
                    try:
                        pkg = self.cache[line.strip()]
                        text = pkg.versions[0].description
                        item = QtGui.QStandardItem(line.strip())
                        item.setCheckState(QtCore.Qt.Checked)
                        item.setToolTip((textwrap.fill(text, 70)))
                    except KeyError:
                        continue
                    model.appendRow(item)
                list_view.setModel(model)
                list_view.show()

        elif type(data) is list:
            if width and height is not None:
                self.resize(width, height)
            for x in data:
                x = (str(x))
                item = QtGui.QStandardItem(x)
                item.setCheckable(False)
                if check_state:
                    item.setCheckState(QtCore.Qt.Checked)
                else:
                    item.setCheckState(QtCore.Qt.Unchecked)
                model.appendRow(item)
            list_view.setModel(model)
            list_view.show()

        else:
            word = 'deb'
            for x in data:
                m = (str(x))
                if m.startswith(word) or m.startswith('#') \
                        and m[2:].split(' ')[0][:3] == word:
                    item = QtGui.QStandardItem(m)
                    item.setCheckable(False)
                    item.setEditable(False)
                    item.setCheckState(QtCore.Qt.Checked)
                    model.appendRow(item)
            list_view.setModel(model)
            list_view.show()
Beispiel #27
0
 def showError(self, error, m_type):
     self.movie.stop()
     UsefulTools().showMessage(
         m_type, "Something went wront, please check details.",
         QtGui.QMessageBox.Critical, error)
Beispiel #28
0
    def __init__(self, parent=None):
        super(UiMainWindow, self).__init__(parent)
        self.d_env = Settings()
        self.setWindowIcon(QtGui.QIcon('/usr/lib/resetter/data/icons/resetter-launcher.png'))
        self.setWindowTitle(self.d_env.window_title)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.resize(850, 685)
        palette = QtGui.QPalette()
        self.setPalette(palette)
        self.menubar = self.menuBar()
        self.menuFile = QMenu(self.menubar)
        self.menuView = QMenu(self.menubar)
        self.menuTools = QMenu(self.menubar)
        self.menuHelp = QMenu(self.menubar)
        self.actionOpen = QAction(self)
        self.actionOpenUserList = QAction(self)
        self.actionUpdateManifests = QAction(self)
        self.actionUpdateUserlists = QAction(self)

        self.actionSaveSnapshot = QAction(self)
        self.actionSaveSnapshot.setStatusTip('Save a snapshot of currently installed packages. '
                                             'It is best to save this file in a removable drive for later use.')
        self.actionOpen.triggered.connect(self.openManifest)
        self.actionOpenUserList.triggered.connect(self.openUserList)

        self.actionSaveSnapshot.triggered.connect(self.save)
        self.actionSaveSnapshot.setShortcut('Ctrl+S')

        self.actionExit = QAction(self)
        self.actionExit.setShortcut('Ctrl+Q')
        self.actionExit.setStatusTip('Exit application')
        self.actionExit.triggered.connect(qApp.quit)
        self.actionAbout = QAction(self)
        self.actionAbout.triggered.connect(self.about)
        self.actionEasyPPA = QAction(self)
        self.actionEasyPPA.triggered.connect(self.searchLaunchpad)
        self.actionEasyPPA.setStatusTip("The easiest way to get and install PPAs right from launchpad.net.")
        self.actionShow_Installed = QAction(self)
        self.actionShow_Installed.setStatusTip('Show list of installed packages')
        self.actionShow_Installed.triggered.connect(self.showInstalled)
        self.actionShow_missing = QAction(self)
        self.actionShow_missing.setStatusTip('Show removed packages from initial install')
        self.actionShow_missing.triggered.connect(self.showMissings)
        self.actionEditSources = QAction(self)
        self.actionEditSources.setStatusTip('Edit your sources list')
        self.actionEditSources.triggered.connect(self.editSourcesList)
        self.actionShowUsers = QAction(self)
        self.actionShowUsers.setStatusTip('View non-default system users')
        self.actionShowUsers.triggered.connect(self.showNonDefaultUsers)
        self.actionUpdateManifests.triggered.connect(lambda: UsefulTools().updateFiles('manifests'))
        self.actionUpdateUserlists.triggered.connect(lambda: UsefulTools().updateFiles('userlists'))

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionOpenUserList)

        self.menuFile.addAction(self.actionSaveSnapshot)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)
        self.menuView.addAction(self.actionShow_missing)
        self.menuView.addAction(self.actionShow_Installed)
        self.menuView.addAction(self.actionShowUsers)
        self.menuTools.addAction(self.actionEasyPPA)
        self.menuTools.addAction(self.actionEditSources)
        self.menuHelp.addAction(self.actionUpdateManifests)
        self.menuHelp.addAction(self.actionUpdateUserlists)

        self.menuHelp.addAction(self.actionAbout)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuView.menuAction())
        self.menubar.addAction(self.menuTools.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
        self.menuFile.setTitle("File")
        self.menuView.setTitle("View")
        self.menuTools.setTitle("Tools")
        self.menuHelp.setTitle("Help")
        self.actionExit.setText("Exit")
        self.actionOpen.setText("Open manifest")
        self.actionOpenUserList.setText("Open default userlist")

        self.actionSaveSnapshot.setText('Save')
        self.actionAbout.setText("About")
        self.actionEasyPPA.setText("Easy PPA")
        self.actionShow_missing.setText("Show missing pre-installed packages")
        self.actionEditSources.setText("Edit Sources")
        self.actionShowUsers.setText("Show non-default system users and groups")
        self.actionShow_Installed.setText("Show installed list")
        self.actionUpdateManifests.setText("Update manifest files")
        self.actionUpdateUserlists.setText("Update userlist files")

        font = QtGui.QFont()
        font.setPointSize(25)
        button_style = ("""
        QPushButton {
        border: 2px solid #555;
        border-radius: 30px;
        padding: 5px;
        background: qradialgradient(cx: 0.5, cy: -0.6,
        fx: -0.5, fy: 0.6,
        radius: 1.35, stop: 0 #fff, stop: 1 #888);
        }

        QPushButton:hover {
        background: qradialgradient(cx: 0.5, cy: 0.3,
        fx: 0.5, fy: 0.3,
        radius: 1.35, stop: 0 #fff, stop: 1 #888);
        min-width: 80px;
        }

        QPushButton:pressed {
        background: qradialgradient(cx: 0.7, cy: -0.7,
        fx: 0.7, fy: -0.7,
        radius: 1.35, stop: 0 #fff, stop: 1 #888);
        }""")
        self.btnReset = QPushButton()
        self.btnReset.setText("Automatic Reset", )
        self.btnReset.setFixedHeight(100)

        self.btnReset.setFont(font)
        self.btnReset.setStyleSheet(button_style)
        self.btnReset.setIcon(QtGui.QIcon('/usr/lib/resetter/data/icons/auto-reset-icon.png'))
        auto_text = "By choosing this option, resetter will automatically choose which packages to remove. " \
                    "Your home directory and user account will also be removed. Choose the custom reset option if you'd" \
                    " like to keep your user account and select which packages to remove. "
        self.btnReset.setToolTip(textwrap.fill(auto_text, 70))
        self.btnReset.setIconSize(QtCore.QSize(80, 80))
        self.btnReset.clicked.connect(self.warningPrompt)
        self.btnCustomReset = QPushButton()
        self.btnCustomReset.setText("Custom Reset")
        self.btnCustomReset.setFixedHeight(100)
        self.btnCustomReset.setFont(font)
        self.btnCustomReset.setStyleSheet(button_style)
        self.btnCustomReset.clicked.connect(self.customReset)
        self.btnCustomReset.setIcon(QtGui.QIcon('/usr/lib/resetter/data/icons/custom-reset-icon.png'))
        self.btnCustomReset.setIconSize(QtCore.QSize(80, 80))
        custom_text = "Choose this option if you would like to control how your system gets reset"
        self.btnCustomReset.setToolTip(textwrap.fill(custom_text, 70))

        self.btnEasyInstall = QPushButton(self)
        self.btnEasyInstall.setText("Easy Install")
        self.btnEasyInstall.setFixedHeight(100)
        self.btnEasyInstall.setFont(font)
        self.btnEasyInstall.setStyleSheet(button_style)
        self.btnEasyInstall.clicked.connect(self.easyInstall)
        self.btnEasyInstall.setIcon(QtGui.QIcon('/usr/lib/resetter/data/icons/easy-install-icon.png'))
        self.btnEasyInstall.setIconSize(QtCore.QSize(60, 60))
        custom_text = "Choose this option if you would like to control how your system gets reset."
        self.btnCustomReset.setToolTip(textwrap.fill(custom_text, 70))
        self.centralWidget = QWidget()
        self.os_version_label = QLabel()
        self.os_name_label = QLabel()
        self.app_version = QLabel()
        self.os_codename_label = QLabel()
        self.os_d_env_label = QLabel()
        self.os_info = self.d_env.os_info
        self.manifest_label = QLabel()
        self.userlist_label = QLabel()
        dse = QGraphicsDropShadowEffect()
        dse.setBlurRadius(4)
        self.manifest = self.d_env.manifest
        self.userlist = self.d_env.userlist
        self.user = self.d_env.user
        self.desktop = self.d_env.desktop_environment
        self.app_version.setText('version: {}'.format(UsefulTools().getVersion()))
        self.os_name_label.setText('OS Name: ' + self.os_info['ID'])
        self.os_version_label.setText('OS version: ' + self.os_info['RELEASE'])
        self.os_name_label.setGraphicsEffect(dse)
        self.os_codename_label.setText('codename: ' + self.os_info['CODENAME'])
        self.non_defaults = []
        self.image_label = QLabel()
        if self.manifest is not None:
            self.manifest_label.setText("Manifest: {}".format(self.manifest.split('/')[-1]))
        else:
            self.manifest_label.setText("Manifest: ???")

        if self.userlist is not None:
            self.userlist_label.setText("Userlist: {}".format(self.userlist.split('/')[-1]))
        else:
            self.userlist_label.setText("Userlist: ???")

        if self.desktop is not None:
            self.os_d_env_label.setText("Desktop Environment: {}".format(self.desktop.split('/')[-1]))
        else:
            self.userlist_label.setText("Desktop Environment: ???")

        logo = QtSvg.QSvgWidget('/usr/lib/resetter/data/icons/resetter-logo.svg')

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.addWidget(logo)
        self.verticalLayout2.addWidget(self.os_name_label)
        self.verticalLayout2.addWidget(self.os_version_label)
        self.verticalLayout2.addWidget(self.os_codename_label)
        self.verticalLayout2.addWidget(self.os_d_env_label)
        self.verticalLayout2.addWidget(self.manifest_label)
        self.verticalLayout2.addWidget(self.userlist_label)
        self.verticalLayout2.addWidget(self.app_version)

        self.verticalLayout2.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.addWidget(self.image_label)
        self.verticalLayout.addLayout(self.verticalLayout2)
        self.verticalLayout.addWidget(self.btnEasyInstall)
        self.verticalLayout.addWidget(self.btnReset)
        self.verticalLayout.addWidget(self.btnCustomReset)
        self.centralWidget.setLayout(self.verticalLayout)
        self.setCentralWidget(self.centralWidget)
Beispiel #29
0
 def alreadyInstalled(self, package):
     UsefulTools().showMessage(
         "Package already installed ",
         "{} is already on your system".format(package),
         QMessageBox.Information)