예제 #1
0
    def shown(self):
        self.timer.start(1000)

        if ctx.flags.install_type == ctx.STEP_BASE:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.setWidgetDateTime(self.ui.countryList.currentIndex())
예제 #2
0
    def __init__(self, parent=None):
        #super(MainWidget,self).__init__()
        QWidget.__init__(self, parent)  # burada bir hata var

        self.setupUi(self)
        self.parent = parent

        self._selectedGroups = []
        self._preexceptions = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False

        # Search Thread
        self._searchThread = PThread(self, self.startSearch,
                                     self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon(("edit-find", "find")))
        self.initializeUpdateTypeList()

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)

        #burada hata alabilirim
        self.packageList.model().dataChanged[QModelIndex, QModelIndex].connect(
            self.statusChanged)

        self.packageList.updateRequested.connect(self.initialize)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(
            FINISHED, lambda: self.parent.statusBar().setVisible(
                not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(
            OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)
예제 #3
0
    def __init__(self, state, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)
        self.state = state
        # PDS Settings
        self._animation = 1
        self._duration = 400
        self.enableOverlay()
        self._disable_parent_in_shown = True
        self.webView.hide()
      
        #Url list for package pisi source files
        global packageUrlList
        packageUrlList = []
        
        self._as = 'http://youtube.googleapis.com/v'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("dialog-close"))

        self.packageHomepage.clicked.connect(self.openWebsite)
        self.packagePisiSource.clicked.connect(self.openPisiSource)
        #self.wdInstallButton.clicked.connect(self.showBasket)
        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.webView.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.showFullImage)

        self.tabWidget.removeTab(0)

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.filterLine.setListWidget(self.filesList)
        self.noconnection.hide()
        self.parent = parent
예제 #4
0
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)

        self.setupUi(self)
        self.parent = parent

        self._selectedGroups = []
        self._preexceptions  = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False

        #set style
        self._style = "/usr/share/kde4/apps/package-manager/data/style.qss"
        self.setStyleSheet(file(self._style).read())

        # Search Thread
        self._searchThread = PThread(self, self.startSearch, self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon("edit-find"))
        self.initializeUpdateTypeList()

        self.morewidgets = MoreWidgets(self.state, self.parent)
        self._postexceptions.append(lambda: self.morewidgets.setActionEnabled(True))
        self.morewidgets._show()

        self.webdialog = WebDialog(self.state, self.parent)

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)

        self.connect(self.packageList.model(), SIGNAL("dataChanged(QModelIndex,QModelIndex)"), self.statusChanged)
        self.connect(self.packageList, SIGNAL("updateRequested()"), self.initialize)
        self.connect(self.morewidgets.randomPackageList, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.showWebdialog)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(FINISHED, lambda: self.parent.statusBar().setVisible(not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)
예제 #5
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type == ctx.STEP_DEFAULT:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.ui.pass1.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.returnPressed.connect(self.slotReturnPressed)
        self.ui.hostname.textChanged[str].connect(self.slotHostnameChanged)
예제 #6
0
    def __init__(self, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)

        self.iface = parent.iface

        # PDS Settings
        self._animation = 1
        self._duration = 1
        self.enableOverlay()
        self.setOverlayOpacity(150)
        self._disable_parent_in_shown = True

        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(
            FINISHED,
            lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://appinfo.pisilinux.org'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("cancel"))

        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAlwaysOff)

        self.webView.page().setLinkDelegationPolicy(
            QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.showFullImage)

        self.tabWidget.removeTab(0)

        self.busy = QProgressIndicator(self, "white")
        self.busy.setMaximumSize(QSize(48, 48))
        self.webLayout.addWidget(self.busy)
        self.busy.hide()

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.noconnection.hide()
        self.parent = parent
예제 #7
0
    def __init__(self, parent = None):
        super(MainWidget, self).__init__(parent)
        
        self.setupUi(self)
        self.parent = parent
        
        self._selectedGroups = []
        self._preexceptions  = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False
        
        
        # Search Thread
        self._searchThread = PThread(self, self.startSearch, self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon(("edit-find", "find")))
        self.initializeUpdateTypeList()

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)
        
        
        
        self.packageList.dataChanged[QModelIndex,QModelIndex].connect(self.statusChanged)
        
        self.packageList.updateRequested.connect(self.initialize)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(FINISHED, lambda: self.parent.statusBar().setVisible(not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)
예제 #8
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type in [ctx.STEP_DEFAULT, ctx.STEP_LIVE]:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.connect(self.ui.pass1, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("returnPressed()"),
                     self.slotReturnPressed)
        self.connect(self.ui.hostname, SIGNAL("textChanged(const QString &)"),
                     self.slotHostnameChanged)
예제 #9
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type == ctx.STEP_DEFAULT:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.ui.pass1.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.returnPressed.connect(self.slotReturnPressed)
        self.ui.hostname.textChanged[str].connect(self.slotHostnameChanged)
예제 #10
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type in [ctx.STEP_DEFAULT, ctx.STEP_LIVE]:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.connect(self.ui.pass1, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("returnPressed()"),
                     self.slotReturnPressed)
        self.connect(self.ui.hostname, SIGNAL("textChanged(const QString &)"),
                     self.slotHostnameChanged)
예제 #11
0
    def __init__(self, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)

        self.iface = parent.iface

        # PDS Settings
        self._animation = 1
        self._duration = 400
        self.enableOverlay()
        self._disable_parent_in_shown = True

        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(FINISHED, lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://onurguzel.com/appinfo'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("dialog-close"))

        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)

        self.webView.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.redirectLinks)

        self.tabWidget.removeTab(0)

        self.busy = QProgressIndicator(self, "white")
        self.busy.setMaximumSize(QSize(48, 48))
        self.webLayout.addWidget(self.busy)
        self.busy.hide()

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.filterLine.setListWidget(self.filesList)
        self.noconnection.hide()
        self.parent = parent
예제 #12
0
    def __init__(self, parent=None, step=1):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.logger = SimpleLogger()
        self.log = self.logger.log

        self.target_repo = REPO_TEMPLATE % 'stable'
        self.iface = Iface(self)

        self.connect(self.iface, SIGNAL("notify(PyQt_PyObject)"),
                     self.showMessage)

        self.msgbox = PMessageBox(self)
        self.msgbox.setStyleSheet("color:white;")
        self.msgbox.enableOverlay()
        # Just for Fun :)
        self.pageWidget = QPageWidget(
            self.widget_screens)  # , direction = 'ttb')
        self.layout.addWidget(self.pageWidget)

        self.button_next.clicked.connect(self.pageWidget.next)
        self.button_previous.clicked.connect(self.pageWidget.prev)
        self.button_cancel.clicked.connect(self.reject)

        # Threads
        self.thread_step_1 = PThread(self, self.step_1_start, self.step_1_end)
        self.thread_step_2 = PThread(self, self.step_2_start, self.step_2_end)
        self.thread_step_3 = PThread(self, self.step_3_start, self.step_3_end)

        # Update Page Title
        self.connect(self.pageWidget, SIGNAL("currentChanged()"), lambda:\
                     self.label_header.setText(self.pageWidget.getCurrentWidget().title))

        self.current_step = step

        if step == 1:
            self.thread_check = PThread(self, self.findMissingPackages,
                                        self.showResults)

            # Welcome
            self.pageWidget.createPage(
                getWidget(ui_screen_1, _("Welcome to Upgrade Manager...")))

            # Repo Selection
            self.pageWidget.createPage(
                getWidget(ui_screen_2, _("Select Upgrade Repository...")))

            # Check Results Page
            self.pageWidget.createPage(getWidget(ui_screen_3,
                                                 _("Checking your system...")),
                                       inMethod=self.checkSystem,
                                       outMethod=self.hideMessage)

            resultWidget = self.pageWidget.getWidget(2).ui
            resultWidget.widget.hide()

            def updateButtons():
                if self.button_next.text() == _("Next"):
                    self.button_next.setText(_("Yes, Upgrade"))
                    self.button_previous.setText(_("Cancel"))
                    self.button_cancel.hide()
                else:
                    self.button_next.setText(_("Next"))
                    self.button_previous.setText(_("Previous"))
                    self.button_cancel.show()

            # Last Question
            self.pageWidget.createPage(getWidget(ui_screen_4, ""),
                                       inMethod=updateButtons,
                                       outMethod=updateButtons)
        self._step_counter = 0

        # Progress Screen
        self.pageWidget.createPage(getWidget(ui_screen_5,
                                             _("Upgrading the system...")),
                                   inMethod=self.upgradeStep_1)

        # Shortcut for Progress Screen UI
        # Get the last added page as progress page
        # After the first step completed, um will use just this page !
        self.ps = self.pageWidget.getWidget(self.pageWidget.count() - 1).ui

        # Busy indicator to Progress Screen
        self.ps.busy = QProgressIndicator(self)
        self.ps.busy.hide()
        self.ps.layout.addWidget(self.ps.busy)

        if step == 2:
            self.upgradeStep_2()
        elif step == 3:
            self.upgradeStep_3()
예제 #13
0
class UmMainScreen(QDialog, ui_mainscreen.Ui_UpgradeManager):
    def __init__(self, parent=None, step=1):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.logger = SimpleLogger()
        self.log = self.logger.log

        self.target_repo = REPO_TEMPLATE % 'stable'
        self.iface = Iface(self)

        self.connect(self.iface, SIGNAL("notify(PyQt_PyObject)"),
                     self.showMessage)

        self.msgbox = PMessageBox(self)
        self.msgbox.setStyleSheet("color:white;")
        self.msgbox.enableOverlay()
        # Just for Fun :)
        self.pageWidget = QPageWidget(
            self.widget_screens)  # , direction = 'ttb')
        self.layout.addWidget(self.pageWidget)

        self.button_next.clicked.connect(self.pageWidget.next)
        self.button_previous.clicked.connect(self.pageWidget.prev)
        self.button_cancel.clicked.connect(self.reject)

        # Threads
        self.thread_step_1 = PThread(self, self.step_1_start, self.step_1_end)
        self.thread_step_2 = PThread(self, self.step_2_start, self.step_2_end)
        self.thread_step_3 = PThread(self, self.step_3_start, self.step_3_end)

        # Update Page Title
        self.connect(self.pageWidget, SIGNAL("currentChanged()"), lambda:\
                     self.label_header.setText(self.pageWidget.getCurrentWidget().title))

        self.current_step = step

        if step == 1:
            self.thread_check = PThread(self, self.findMissingPackages,
                                        self.showResults)

            # Welcome
            self.pageWidget.createPage(
                getWidget(ui_screen_1, _("Welcome to Upgrade Manager...")))

            # Repo Selection
            self.pageWidget.createPage(
                getWidget(ui_screen_2, _("Select Upgrade Repository...")))

            # Check Results Page
            self.pageWidget.createPage(getWidget(ui_screen_3,
                                                 _("Checking your system...")),
                                       inMethod=self.checkSystem,
                                       outMethod=self.hideMessage)

            resultWidget = self.pageWidget.getWidget(2).ui
            resultWidget.widget.hide()

            def updateButtons():
                if self.button_next.text() == _("Next"):
                    self.button_next.setText(_("Yes, Upgrade"))
                    self.button_previous.setText(_("Cancel"))
                    self.button_cancel.hide()
                else:
                    self.button_next.setText(_("Next"))
                    self.button_previous.setText(_("Previous"))
                    self.button_cancel.show()

            # Last Question
            self.pageWidget.createPage(getWidget(ui_screen_4, ""),
                                       inMethod=updateButtons,
                                       outMethod=updateButtons)
        self._step_counter = 0

        # Progress Screen
        self.pageWidget.createPage(getWidget(ui_screen_5,
                                             _("Upgrading the system...")),
                                   inMethod=self.upgradeStep_1)

        # Shortcut for Progress Screen UI
        # Get the last added page as progress page
        # After the first step completed, um will use just this page !
        self.ps = self.pageWidget.getWidget(self.pageWidget.count() - 1).ui

        # Busy indicator to Progress Screen
        self.ps.busy = QProgressIndicator(self)
        self.ps.busy.hide()
        self.ps.layout.addWidget(self.ps.busy)

        if step == 2:
            self.upgradeStep_2()
        elif step == 3:
            self.upgradeStep_3()

    # Step 1 Method
    def checkSystem(self):
        self.showMessage(_("Checking your system..."))
        self.log("CHECKING CURRENT PACKAGES", "GUI")
        repoWidget = self.pageWidget.getWidget(1).ui

        for repo in ('stable', 'devel', 'testing'):
            if getattr(repoWidget, repo).isChecked():
                self.target_repo = REPO_TEMPLATE % repo

        if repoWidget.manual.isChecked():
            self.target_repo = str(repoWidget.manualRepo.text())

        self.thread_check.start()

    # Step 1 Method
    def findMissingPackages(self):
        updatePlan = DistupdatePlanner(nextRepoUri=self.target_repo,
                                       Debug=True,
                                       forceInstallUri=FORCE_INSTALL)
        updatePlan.plan()
        self.missing_packages = updatePlan.missingPackages
        try:
            self.missing_packages.remove("upgrade-manager")
        except ValueError:
            pass
        self.required_diskspace = updatePlan.sizeOfNeededTotalSpace
        self.planner_successful = updatePlan.successful

    # Step 1 Method
    def showResults(self):
        resultWidget = self.pageWidget.getWidget(2).ui
        free_size = os.statvfs('/').f_bavail * os.statvfs('/').f_bsize
        if not self.planner_successful:
            self.hideMessage()
            QMessageBox.critical(self, _("Critical Error"),
                                       _("An error ocurred while planning the upgrade procedure, "\
                                         "this is usually caused by faulty Network Connection or "\
                                         "wrong repo address."))
            self.pageWidget.prev()
            return
        if self.required_diskspace + 200000000 > free_size:
            self.hideMessage()
            QMessageBox.critical(self, _("Not enough free space"),
                                       _("This upgrade requires at least <b>%s MB</b> free space, "\
                                         "please use another repository or remove some files "\
                                         "to make a space for upgrade operation.") % \
                                       str(self.required_diskspace / (1024 ** 2)))
            self.pageWidget.prev()
            return
        else:
            resultWidget.widget.show()
            if self.missing_packages:
                resultWidget.package_list.clear()
                resultWidget.package_list.addItems(self.missing_packages)
            self.log(
                "MISSING PACKAGES FOUND: %s" % ','.join(self.missing_packages),
                "GUI")
        self.label_header.setText(_("Check results..."))
        self.hideMessage()

    # Step 1 Method
    def upgradeStep_1(self):
        self.log("STARTING TO STEP 1", "GUI")
        self.log('PISI VERSION in STEP 1 is %s' % str(pisi.__version__), "GUI")
        self.disableButtons()

        # To Animate it
        self.ps.steps.hide()
        self.ps.busy.busy()

        # Install New Pisi and its dependencies
        # To keep install in given order we need to pass ignore_dep as True
        self.thread_step_1.start()

    # Step 1 Threaded Method
    def step_1_start(self):
        resultWidget = self.pageWidget.getWidget(2).ui
        if resultWidget.remove_packages.isChecked():
            self.ps.progress.setFormat(_("Removing unsupported packages..."))
            self.iface.removePackages(self.missing_packages)

        self.ps.progress.setFormat(
            _("Installing new package management system..."))
        self.iface.removeRepos()
        self.iface.installPackages(map(lambda x: ARA_FORM % x,
                                       REQUIRED_PACKAGES),
                                   ignore_dep=True)

    # Step 1 Threaded Method Finalize
    def step_1_end(self):
        # END OF Step 1 in Upgrade
        self.log("STEP 1 COMPLETED", "GUI")
        self.ps.progress.setFormat(_("Step 1 Completed"))

        # STEP 1 Finishes at 10 percent
        self.ps.progress.setValue(10)

        # Write selected upgrade repository to a temporary file
        try:
            file('/tmp/target_repo', 'w').write(self.target_repo)
        except:
            self.log("TARGET REPO STORE FAILED, USING stable AS DEFAULT",
                     "GUI")

        # Mark the step
        self.logger.markStep(2)

        # Cleanup Pisi DB
        cleanup_pisi()

        # Just wait a little bit.
        time.sleep(2)

        # Re-launch the um for 2. step
        os.execv('/usr/bin/upgrade-manager',
                 ['/usr/bin/upgrade-manager', '--start-from-step2'])

    # Step 2 Method
    def upgradeStep_2(self):
        self.log("STARTING TO STEP 2", "GUI")
        self.disableButtons()
        self.ps.steps.hide()
        self.ps.busy.busy()
        self.ps.progress.setValue(10)
        self.ps.progress.setFormat(_("Upgrading to Pardus 2011..."))

        self.thread_step_2.start()

    # Step 2 Threaded Method
    def step_2_start(self):
        # Lets Update !
        self._step2_success = self.iface.upgradeSystem()

    # Step 2 Threaded Method Finalize
    def step_2_end(self):
        if not self._step2_success:
            QMessageBox.critical(self, _("Critical Error"),
                                       _("An error ocurred while upgrading the system, "\
                                         "this is usually caused by a repository problem.\n"\
                                         "Please try again later."))
            sys.exit(1)

        self.log("STEP 2 COMPLETED", "GUI")
        # Mark the step
        self.logger.markStep(3)

        # Just wait a little bit.
        time.sleep(2)

        # Re-launch the um for 3. step
        os.execv('/usr/bin/upgrade-manager',
                 ['/usr/bin/upgrade-manager', '--start-from-step3'])

    # Step 3 Method
    def upgradeStep_3(self):
        self.log("STARTING TO STEP 3", "GUI")
        self.disableButtons()
        self.ps.steps.hide()
        self.ps.busy.busy()
        self.ps.progress.setValue(70)
        self.ps.progress.setFormat(_("Configuring for Pardus 2011..."))

        self.thread_step_3.start()

    # Step 3 Threaded Method
    def step_3_start(self):
        # Lets Configure !
        self.iface.configureSystem()

    # Step 3 Threaded Method Finalize
    def step_3_end(self):
        self.log("STEP 3 COMPLETED", "GUI")
        # Step 4
        self.ps.progress.setFormat(_("Running Post Upgrade Operations..."))

        # Migrate KDE Configs
        self.log("RUNNING migrateKDE SCRIPT...", "GUI")
        migrateKDE()
        self.log("migrateKDE SCRIPT COMPLETED.", "GUI")

        # Migrate NetworkManager Configurations
        self.log("MIGRATING NETWORK PROFILES...", "GUI")
        os.system("/usr/sbin/migrate-comar-network-profiles")
        self.log("NETWORK PROFILES MIGRATED.", "GUI")

        # Migrate BootLoader conf
        self.log("MIGRATING grub.conf...", "GUI")
        migrateGrubconf('/boot/grub/grub.conf')
        self.log("grub.conf MIGRATED", "GUI")

        # Time to reboot
        self.ps.progress.setFormat(_("Rebooting to the Pardus 2011..."))

        # Finalize log.
        self.log("STEP 4 COMPLETED", "GUI")

        # Mark the step
        self.logger.markStep(4)

        # Just wait a little bit.
        time.sleep(3)

        # Time to reboot to Pardus 2011
        self.log("REBOOTING TO Pardus 2011...", "GUI")
        self.logger.close()
        os.system("reboot")

    # Shared Method
    def processNotify(self, event, notify):

        # print "PN:", event, "%%", notify

        self.hideMessage()

        if 'package' in notify:
            package = str(notify['package'].name)

            if event == installing:
                self.ps.status.setText(_("Installing: <b>%s</b>") % package)
            elif event == installed:
                self.ps.status.setText(_("Installed: <b>%s</b>") % package)
            elif event == upgraded:
                self.ps.status.setText(_("Upgraded: <b>%s</b>") % package)
            elif event == configuring:
                self.ps.status.setText(_("Configuring: <b>%s</b>") % package)
            elif event == configured:
                self.ps.status.setText(_("Configured: <b>%s</b>") % package)
            elif event == removing:
                self.ps.status.setText(_("Removing: <b>%s</b>") % package)
            elif event == removed:
                self.ps.status.setText(_("Removed: <b>%s</b>") % package)

            self.log(salt_text(self.ps.status.text()), "PISI")

            if event in (installed, upgraded) and self.current_step == 1:
                self.ps.progress.setValue(self.ps.progress.value() + 2)

            if self.current_step == 2 and event in (installed, upgraded):
                self._step_counter += 1
                # STEP 2 Finishes at 70 percent
                if self.iface._nof_packgages > 0:
                    self.ps.progress.setValue(10 + self._step_counter /
                                              (self.iface._nof_packgages / 60))

            if self.current_step == 3 and event == configured:
                self._step_counter += 1
                # STEP 3 Finishes at 100 percent
                if self.iface._nof_packgages > 0:
                    self.ps.progress.setValue(
                        70 + self._step_counter /
                        (self.iface._nof_packgages / 100))

    # Shared Method
    def updateProgress(self, raw):
        self.ps.status.setText(_("Downloading: <b>%s</b>") % raw['filename'])
        percent = raw['percent']

        if percent == 100:
            self.ps.steps.hide()
            self.ps.busy.busy()
        else:
            self.ps.steps.setValue(percent)
            self.ps.steps.show()
            self.ps.busy.hide()

    # Shared Method
    def showMessage(self, message):
        self.msgbox.busy.busy()
        self.msgbox.setMessage(message)
        if not self.msgbox.isVisible():
            self.msgbox.animate(start=MIDCENTER, stop=MIDCENTER)

    # Shared Method
    def hideMessage(self):
        if self.msgbox.isVisible():
            self.msgbox.animate(start=CURRENT, stop=CURRENT, direction=OUT)

    # Shared Method
    def disableButtons(self):
        for button in (self.button_cancel, self.button_previous,
                       self.button_next):
            button.setEnabled(False)

    # Shared Method
    def reject(self):
        self.log("USER REJECTED", "GUI")
        for thread in (self.thread_step_1, self.thread_step_2,
                       self.thread_step_3):
            if thread.isRunning():
                self.log("REQUEST IGNORED PISI IS STILL RUNNING !", "GUI")
                return
        self.log("REQUEST ACCEPTED, EXITING", "GUI")
        QDialog.reject(self)
예제 #14
0
파일: gui.py 프로젝트: muratongan/Pardus
    def __init__(self, parent = None, step = 1):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.logger = SimpleLogger()
        self.log = self.logger.log

        self.target_repo = REPO_TEMPLATE % 'stable'
        self.iface = Iface(self)

        self.connect(self.iface, SIGNAL("notify(PyQt_PyObject)"), self.showMessage)

        self.msgbox = PMessageBox(self)
        self.msgbox.setStyleSheet("color:white;")
        self.msgbox.enableOverlay()
                                                          # Just for Fun :)
        self.pageWidget = QPageWidget(self.widget_screens)# , direction = 'ttb')
        self.layout.addWidget(self.pageWidget)

        self.button_next.clicked.connect(self.pageWidget.next)
        self.button_previous.clicked.connect(self.pageWidget.prev)
        self.button_cancel.clicked.connect(self.reject)

        # Threads
        self.thread_step_1 = PThread(self, self.step_1_start, self.step_1_end)
        self.thread_step_2 = PThread(self, self.step_2_start, self.step_2_end)
        self.thread_step_3 = PThread(self, self.step_3_start, self.step_3_end)

        # Update Page Title
        self.connect(self.pageWidget, SIGNAL("currentChanged()"), lambda:\
                     self.label_header.setText(self.pageWidget.getCurrentWidget().title))

        self.current_step = step

        if step == 1:
            self.thread_check = PThread(self, self.findMissingPackages, self.showResults)

            # Welcome
            self.pageWidget.createPage(
                    getWidget(ui_screen_1, _("Welcome to Upgrade Manager...")))

            # Repo Selection
            self.pageWidget.createPage(
                    getWidget(ui_screen_2, _("Select Upgrade Repository...")))

            # Check Results Page
            self.pageWidget.createPage(
                    getWidget(ui_screen_3, _("Checking your system...")),
                    inMethod = self.checkSystem, outMethod = self.hideMessage)

            resultWidget = self.pageWidget.getWidget(2).ui
            resultWidget.widget.hide()

            def updateButtons():
                if self.button_next.text() == _("Next"):
                    self.button_next.setText(_("Yes, Upgrade"))
                    self.button_previous.setText(_("Cancel"))
                    self.button_cancel.hide()
                else:
                    self.button_next.setText(_("Next"))
                    self.button_previous.setText(_("Previous"))
                    self.button_cancel.show()

            # Last Question
            self.pageWidget.createPage(
                    getWidget(ui_screen_4, ""), inMethod = updateButtons,
                                                outMethod= updateButtons)
        self._step_counter = 0

        # Progress Screen
        self.pageWidget.createPage(
                getWidget(ui_screen_5, _("Upgrading the system...")), inMethod = self.upgradeStep_1)

        # Shortcut for Progress Screen UI
        # Get the last added page as progress page
        # After the first step completed, um will use just this page !
        self.ps = self.pageWidget.getWidget(self.pageWidget.count() - 1).ui

        # Busy indicator to Progress Screen
        self.ps.busy = QProgressIndicator(self)
        self.ps.busy.hide()
        self.ps.layout.addWidget(self.ps.busy)

        if step == 2:
            self.upgradeStep_2()
        elif step == 3:
            self.upgradeStep_3()
예제 #15
0
파일: gui.py 프로젝트: muratongan/Pardus
class UmMainScreen(QDialog, ui_mainscreen.Ui_UpgradeManager):

    def __init__(self, parent = None, step = 1):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.logger = SimpleLogger()
        self.log = self.logger.log

        self.target_repo = REPO_TEMPLATE % 'stable'
        self.iface = Iface(self)

        self.connect(self.iface, SIGNAL("notify(PyQt_PyObject)"), self.showMessage)

        self.msgbox = PMessageBox(self)
        self.msgbox.setStyleSheet("color:white;")
        self.msgbox.enableOverlay()
                                                          # Just for Fun :)
        self.pageWidget = QPageWidget(self.widget_screens)# , direction = 'ttb')
        self.layout.addWidget(self.pageWidget)

        self.button_next.clicked.connect(self.pageWidget.next)
        self.button_previous.clicked.connect(self.pageWidget.prev)
        self.button_cancel.clicked.connect(self.reject)

        # Threads
        self.thread_step_1 = PThread(self, self.step_1_start, self.step_1_end)
        self.thread_step_2 = PThread(self, self.step_2_start, self.step_2_end)
        self.thread_step_3 = PThread(self, self.step_3_start, self.step_3_end)

        # Update Page Title
        self.connect(self.pageWidget, SIGNAL("currentChanged()"), lambda:\
                     self.label_header.setText(self.pageWidget.getCurrentWidget().title))

        self.current_step = step

        if step == 1:
            self.thread_check = PThread(self, self.findMissingPackages, self.showResults)

            # Welcome
            self.pageWidget.createPage(
                    getWidget(ui_screen_1, _("Welcome to Upgrade Manager...")))

            # Repo Selection
            self.pageWidget.createPage(
                    getWidget(ui_screen_2, _("Select Upgrade Repository...")))

            # Check Results Page
            self.pageWidget.createPage(
                    getWidget(ui_screen_3, _("Checking your system...")),
                    inMethod = self.checkSystem, outMethod = self.hideMessage)

            resultWidget = self.pageWidget.getWidget(2).ui
            resultWidget.widget.hide()

            def updateButtons():
                if self.button_next.text() == _("Next"):
                    self.button_next.setText(_("Yes, Upgrade"))
                    self.button_previous.setText(_("Cancel"))
                    self.button_cancel.hide()
                else:
                    self.button_next.setText(_("Next"))
                    self.button_previous.setText(_("Previous"))
                    self.button_cancel.show()

            # Last Question
            self.pageWidget.createPage(
                    getWidget(ui_screen_4, ""), inMethod = updateButtons,
                                                outMethod= updateButtons)
        self._step_counter = 0

        # Progress Screen
        self.pageWidget.createPage(
                getWidget(ui_screen_5, _("Upgrading the system...")), inMethod = self.upgradeStep_1)

        # Shortcut for Progress Screen UI
        # Get the last added page as progress page
        # After the first step completed, um will use just this page !
        self.ps = self.pageWidget.getWidget(self.pageWidget.count() - 1).ui

        # Busy indicator to Progress Screen
        self.ps.busy = QProgressIndicator(self)
        self.ps.busy.hide()
        self.ps.layout.addWidget(self.ps.busy)

        if step == 2:
            self.upgradeStep_2()
        elif step == 3:
            self.upgradeStep_3()

    # Step 1 Method
    def checkSystem(self):
        self.showMessage(_("Checking your system..."))
        self.log("CHECKING CURRENT PACKAGES", "GUI")
        repoWidget = self.pageWidget.getWidget(1).ui

        for repo in ('stable', 'devel', 'testing'):
            if getattr(repoWidget, repo).isChecked():
                self.target_repo = REPO_TEMPLATE % repo

        if repoWidget.manual.isChecked():
            self.target_repo = str(repoWidget.manualRepo.text())

        self.thread_check.start()

    # Step 1 Method
    def findMissingPackages(self):
        updatePlan = DistupdatePlanner(nextRepoUri = self.target_repo, Debug = True, forceInstallUri = FORCE_INSTALL)
        updatePlan.plan()
        self.missing_packages = updatePlan.missingPackages
        try:
            self.missing_packages.remove("upgrade-manager")
        except ValueError:
            pass
        self.required_diskspace = updatePlan.sizeOfNeededTotalSpace
        self.planner_successful = updatePlan.successful

    # Step 1 Method
    def showResults(self):
        resultWidget = self.pageWidget.getWidget(2).ui
        free_size = os.statvfs('/').f_bavail * os.statvfs('/').f_bsize
        if not self.planner_successful:
            self.hideMessage()
            QMessageBox.critical(self, _("Critical Error"),
                                       _("An error ocurred while planning the upgrade procedure, "\
                                         "this is usually caused by faulty Network Connection or "\
                                         "wrong repo address."))
            self.pageWidget.prev()
            return
        if self.required_diskspace + 200000000 > free_size:
            self.hideMessage()
            QMessageBox.critical(self, _("Not enough free space"),
                                       _("This upgrade requires at least <b>%s MB</b> free space, "\
                                         "please use another repository or remove some files "\
                                         "to make a space for upgrade operation.") % \
                                       str(self.required_diskspace / (1024 ** 2)))
            self.pageWidget.prev()
            return
        else:
            resultWidget.widget.show()
            if self.missing_packages:
                resultWidget.package_list.clear()
                resultWidget.package_list.addItems(self.missing_packages)
            self.log("MISSING PACKAGES FOUND: %s" % ','.join(self.missing_packages), "GUI")
        self.label_header.setText(_("Check results..."))
        self.hideMessage()

    # Step 1 Method
    def upgradeStep_1(self):
        self.log("STARTING TO STEP 1", "GUI")
        self.log('PISI VERSION in STEP 1 is %s' % str(pisi.__version__),"GUI")
        self.disableButtons()

        # To Animate it
        self.ps.steps.hide()
        self.ps.busy.busy()

        # Install New Pisi and its dependencies
        # To keep install in given order we need to pass ignore_dep as True
        self.thread_step_1.start()

    # Step 1 Threaded Method
    def step_1_start(self):
        resultWidget = self.pageWidget.getWidget(2).ui
        if resultWidget.remove_packages.isChecked():
            self.ps.progress.setFormat(_("Removing unsupported packages..."))
            self.iface.removePackages(self.missing_packages)

        self.ps.progress.setFormat(_("Installing new package management system..."))
        self.iface.removeRepos()
        self.iface.installPackages(map(lambda x: ARA_FORM % x, REQUIRED_PACKAGES), ignore_dep = True)

    # Step 1 Threaded Method Finalize
    def step_1_end(self):
        # END OF Step 1 in Upgrade
        self.log("STEP 1 COMPLETED", "GUI")
        self.ps.progress.setFormat(_("Step 1 Completed"))

        # STEP 1 Finishes at 10 percent
        self.ps.progress.setValue(10)

        # Write selected upgrade repository to a temporary file
        try:
            file('/tmp/target_repo','w').write(self.target_repo)
        except:
            self.log("TARGET REPO STORE FAILED, USING stable AS DEFAULT", "GUI")

        # Mark the step
        self.logger.markStep(2)

        # Cleanup Pisi DB
        cleanup_pisi()

        # Just wait a little bit.
        time.sleep(2)

        # Re-launch the um for 2. step
        os.execv('/usr/bin/upgrade-manager', ['/usr/bin/upgrade-manager', '--start-from-step2'])

    # Step 2 Method
    def upgradeStep_2(self):
        self.log("STARTING TO STEP 2", "GUI")
        self.disableButtons()
        self.ps.steps.hide()
        self.ps.busy.busy()
        self.ps.progress.setValue(10)
        self.ps.progress.setFormat(_("Upgrading to Pardus 2011..."))

        self.thread_step_2.start()

    # Step 2 Threaded Method
    def step_2_start(self):
        # Lets Update !
        self._step2_success = self.iface.upgradeSystem()

    # Step 2 Threaded Method Finalize
    def step_2_end(self):
        if not self._step2_success:
            QMessageBox.critical(self, _("Critical Error"),
                                       _("An error ocurred while upgrading the system, "\
                                         "this is usually caused by a repository problem.\n"\
                                         "Please try again later."))
            sys.exit(1)

        self.log("STEP 2 COMPLETED", "GUI")
        # Mark the step
        self.logger.markStep(3)

        # Just wait a little bit.
        time.sleep(2)

        # Re-launch the um for 3. step
        os.execv('/usr/bin/upgrade-manager', ['/usr/bin/upgrade-manager', '--start-from-step3'])

    # Step 3 Method
    def upgradeStep_3(self):
        self.log("STARTING TO STEP 3", "GUI")
        self.disableButtons()
        self.ps.steps.hide()
        self.ps.busy.busy()
        self.ps.progress.setValue(70)
        self.ps.progress.setFormat(_("Configuring for Pardus 2011..."))

        self.thread_step_3.start()

    # Step 3 Threaded Method
    def step_3_start(self):
        # Lets Configure !
        self.iface.configureSystem()

    # Step 3 Threaded Method Finalize
    def step_3_end(self):
        self.log("STEP 3 COMPLETED", "GUI")
        # Step 4
        self.ps.progress.setFormat(_("Running Post Upgrade Operations..."))

        # Migrate KDE Configs
        self.log("RUNNING migrateKDE SCRIPT...", "GUI")
        migrateKDE()
        self.log("migrateKDE SCRIPT COMPLETED.", "GUI")

        # Migrate NetworkManager Configurations
        self.log("MIGRATING NETWORK PROFILES...", "GUI")
        os.system("/usr/sbin/migrate-comar-network-profiles")
        self.log("NETWORK PROFILES MIGRATED.", "GUI")

        # Migrate BootLoader conf
        self.log("MIGRATING grub.conf...", "GUI")
        migrateGrubconf('/boot/grub/grub.conf')
        self.log("grub.conf MIGRATED", "GUI")

        # Time to reboot
        self.ps.progress.setFormat(_("Rebooting to the Pardus 2011..."))

        # Finalize log.
        self.log("STEP 4 COMPLETED", "GUI")

        # Mark the step
        self.logger.markStep(4)

        # Just wait a little bit.
        time.sleep(3)

        # Time to reboot to Pardus 2011
        self.log("REBOOTING TO Pardus 2011...", "GUI")
        self.logger.close()
        os.system("reboot")

    # Shared Method
    def processNotify(self, event, notify):

        # print "PN:", event, "%%", notify

        self.hideMessage()

        if 'package' in notify:
            package = str(notify['package'].name)

            if event == installing:
                self.ps.status.setText(_("Installing: <b>%s</b>") % package)
            elif event == installed:
                self.ps.status.setText(_("Installed: <b>%s</b>") % package)
            elif event == upgraded:
                self.ps.status.setText(_("Upgraded: <b>%s</b>") % package)
            elif event == configuring:
                self.ps.status.setText(_("Configuring: <b>%s</b>") % package)
            elif event == configured:
                self.ps.status.setText(_("Configured: <b>%s</b>") % package)
            elif event == removing:
                self.ps.status.setText(_("Removing: <b>%s</b>") % package)
            elif event == removed:
                self.ps.status.setText(_("Removed: <b>%s</b>") % package)

            self.log(salt_text(self.ps.status.text()), "PISI")

            if event in (installed, upgraded) and self.current_step == 1:
                self.ps.progress.setValue(self.ps.progress.value() + 2)

            if self.current_step == 2 and event in (installed, upgraded):
                self._step_counter += 1
                # STEP 2 Finishes at 70 percent
                if self.iface._nof_packgages > 0:
                    self.ps.progress.setValue(10 + self._step_counter / (self.iface._nof_packgages / 60))

            if self.current_step == 3 and event == configured:
                self._step_counter += 1
                # STEP 3 Finishes at 100 percent
                if self.iface._nof_packgages > 0:
                    self.ps.progress.setValue(70 + self._step_counter / (self.iface._nof_packgages / 100))

    # Shared Method
    def updateProgress(self, raw):
        self.ps.status.setText(_("Downloading: <b>%s</b>") % raw['filename'])
        percent = raw['percent']

        if percent==100:
            self.ps.steps.hide()
            self.ps.busy.busy()
        else:
            self.ps.steps.setValue(percent)
            self.ps.steps.show()
            self.ps.busy.hide()

    # Shared Method
    def showMessage(self, message):
        self.msgbox.busy.busy()
        self.msgbox.setMessage(message)
        if not self.msgbox.isVisible():
            self.msgbox.animate(start = MIDCENTER, stop = MIDCENTER)

    # Shared Method
    def hideMessage(self):
        if self.msgbox.isVisible():
            self.msgbox.animate(start = CURRENT, stop = CURRENT, direction = OUT)

    # Shared Method
    def disableButtons(self):
        for button in (self.button_cancel, self.button_previous, self.button_next):
            button.setEnabled(False)

    # Shared Method
    def reject(self):
        self.log("USER REJECTED", "GUI")
        for thread in (self.thread_step_1, self.thread_step_2, self.thread_step_3):
            if thread.isRunning():
                self.log("REQUEST IGNORED PISI IS STILL RUNNING !", "GUI")
                return
        self.log("REQUEST ACCEPTED, EXITING", "GUI")
        QDialog.reject(self)
예제 #16
0
class Widget(QWidget, ScreenWidget):
    name = "timeSetup"

    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_DateTimeWidget()
        self.ui.setupUi(self)
        self.timer = QTimer(self)
        self.from_time_updater = True
        self.is_date_changed = False

        self.current_zone = ""

        self.tz_dict = {}
        self.continents = []
        self.countries = []

        for country, data in yali.localedata.locales.items():
            if country == ctx.consts.lang:
                if data.has_key("timezone"):
                    ctx.installData.timezone = data["timezone"]

        # Append continents and countries the time zone dictionary
        self.createTZDictionary()

        # Sort continent list
        self.sortContinents()

        # Append sorted continents to combobox
        self.loadContinents()

        # Load current continents country list
        self.getCountries(self.current_zone["continent"])

        # Highlight the current zone
        self.index = self.ui.continentList.findText(self.current_zone["continent"])
        self.ui.continentList.setCurrentIndex(self.index)

        self.index = self.ui.countryList.findText(self.current_zone["country"])
        self.ui.countryList.setCurrentIndex(self.index)

        # Initialize widget signal and slots
        self.__initSignals__()

        self.ui.calendarWidget.setDate(QDate.currentDate())

        self.pthread = None
        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.timer.start(1000)

    def __initSignals__(self):
        self.ui.timeEdit.timeChanged[QTime].connect(self.timerStop)
        self.ui.calendarWidget.dateChanged.connect(self.dateChanged)
        self.timer.timeout.connect(self.updateClock)
        self.ui.continentList.activated[str].connect(self.getCountries)

    def createTZDictionary(self):
        tz = TimeZoneList()
        zones = [ x.timeZone for x in tz.getEntries() ]
        zones.sort()

        for zone in zones:
            split = zone.split("/")

            # Human readable continent names
            continent_pretty_name = split[0].replace("_", " ")
            continent_pretty_name = continent_pretty_name

            # Some country names can be like Argentina/Catamarca so this fixes the splitting problem
            # caused by zone.split("/")
            #
            # Remove continent info and take the rest as the country name
            split.pop(0)
            country_pretty_name = " / ".join(split)

            # Human readable country names
            country_pretty_name = country_pretty_name.replace("_", " ")

            # Get current zone
            if zone == ctx.installData.timezone:
                self.current_zone = { "continent":continent_pretty_name, "country":country_pretty_name}

            # Append to dictionary
            if self.tz_dict.has_key(continent_pretty_name):
                self.tz_dict[continent_pretty_name].append([country_pretty_name, zone])
            else:
                self.tz_dict[continent_pretty_name] = [[country_pretty_name, zone]]


    def sortContinents(self):
        for continent in self.tz_dict.keys():
            self.continents.append(continent)
        self.continents.sort()

    def loadContinents(self):
        for continent in self.continents:
            self.ui.continentList.addItem(continent)

    def getCountries(self, continent):
        # Countries of the selected continent
        countries = self.tz_dict[str(continent)]

        self.ui.countryList.clear()

        for country, zone in countries:
            self.ui.countryList.addItem(country, zone)
            self.countries.append(country)



    def dateChanged(self):
        self.is_date_changed = True

    def timerStop(self):
        if self.from_time_updater:
            return
        # Human action detected; stop the timer.
        self.timer.stop()

    def updateClock(self):

        # What time is it ?
        cur = QTime.currentTime()

        self.from_time_updater = True
        self.ui.timeEdit.setTime(cur)
        self.from_time_updater = False

    def shown(self):
        self.timer.start(1000)

        if ctx.flags.install_type == ctx.STEP_BASE:
            self.pthread = PThread(self, self.startInit, self.dummy)

    def dummy(self):
        pass

    def setTime(self):
        ctx.interface.informationWindow.update(_("Adjusting time settings"))
        date = self.ui.calendarWidget.date()
        time = self.ui.timeEdit.time()
        args = "%02d%02d%02d%02d%04d.%02d" % (date.month(), date.day(),
                                              time.hour(), time.minute(),
                                              date.year(), time.second())


        # Set current date and time
        ctx.logger.debug("Date/Time setting to %s" % args)
        yali.util.run_batch("date", [args])

        # Sync date time with hardware
        ctx.logger.debug("YALI's time is syncing with the system.")
        yali.util.run_batch("hwclock", ["--systohc"])
        ctx.interface.informationWindow.hide()

    def execute(self):
        if not self.timer.isActive() or self.is_date_changed:
            QTimer.singleShot(500, self.setTime)
            self.timer.stop()

        index = self.ui.countryList.currentIndex()
        ctx.installData.timezone = self.ui.countryList.itemData(index)
        ctx.logger.debug("Time zone selected as %s " % ctx.installData.timezone)

        if ctx.flags.install_type == ctx.STEP_BASE:
            #FIXME:Refactor hacky code
            ctx.installData.rootPassword = ctx.consts.default_password
            ctx.installData.hostName = yali.util.product_release()
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
                return True
            else:
                self.pds_messagebox.setMessage(_("Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True

    def startInit(self):
        self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)

    def startStorageInitialize(self):
        ctx.storageInitialized = yali.storage.initialize(ctx.storage, ctx.interface)
        self.initFinished()

    def initFinished(self):
        self.pds_messagebox.animate(start=CURRENT, stop=CURRENT, direction=OUT)
        disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
        if ctx.storageInitialized:
            if len(disks) == 1:
                ctx.storage.clearPartDisks = [disks[0].name]
                ctx.mainScreen.step_increment = 2
            else:
                ctx.mainScreen.step_increment = 1
            ctx.mainScreen.slotNext(dry_run=True)
        else:
            ctx.mainScreen.enableBack()
예제 #17
0
    def shown(self):
        self.timer.start(1000)

        if ctx.flags.install_type == ctx.STEP_BASE:
            self.pthread = PThread(self, self.startInit, self.dummy)
예제 #18
0
class Widget(QWidget, ScreenWidget):
    name = "admin"
    finished=pyqtSignal()
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type == ctx.STEP_DEFAULT:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.ui.pass1.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.textChanged[str].connect(self.slotTextChanged)
        self.ui.pass2.returnPressed.connect(self.slotReturnPressed)
        self.ui.hostname.textChanged[str].connect(self.slotHostnameChanged)

    def update(self):
        if self.host_valid and self.pass_valid:
            ctx.mainScreen.enableNext()
        else:
            ctx.mainScreen.disableNext()

    def shown(self):
        if ctx.installData.hostName:
            self.ui.hostname.setText(str(ctx.installData.hostName))
        else:
            # Use first added user's name as machine name if its exists
            release_hostname = yali.util.product_release()
            if self.ui.hostname.text() == '':
                self.ui.hostname.setText(release_hostname)

        if ctx.installData.rootPassword:
            self.ui.pass1.setText(ctx.installData.rootPassword)
            self.ui.pass2.setText(ctx.installData.rootPassword)

        self.update()
        self.checkCapsLock()
        self.ui.pass1.setFocus()


    def dummy(self):
        pass

    def execute(self):
        ctx.installData.rootPassword = unicode(self.ui.pass1.text())
        ctx.installData.hostName = unicode(self.ui.hostname.text())

        if ctx.flags.install_type == ctx.STEP_DEFAULT:
            #FIXME:Refactor dirty code
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
            else:
                self.pds_messagebox.setMessage(_("Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True

    def startInit(self):
        self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)

    def startStorageInitialize(self):
        ctx.storageInitialized = yali.storage.initialize(ctx.storage, ctx.interface)
        self.initFinished()

    def initFinished(self):
        self.pds_messagebox.animate(start=CURRENT, stop=CURRENT, direction=OUT)
        disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
        if ctx.storageInitialized:
            if len(disks) == 1:
                ctx.storage.clearPartDisks = [disks[0].name]
                ctx.mainScreen.step_increment = 2
            else:
                ctx.mainScreen.step_increment = 1
            ctx.mainScreen.slotNext(dry_run=True)
            self.finished.emit()
        else:
            ctx.mainScreen.enableBack()

    def setCapsLockIcon(self, child):
        if type(child) == QLineEdit:
            if pardus.xorg.capslock.isOn():
                child.setStyleSheet("""QLineEdit {
                        background-image: url(:/gui/pics/caps.png);
                        background-repeat: no-repeat;
                        background-position: right;
                        padding-right: 35px;
                        }""")
            else:
                child.setStyleSheet("""QLineEdit {
                        background-image: none;
                        padding-right: 0px;
                        }""")

    def checkCapsLock(self):
        for child in self.ui.groupBox.children():
            self.setCapsLockIcon(child)

    def keyReleaseEvent(self, event):
        self.checkCapsLock()

    def slotTextChanged(self):

        password = str(self.ui.pass1.text())
        password_confirm = str(self.ui.pass2.text())

        if password and password == password_confirm:
            if len(password) < 4:
                self.intf.informationWindow.update(_('Password is too short.'), type="error")
                self.pass_valid = False
            else:
                self.intf.informationWindow.hide()
                self.pass_valid = True
        else:
            self.pass_valid = False
            if password_confirm:
                self.intf.informationWindow.update(_('Passwords do not match.'), type="error")

        if password.lower()=="root" or password_confirm.lower()=="root":
            self.pass_valid = False
            if password_confirm:
                self.intf.informationWindow.update(_('Do not use your username as your password.'), type="error")

        if self.pass_valid:
            self.intf.informationWindow.hide()

        self.update()

    def slotHostnameChanged(self, hostname):
        if len(hostname) > 64:
            self.host_valid = False
            self.intf.informationWindow.update(_('Hostname cannot be longer than 64 characters.'), type="error")
            self.update()
            return


        if not hostname:
            self.host_valid = False
            self.update()
            return

        self.host_valid = yali.util.is_text_valid(hostname)

        if not self.host_valid:
            self.intf.informationWindow.update(_('Hostname contains invalid characters.'), type="error")
        else:
            self.intf.informationWindow.hide()
        self.update()


    def slotReturnPressed(self):
        if ctx.mainScreen.isNextEnabled():
            ctx.mainScreen.slotNext()
예제 #19
0
class MainWidget(QWidget, PM, Ui_MainWidget):
    # Signal Emits
    updatingStatus = pyqtSignal()
    repositoriesUpdated = pyqtSignal()
    selectionStatusChanged = pyqtSignal([str])
    finished = pyqtSignal()
    cleanUp = pyqtSignal()
    
    def __init__(self, parent = None):
        super(MainWidget, self).__init__(parent)
        
        self.setupUi(self)
        self.parent = parent
        
        self._selectedGroups = []
        self._preexceptions  = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False
        
        
        # Search Thread
        self._searchThread = PThread(self, self.startSearch, self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon(("edit-find", "find")))
        self.initializeUpdateTypeList()

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)
        
        
        
        self.packageList.dataChanged[QModelIndex,QModelIndex].connect(self.statusChanged)
        
        self.packageList.updateRequested.connect(self.initialize)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(FINISHED, lambda: self.parent.statusBar().setVisible(not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)
        

    def connectMainSignals(self):
        self.actionButton.clicked.connect(self.showBasket)
        self.checkUpdatesButton.clicked.connect(self.state.updateRepoAction)
        self.searchButton.clicked.connect(self.searchActivated)
        self.searchLine.textEdited[str].connect(self.searchLineChanged)
        self.searchLine.returnPressed.connect(self.searchActivated)
        
        self.searchLine.textChanged[str].connect(self.slotSearchLineClear)       
        
        self.typeCombo.activated[int].connect(self.typeFilter)
        self.stateTab.currentChanged[int].connect(self.switchState)
        self.groupList.groupChanged.connect(self.groupFilter)
        self.groupList.groupChanged.connect(lambda:self.searchButton.setEnabled(False))
        self.packageList.select_all.clicked[bool].connect(self.toggleSelectAll)
        self.packageList.itemDelegate().packageSelected[bool].connect(self.toggleSelect)
        self.statusUpdater.selectedInfoChanged[int,str,int,str].connect(self.emitStatusBarInfo)
        self.statusUpdater.selectedInfoChanged[str].connect(lambda message: self.selectionStatusChanged[str].emit(message))
        self.statusUpdater.finished.connect(self.statusUpdated)

    def initialize(self):
        waitCursor()
        self.searchLine.clear()
        self._started = False
        self._last_packages = None
        self.state.reset()
        self.initializePackageList()
        self.initializeGroupList()
        self.initializeStatusUpdater()
        self.statusChanged()
        self._selectedGroups = []
        self.packageList.select_all.setChecked(False)
        self.initializeBasket()
        self.searchLine.setFocus(True)
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0:
                QTimer.singleShot(0, \
                lambda: self.pdsMessageBox.showMessage(_translate("Packaga Manager","All packages are up to date"), icon = "info"))
        if self.groupList.count() > 0:
            if self.state.inUpgrade():
                self.pdsMessageBox.hideMessage(force = True)
        restoreCursor()

    def initializeStatusUpdater(self):
        self.statusUpdater.calculate_deps = not self.state.state == self.state.ALL
        self.statusUpdater.setModel(self.packageList.model().sourceModel())

    def initializeBasket(self):
        waitCursor()
        self.basket.setModel(self.packageList.model().sourceModel())
        restoreCursor()

    def initializePackageList(self):
        self.packageList.model().reset()
        self.packageList.setPackages(self.state.packages())

        if self.completer:
            self.completer.deleteLater()
            del self.completer

        self.completer = QCompleter(self.state.allPackages(), self)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchLine.setCompleter(self.completer)

    def selectComponent(self, component):
        if not self.state.iface.operationInProgress():
            if self.basket.isVisible():
                self.basket._hide()

            self.stateTab.setCurrentIndex(1)
            self.switchState(self.state.INSTALL)

            if component in self.groupList._list:
                self.groupList.setCurrentItem(self.groupList._list[component])
                self.groupFilter()

    def updateSettings(self):   # pmconfig ikinci kez okunmuyor
        self.packageList.showComponents = PMConfig().showComponents()
        self.packageList.showIsA = PMConfig().showIsA()
        self.packageList.setFocus()
        self.initialize()

    def searchLineChanged(self, text):
        self.searchButton.setEnabled(bool(text))
        if text == '':
            self.searchActivated()

    def statusUpdated(self):
        if self.statusUpdater.needsUpdate:
            self.statusUpdater.needsUpdate = False
            self.statusChanged()

    def statusChanged(self):
        self.setActionEnabled()
        if self.statusUpdater.isRunning():
            self.statusUpdater.needsUpdate = True
        else:
            self.updatingStatus.emit()
            self.statusUpdater.start()

    def initializeGroupList(self):
        self.groupList.clear()
        self.groupList._list = {}
        self.groupList.setAlternatingRowColors(True)
        self.groupList.setIconSize(QSize(32, 32))
        self.groupList.setState(self.state)
        self.groupList.addGroups(self.state.groups())
        if self.state.state == self.state.UPGRADE:
            self.typeCombo.show()
        else:
            self.typeCombo.hide()
            self.state._typeFilter = 'normal'
        self.groupFilter()

    def packageFilter(self, text):
        self.packageList.model().setFilterRole(Qt.DisplayRole)
        self.packageList.model().setFilterRegExp(QRegExp(unicode(text), Qt.CaseInsensitive, QRegExp.FixedString))

    def typeFilter(self, index):
        if self.state.state == self.state.UPGRADE:
            filter = self.typeCombo.itemData(index)
            if not self.state._typeFilter == filter:
                self.state._typeFilter = filter
                self.initializeGroupList()
    def slotSearchLineClear(self):
        if self.searchLine.text()!="":
            return
        
        self.groupFilter()
    
    def groupFilter(self):
        waitCursor()
        self.packageList.resetMoreInfoRow()
        packages = self.state.groupPackages(self.groupList.currentGroup())
        self.packageList.model().setFilterRole(GroupRole)
        self.packageList.model().setFilterPackages(packages)
        self.packageList.scrollToTop()
        self.packageList.select_all.setChecked(self.groupList.currentGroup() in self._selectedGroups)
        restoreCursor()

    def searchActivated(self):
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0 and not self.searchUsed:
                return
                
        if not self.searchLine.text() == '':
            self.pdsMessageBox.showMessage(_translate("Packaga Manager","Searching..."), busy = True)
            self.groupList.lastSelected = None
            self._searchThread.start()
            self.searchUsed = True
        else:
            self.state.cached_packages = None
            self.state.packages()
            self.searchUsed = False
            self.searchFinished()

    def searchFinished(self):
        if self.state.cached_packages == []:
            self.pdsMessageBox.showMessage(_translate("Packaga Manager","No results found."), "dialog-information")
        else:
            self.pdsMessageBox.hideMessage()
        self.initializeGroupList()
        self.initializePackageList()
        

    def startSearch(self):
        searchText = str(self.searchLine.text()).split()
        sourceModel = self.packageList.model().sourceModel()
        self.state.cached_packages = sourceModel.search(searchText)
        self.finished.emit()
        return self.state.cached_packages

    def setActionButton(self):
        self.actionButton.setEnabled(False)
        if self.state.state == self.state.ALL:
            menu = QMenu(self.actionButton)
            self.__install_action = menu.addAction(self.state.getActionIcon(self.state.INSTALL),
                                                   self.state.getActionName(self.state.INSTALL),
                                                   self.showBasket)
            self.__remove_action = menu.addAction(self.state.getActionIcon(self.state.REMOVE),
                                                  self.state.getActionName(self.state.REMOVE),
                                                  self.showBasket)
            self.actionButton.setMenu(menu)
        else:
            self.actionButton.setMenu(None)
        self.actionButton.setIcon(self.state.getActionIcon())
        self.actionButton.setText(self.state.getActionName())

    def actionStarted(self, operation):
        self.pdsMessageBox.hideMessage()
        self.progressDialog.reset()
        if not operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            totalPackages = self.packageList.packageCount()
            self.operation.setTotalPackages(totalPackages)
            self.progressDialog.updateStatus(0, totalPackages, self.state.toBe())
        if self.isVisible():
            if operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
                self.progressDialog.repoOperationView()
            if self.basket.isVisible():
                self.basket._hide()
                QTimer.singleShot(0, self.progressDialog._show)
            else:
                self.progressDialog._show()

        if not self._started:
            self.progressDialog.disableCancel()
        else:
            self.progressDialog.enableCancel()

    def actionFinished(self, operation):
        if operation in ("System.Manager.installPackage",
                         "System.Manager.removePackage",
                         "System.Manager.updatePackage"):
            self.notifyFinished()

        if operation == "System.Manager.installPackage" and self._started:
            KIconLoader.updateAvailableIcons()
            self.summaryDialog.setDesktopFiles(self.operation.desktopFiles)
            self.summaryDialog.showSummary()

        if operation in ("System.Manager.updateRepository",
                         "System.Manager.updateAllRepositories"):
            self.repositoriesUpdated.emit()
        self.searchLine.clear()
        self.state.reset()
        self.progressDialog._hide()
        if not self.currentState == self.state.UPGRADE:
            self.switchState(self.currentState)
        self.initialize()

    def actionCancelled(self):
        self.progressDialog._hide()
        self.progressDialog.reset()
        self.switchState(self.currentState)
        self.groupFilter()

    def setActionEnabled(self):
        enabled = self.packageList.isSelected()
        self.actionButton.setEnabled(enabled)
        self.basket.setActionEnabled(enabled)

    def switchState(self, state):
        self.pdsMessageBox.hideMessage()
        self._states[state][1].setChecked(True)
        self.state.setState(state)
        self.currentState = state
        self._selectedGroups = []
        if not state == self.state.HISTORY:
            self.setActionButton()
            self.state.cached_packages = None
            if state == self.state.UPGRADE or (state == self.state.INSTALL and self.groupList.count() == 1):
                if not self._updatesCheckedOnce:
                    self._updatesCheckedOnce = self.state.updateRepoAction(silence = True)
            self.checkUpdatesButton.setHidden(not state == self.state.UPGRADE)
            self.initialize()

    def emitStatusBarInfo(self, packages, packagesSize, extraPackages, extraPackagesSize):
        self.selectionStatusChanged[str].emit(self.state.statusText(packages, packagesSize, extraPackages, extraPackagesSize))
        
        # paket seçimine geçici çözüm
        if packages > 0:
            self.actionButton.setEnabled(True)
        else:
            self.actionButton.setEnabled(False)

    def setSelectAll(self, packages=None):
        if packages:
            self.packageList.reverseSelection(packages)

    def setReverseAll(self, packages=None):
        if packages:
            self.packageList.selectAll(packages)

    def toggleSelectAll(self, toggled):
        self._last_packages = self.packageList.model().getFilteredPackages()

        if toggled:
            if self.groupList.currentGroup() not in self._selectedGroups:
                self._selectedGroups.append(self.groupList.currentGroup())
            self.setReverseAll(self._last_packages)
        else:
            if self.groupList.currentGroup() in self._selectedGroups:
                self._selectedGroups.remove(self.groupList.currentGroup())
            self.setSelectAll(self._last_packages)

        self.packageList.setFocus()
        self.statusChanged()
    
    def toggleSelect(self, toggled):
        #self._last_packages = self.packageList.model().getFilteredPackages()
        if toggled:
            if self.groupList.currentGroup() not in self._selectedGroups:
                self._selectedGroups.append(self.groupList.currentGroup())
        
        #else:
            #if self.groupList.currentGroup() in self._selectedGroups:
            #    self._selectedGroups.remove(self.groupList.currentGroup())
            #self.setSelectAll(self._last_packages)

        self.packageList.setFocus()
        self.statusChanged() 

    def showBasket(self):

        if self.basket.isVisible():
            return

        waitCursor()
        self.statusUpdater.wait()

        if self.currentState == self.state.ALL:
            action = {self.__remove_action:self.state.REMOVE,
                      self.__install_action:self.state.INSTALL}.get(self.sender(), self.state.INSTALL)
            if action:
                if action == self.state.REMOVE:
                    installed_packages = self.state.iface.getInstalledPackages()
                    filtered_packages = filter(lambda x: x not in installed_packages, self.basket.model.selectedPackages())
                    if filtered_packages == self.basket.model.selectedPackages():
                        restoreCursor()
                        QMessageBox(_translate("Packaga Manager","Select packages"),
                                    _translate("Packaga Manager","You must select at least one installed package"),
                                    QMessageBox.Information, QMessageBox.Ok, 0, 0).exec_()
                        return
                    self.packageList.model().sourceModel().selectPackages(filtered_packages, state = False)

                self.state.state = action

        self.basket._show()
        restoreCursor()

    def initializeUpdateTypeList(self):
        self.typeCombo.clear()
        UPDATE_TYPES = [['normal', _translate("Packaga Manager",'All Updates'), ('system-software-update', 'ledgreen')],
                        ['security', _translate("Packaga Manager",'Security Updates'), ('security-medium', 'ledyellow')],
                        ['critical', _translate("Packaga Manager",'Critical Updates'), ('security-low', 'ledred')]]

        for type in UPDATE_TYPES:
            self.typeCombo.addItem(KIcon(type[2]), type[1], QVariant(type[0]))
예제 #20
0
class WebDialog(PAbstractBox, Ui_WebDialog):
    def __init__(self, state, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)
        self.state = state
        self.iface = parent.iface
        # PDS Settings
        self._animation = 1
        self._duration = 400
        self.enableOverlay()
        self._disable_parent_in_shown = True
        self.webView.hide()
      
        #Url list for package pisi source files
        global packageUrlList
        packageUrlList = []
        
        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(FINISHED, lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://youtube.googleapis.com/v'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("dialog-close"))

        self.packageHomepage.clicked.connect(self.openWebsite)
        self.packagePisiSource.clicked.connect(self.openPisiSource)
        #self.wdInstallButton.clicked.connect(self.showBasket)
        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.webView.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.showFullImage)

        self.tabWidget.removeTab(0)

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.filterLine.setListWidget(self.filesList)
        self.noconnection.hide()
        self.parent = parent


    def showFullImage(self, url):
        PreviewDialog(self, url)

    def getFiles(self):
        return self.iface.getPackageFiles(str(self.packageName.text()))

    def getFilesFinished(self):
        self.filesList.addItems(self._filesThread.get())
        self.filesList.sortItems()

    def _tabSwitched(self, index):
        if index == 0 and self.tabWidget.count() > 1:
            if self.filesList.count() == 0:
                self._filesThread.start()

    def _sync_template(self, status, package = '', summary = '', description = ''):
        def _replace(key, value):
            self.webView.page().mainFrame().evaluateJavaScript(\
                    '%s.innerHTML="%s";' % (key, value))
        if status:
            _replace('title', package)
            _replace('summary', summary)
            _replace('description', description)
            self.webWidget.show()
            self.noconnection.hide()
        else:
            self.noconnection.hide()
            self.webWidget.show()

        reset_proxy_settings()

    def openWebsite(self):
        webbrowser.open_new_tab(packageUrlList[1])
        
    def openPisiSource(self):
        webbrowser.open_new_tab(packageUrlList[0]) 
    
    def showBasket(self):
        package = [self.packageName.text()]
        print package
        self.basket.__initList(package)
        self.basket._show()
        
    def __makePath(self, path, package):
        #Package Component configure for PiSi source files url.
        #And added new urls to packageUrlList       
        global packageSourceUrl
        __make = path.split(".")
        newPath = ("/").join(__make)
        packageSourceUrl = "https://github.com/pisilinux/PisiLinux/tree/master/%s/%s" % (newPath, package)
        self.packagePisiSource.setToolTip(packageSourceUrl) 
        #packageUrlList[0] => pisi source files url
        #packageUrlList[1] => package home page url
        packageUrlList.append(packageSourceUrl)
        packageUrlList.append(self.packageHomepage.text())
        
    def showPackageDetails(self, package, installed, summary='', description='', homepage='', appIsa='', appComponent='', rate="", repository='', _icon=''):
        self.packageName.setText(package)
        self.packageSummary.setText(summary)
        self.packageDescription.setText(description)
        self.packageHomepage.setText(homepage)
        self.packageComponent.setText(appComponent)
        self.packageIsa.setText(appIsa)        
        self.kratingwidget.setRating(rate)
        self.packageRepo.setText(repository)

        #package big screenshot in ToolTip
        self.__ssUrl = "/tmp/pm-ss/%s.png" % package

        if os.path.isdir("/tmp/pm-ss") == False:
            os.mkdir("/tmp/pm-ss")
        else:
            pass
        
        if os.path.isfile(self.__ssUrl) == False:
            
            if network_available():
                try:
                    imageUrl = urllib2.urlopen("http://www.ozgurlukicin.org/media/upload/tema/paket-goruntusu/buyuk/%s.png" % package )
                    imageData = imageUrl.read()
                    image = open(self.__ssUrl,"w")
                    image.write(imageData)
                    imageUrl.close()
                    image.close()
                except:
                    print "%s not found." % package
                    
                self.labelScreenshot.setPixmap(QtGui.QPixmap("/tmp/pm-ss/%s.png" % package))         
                self.labelScreenshot.setToolTip("<html><head/><body><img src='/tmp/pm-ss/%s.png'/>%s</body></html>" % (package,package))         
            else:
                print "net yok" 
                if os.path.isfile(self.__ssUrl) == False:
                    self.labelScreenshot.setText(package)
                else:
                    self.labelScreenshot.setPixmap(QtGui.QPixmap(self.__ssUrl))
                    self.labelScreenshot.setToolTip("<html><head/><body><p><img src=\"%s\"/></p></body></html>" % self.__ssUrl)
        else:
            print "..."
            self.labelScreenshot.setPixmap(QtGui.QPixmap("/tmp/pm-ss/%s.png" % package)) 
            self.labelScreenshot.setToolTip("<html><head/><body><img src='/tmp/pm-ss/%s.png'/>%s</body></html>" % (package,package))  
       
        #Make path for source url
        self.__makePath(appComponent, package)
        #Package logo for package details tab and logo image control
        if os.path.isfile("/usr/share/pixmaps/%s.png" % package) == False:
            self.packageLogo.setPixmap(QtGui.QPixmap("/usr/share/icons/hicolor/32x32/mimetypes/application-x-pisi.png"))
        else:
            self.packageLogo.setPixmap(QtGui.QPixmap("/usr/share/pixmaps/%s.png" % package))        
        self.filesList.clear()
        self.tabWidget.insertTab(0, self.packageFiles, i18n('Package Files'))
        self.tabWidget.currentChanged.connect(self._tabSwitched)
        if not installed:
            self.tabWidget.removeTab(0)
            self.tabWidget.currentChanged.disconnect(self._tabSwitched)
        self.animate(start = BOTCENTER, stop = MIDCENTER)

    def _show(self):
        self.animate(start = BOTCENTER, stop = MIDCENTER)
        self._shown = True

    def _hide(self):
        if len(packageUrlList) > 0:
            del packageUrlList[:] # for package url
        else:
            pass       
        self.animate(start = MIDCENTER, stop = BOTCENTER, direction = OUT)
예제 #21
0
class WebDialog(PAbstractBox, Ui_WebDialog):
    def __init__(self, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)

        self.iface = parent.iface

        # PDS Settings
        self._animation = 1
        self._duration = 1
        self.enableOverlay()
        self.setOverlayOpacity(150)
        self._disable_parent_in_shown = True

        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(
            FINISHED,
            lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://appinfo.pisilinux.org'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("cancel"))

        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAlwaysOff)

        self.webView.page().setLinkDelegationPolicy(
            QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.showFullImage)

        self.tabWidget.removeTab(0)

        self.busy = QProgressIndicator(self, "white")
        self.busy.setMaximumSize(QSize(48, 48))
        self.webLayout.addWidget(self.busy)
        self.busy.hide()

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.noconnection.hide()
        self.parent = parent

    def showFullImage(self, url):
        PreviewDialog(self, url)

    def showPage(self, addr):
        if network_available():
            self.webView.load(QUrl(addr))
        else:
            self._sync_template(status=False)
        self.animate(start=BOTCENTER, stop=MIDCENTER)

    def getFiles(self):
        return self.iface.getPackageFiles(str(self.packageName.text()))

    def getFilesFinished(self):
        self.filesList.addItems(self._filesThread.get())
        self.filesList.sortItems()

    def _tabSwitched(self, index):
        if index == 0 and self.tabWidget.count() > 1:
            if self.filesList.count() == 0:
                self._filesThread.start()

    def _sync_template(self, status, package='', summary='', description=''):
        def _replace(key, value):
            self.webView.page().mainFrame().evaluateJavaScript(\
                    '%s.innerHTML="%s";' % (key, value))

        self.busy.hide()
        self.busy.stopAnimation()

        if status:
            _replace('title', package)
            _replace('summary', summary)
            _replace('description', description)
            self.webWidget.show()
            self.noconnection.hide()
        else:
            self.noconnection.show()
            self.webWidget.hide()

        reset_proxy_settings()

    def showPackageDetails(self,
                           package,
                           installed,
                           summary='',
                           description=''):
        self.packageName.setText(package)
        self.filesList.clear()

        self.tabWidget.insertTab(0, self.packageFiles, i18n('Package Files'))
        self.tabWidget.currentChanged.connect(self._tabSwitched)

        if config.USE_APPINFO:
            self.webView.loadFinished.connect(lambda x: \
                    self._sync_template(x, package, summary, description))

            if network_available():
                set_proxy_settings()
                self.webWidget.hide()
                self.busy.show()
                self.busy.startAnimation()
                self.webView.load(QUrl('%s/?p=%s' % (self._as, package)))
            else:
                self._sync_template(status=False)
        else:
            self.tabWidget.removeTab(1)
            self._filesThread.start()

        if not installed:
            self.tabWidget.removeTab(0)
            self.tabWidget.currentChanged.disconnect(self._tabSwitched)

        self.animate(start=BOTCENTER, stop=MIDCENTER)

    def _hide(self):
        self.busy.stopAnimation()
        try:
            self.webView.loadFinished.disconnect()
        except:
            pass
        self.animate(start=MIDCENTER, stop=BOTCENTER, direction=OUT)
예제 #22
0
class Widget(QWidget, ScreenWidget):
    name = "timeSetup"

    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_DateTimeWidget()
        self.ui.setupUi(self)
        self.timer = QTimer(self)
        self.from_time_updater = True
        self.is_date_changed = False

        self.current_zone = ""

        self.tz_dict = {}
        self.continents = []
        self.countries = []

        for country, data in yali.localedata.locales.items():
            if country == ctx.lang:
                if data.has_key("timezone"):
                    ctx.installData.timezone = data["timezone"]

        # Append continents and countries the time zone dictionary
        self.createTZDictionary()

        # Sort continent list
        self.sortContinents()

        # Append sorted continents to combobox
        self.loadContinents()

        # Load current continents country list
        self.getCountries(self.current_zone["continent"])

        # Highlight the current zone
        self.index = self.ui.continentList.findText(
            self.current_zone["continent"])
        self.ui.continentList.setCurrentIndex(self.index)

        self.index = self.ui.countryList.findText(self.current_zone["country"])
        self.ui.countryList.setCurrentIndex(self.index)

        # Initialize widget signal and slots
        self.__initSignals__()

        self.ui.calendarWidget.setDate(QDate.currentDate())

        self.pthread = None
        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.timer.start(1000)

        ctx.mainScreen.currentLanguageChanged.connect(self.retranslateUi)
        ctx.mainScreen.currentLanguageChanged.connect(self.changeCountry)
        ctx.mainScreen.currentLanguageChanged.connect(self.updateClock)
        self.ui.countryList.currentIndexChanged[int].connect(
            self.setWidgetDateTime)

    def changeCountry(self):
        data = yali.localedata.locales[ctx.lang.split("_")[0]]

        if data.has_key("timezone"):
            ctx.installData.timezone = data["timezone"]

        # Append continents and countries the time zone dictionary
        self.createTZDictionary()

        # Sort continent list
        self.sortContinents()

        # Append sorted continents to combobox
        self.loadContinents()

        # Load current continents country list
        self.getCountries(self.current_zone["continent"])

        # Highlight the current zone
        self.index = self.ui.continentList.findText(
            self.current_zone["continent"])
        self.ui.continentList.setCurrentIndex(self.index)

        self.index = self.ui.countryList.findText(self.current_zone["country"])
        self.ui.countryList.setCurrentIndex(self.index)

    def setWidgetDateTime(self, index):
        tz = str(self.ui.countryList.itemData(index))
        currentDateTime = QDateTime.currentDateTimeUtc().toTimeZone(
            QTimeZone(tz))

        self.ui.calendarWidget.setDate(currentDateTime.date())
        self.ui.timeEdit.setDateTime(currentDateTime)

    def __initSignals__(self):
        self.ui.timeEdit.timeChanged[QTime].connect(self.timerStop)
        self.ui.calendarWidget.dateChanged.connect(self.dateChanged)
        self.timer.timeout.connect(self.updateClock)
        self.ui.continentList.activated[str].connect(self.getCountries)

    def createTZDictionary(self):
        tz = TimeZoneList()
        zones = [x.timeZone for x in tz.getEntries()]
        zones.sort()

        for zone in zones:
            split = zone.split("/")

            # Human readable continent names
            continent_pretty_name = split[0].replace("_", " ")
            continent_pretty_name = continent_pretty_name

            # Some country names can be like Argentina/Catamarca so this fixes the splitting problem
            # caused by zone.split("/")
            #
            # Remove continent info and take the rest as the country name
            split.pop(0)
            country_pretty_name = " / ".join(split)

            # Human readable country names
            country_pretty_name = country_pretty_name.replace("_", " ")

            # Get current zone
            if zone == ctx.installData.timezone:
                self.current_zone = {
                    "continent": continent_pretty_name,
                    "country": country_pretty_name
                }

            # Append to dictionary
            if self.tz_dict.has_key(continent_pretty_name):
                self.tz_dict[continent_pretty_name].append(
                    [country_pretty_name, zone])
            else:
                self.tz_dict[continent_pretty_name] = [[
                    country_pretty_name, zone
                ]]

    def sortContinents(self):
        for continent in self.tz_dict.keys():
            self.continents.append(continent)
        self.continents.sort()

    def loadContinents(self):
        for continent in self.continents:
            self.ui.continentList.addItem(continent)

    def getCountries(self, continent):
        # Countries of the selected continent
        countries = self.tz_dict[str(continent)]

        self.ui.countryList.clear()

        for country, zone in countries:
            self.ui.countryList.addItem(country, zone)
            self.countries.append(country)

    def dateChanged(self):
        self.is_date_changed = True

    def timerStop(self):
        if self.from_time_updater:
            return
        # Human action detected; stop the timer.
        self.timer.stop()

    def updateClock(self):

        # What time is it ?
        cur = QTime.currentTime()

        self.from_time_updater = True
        self.ui.timeEdit.setTime(cur)
        self.from_time_updater = False

    def shown(self):
        self.timer.start(1000)

        if ctx.flags.install_type == ctx.STEP_BASE:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.setWidgetDateTime(self.ui.countryList.currentIndex())

    def dummy(self):
        pass

    def setTime(self):
        ctx.interface.informationWindow.update(
            _("General", "Adjusting time settings"))
        date = self.ui.calendarWidget.date()
        time = self.ui.timeEdit.time()
        args = "%02d%02d%02d%02d%04d.%02d" % (date.month(), date.day(),
                                              time.hour(), time.minute(),
                                              date.year(), time.second())

        # Set current date and time
        ctx.logger.debug("Date/Time setting to %s" % args)
        yali.util.run_batch("date", [args])

        # Sync date time with hardware
        ctx.logger.debug("YALI's time is syncing with the system.")
        yali.util.run_batch("hwclock", ["--systohc"])
        ctx.interface.informationWindow.hide()

    def execute(self):
        if not self.timer.isActive() or self.is_date_changed:
            QTimer.singleShot(500, self.setTime)
            self.timer.stop()

        index = self.ui.countryList.currentIndex()
        ctx.installData.timezone = self.ui.countryList.itemData(index)
        ctx.logger.debug("Time zone selected as %s " %
                         ctx.installData.timezone)

        if ctx.flags.install_type == ctx.STEP_BASE:
            #FIXME:Refactor hacky code
            ctx.installData.rootPassword = ctx.consts.default_password
            ctx.installData.hostName = yali.util.product_release()
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden,
                               ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
                return True
            else:
                self.pds_messagebox.setMessage(
                    _("General", "Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True

    def startInit(self):
        self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)

    def startStorageInitialize(self):
        ctx.storageInitialized = yali.storage.initialize(
            ctx.storage, ctx.interface)
        self.initFinished()

    def initFinished(self):
        self.pds_messagebox.animate(start=CURRENT, stop=CURRENT, direction=OUT)
        disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
        if ctx.storageInitialized:
            if len(disks) == 1:
                ctx.storage.clearPartDisks = [disks[0].name]
                ctx.mainScreen.step_increment = 2
            else:
                ctx.mainScreen.step_increment = 1
            ctx.mainScreen.slotNext(dry_run=True)
        else:
            ctx.mainScreen.enableBack()

    def retranslateUi(self):
        self.ui.retranslateUi(self)
예제 #23
0
    def shown(self):
        self.timer.start(1000)

        if ctx.flags.install_type == ctx.STEP_BASE:
            self.pthread = PThread(self, self.startInit, self.dummy)
예제 #24
0
class WebDialog(PAbstractBox, Ui_WebDialog):
    def __init__(self, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)

        self.iface = parent.iface

        # PDS Settings
        self._animation = 1
        self._duration = 400
        self.enableOverlay()
        self._disable_parent_in_shown = True

        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(FINISHED, lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://onurguzel.com/appinfo'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(KIcon("dialog-close"))

        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)

        self.webView.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.redirectLinks)

        self.tabWidget.removeTab(0)

        self.busy = QProgressIndicator(self, "white")
        self.busy.setMaximumSize(QSize(48, 48))
        self.webLayout.addWidget(self.busy)
        self.busy.hide()

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.filterLine.setListWidget(self.filesList)
        self.noconnection.hide()
        self.parent = parent

    def redirectLinks(self, url):
        if url.hasFragment():
            if url.fragment() == 'login':
                self.showLogin()
        else:
            PreviewDialog(self, url)

    def showLogin(self):
        self._hide()
        self.parent.settingsDialog.show()
        self.parent.settingsDialog.tabWidget.setCurrentIndex(4)

    def showPage(self, addr):
        if network_available():
            self.webView.load(QUrl(addr))
        else:
            self._sync_template(status = False)
        self.animate(start = BOTCENTER, stop = MIDCENTER)

    def getFiles(self):
        return self.iface.getPackageFiles(str(self.packageName.text()))

    def getFilesFinished(self):
        self.filesList.addItems(self._filesThread.get())
        self.filesList.sortItems()

    def _tabSwitched(self, index):
        if index == 0 and self.tabWidget.count() > 1:
            if self.filesList.count() == 0:
                self._filesThread.start()

    def _sync_template(self, status, package = '', summary = '', description = ''):
        def _replace(key, value):
            self.webView.page().mainFrame().evaluateJavaScript(\
                    '%s.innerHTML="%s";' % (key, value))

        self.busy.hide()
        self.busy.stopAnimation()

        if status:
            _replace('title', package)
            _replace('summary', summary)
            _replace('description', description)
            self.webWidget.show()
            self.noconnection.hide()
        else:
            self.noconnection.show()
            self.webWidget.hide()

        reset_proxy_settings()

    def showPackageDetails(self, package, installed, summary='', description=''):
        self.packageName.setText(package)
        self.key = config.PMConfig().getOpenDesktopKey()

        self.filesList.clear()
        self.webView.loadFinished.connect(lambda x: \
                self._sync_template(x, package, summary, description))

        if network_available():
            set_proxy_settings()
            self.webWidget.hide()
            self.busy.show()
            self.busy.startAnimation()
            params = {'p': package}
            if self.key:
                params['k'] = self.key
            self.webView.load(QUrl('%s/?%s' % (self._as, urlencode(params))))
        else:
            self._sync_template(status = False)

        self.tabWidget.insertTab(0, self.packageFiles, i18n('Package Files'))
        self.tabWidget.currentChanged.connect(self._tabSwitched)

        if not installed:
            self.tabWidget.removeTab(0)
            self.tabWidget.currentChanged.disconnect(self._tabSwitched)

        self.animate(start = BOTCENTER, stop = MIDCENTER)

    def _hide(self):
        self.busy.stopAnimation()
        try:
            self.webView.loadFinished.disconnect()
        except:
            pass
        self.animate(start = MIDCENTER, stop = BOTCENTER, direction = OUT)
예제 #25
0
class MainWidget(QWidget, PM, Ui_MainWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.setupUi(self)
        self.parent = parent

        self._selectedGroups = []
        self._preexceptions = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False

        # Search Thread
        self._searchThread = PThread(self, self.startSearch,
                                     self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon(("edit-find", "find")))
        self.initializeUpdateTypeList()

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)

        self.packageList.model().dataChanged.connect(self.statusChanged)
        self.packageList.updateRequested.connect(self.initialize)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(
            FINISHED, lambda: self.parent.statusBar().setVisible(
                not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(
            OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)

    def connectMainSignals(self):
        self.actionButton.clicked.connect(self.showBasket)
        self.checkUpdatesButton.clicked.connect(self.state.updateRepoAction)
        self.searchButton.clicked.connect(self.searchActivated)
        self.searchLine.textEdited.connect(self.searchLineChanged)
        self.searchLine.returnPressed.connect(self.searchActivated)
        self.searchLine.clearButtonClicked.connect(self.groupFilter)
        self.typeCombo.activated.connect(self.typeFilter)
        self.stateTab.currentChanged.connect(self.switchState)
        self.groupList.groupChanged.connect(self.groupFilter)
        self.groupList.groupChanged.connect(
            lambda: self.searchButton.setEnabled(False))
        self.packageList.select_all.clicked.connect(self.toggleSelectAll)
        self.statusUpdater.selectedInfoChanged.connect(self.emitStatusBarInfo)
        self.statusUpdater.selectedInfoChanged.connect(
            lambda message: self.selectionStatusChanged.emit(message))
        self.statusUpdater.finished.connect(self.statusUpdated)

    def initialize(self):
        waitCursor()
        self.searchLine.clear()
        self._started = False
        self._last_packages = None
        self.state.reset()
        self.initializePackageList()
        self.initializeGroupList()
        self.initializeStatusUpdater()
        self.statusChanged()
        self._selectedGroups = []
        self.packageList.select_all.setChecked(False)
        self.initializeBasket()
        self.searchLine.setFocus(True)
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0:
                QTimer.singleShot(0, \
                lambda: self.pdsMessageBox.showMessage(self.tr("All packages are up to date"), icon = "info"))
        if self.groupList.count() > 0:
            if self.state.inUpgrade():
                self.pdsMessageBox.hideMessage(force=True)
        restoreCursor()

    def initializeStatusUpdater(self):
        self.statusUpdater.calculate_deps = not self.state.state == self.state.ALL
        self.statusUpdater.setModel(self.packageList.model().sourceModel())

    def initializeBasket(self):
        waitCursor()
        self.basket.setModel(self.packageList.model().sourceModel())
        restoreCursor()

    def initializePackageList(self):
        self.packageList.model().reset()
        self.packageList.setPackages(self.state.packages())

        if self.completer:
            self.completer.deleteLater()
            del self.completer

        self.completer = QCompleter(self.state.packages(), self)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchLine.setCompleter(self.completer)

    def selectComponent(self, component):
        if not self.state.iface.operationInProgress():
            if self.basket.isVisible():
                self.basket._hide()

            self.stateTab.setCurrentIndex(1)
            self.switchState(self.state.INSTALL)

            if component in self.groupList._list:
                self.groupList.setCurrentItem(self.groupList._list[component])
                self.groupFilter()

    def updateSettings(self):
        self.packageList.showComponents = PMConfig().showComponents()
        self.packageList.showIsA = PMConfig().showIsA()
        self.packageList.setFocus()

    def searchLineChanged(self, text):
        self.searchButton.setEnabled(bool(text))
        if text == '':
            self.searchActivated()

    def statusUpdated(self):
        if self.statusUpdater.needsUpdate:
            self.statusUpdater.needsUpdate = False
            self.statusChanged()

    updatingStatus = pyqtSignal()

    def statusChanged(self):
        self.setActionEnabled()
        if self.statusUpdater.isRunning():
            self.statusUpdater.needsUpdate = True
        else:
            self.updatingStatus.emit()
            self.statusUpdater.start()

    def initializeGroupList(self):
        self.groupList.clear()
        self.groupList._list = {}
        self.groupList.setAlternatingRowColors(True)
        self.groupList.setIconSize(QSize(32, 32))
        self.groupList.setState(self.state)
        self.groupList.addGroups(self.state.groups())
        if self.state.state == self.state.UPGRADE:
            self.typeCombo.show()
        else:
            self.typeCombo.hide()
            self.state._typeFilter = 'normal'
        self.groupFilter()

    def packageFilter(self, text):
        self.packageList.model().setFilterRole(Qt.DisplayRole)
        self.packageList.model().setFilterRegExp(
            QRegExp(unicode(text), Qt.CaseInsensitive, QRegExp.FixedString))

    def typeFilter(self, index):
        if self.state.state == self.state.UPGRADE:
            filter = self.typeCombo.itemData(index).toString()
            if not self.state._typeFilter == filter:
                self.state._typeFilter = filter
                self.initializeGroupList()

    def groupFilter(self):
        waitCursor()
        self.packageList.resetMoreInfoRow()
        packages = self.state.groupPackages(self.groupList.currentGroup())
        self.packageList.model().setFilterRole(GroupRole)
        self.packageList.model().setFilterPackages(packages)
        self.packageList.scrollToTop()
        self.packageList.select_all.setChecked(
            self.groupList.currentGroup() in self._selectedGroups)
        restoreCursor()

    def searchActivated(self):
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0 and not self.searchUsed:
                return

        if not self.searchLine.text() == '':
            self.pdsMessageBox.showMessage(self.tr("Searching..."), busy=True)
            self.groupList.lastSelected = None
            self._searchThread.start()
            self.searchUsed = True
        else:
            self.state.cached_packages = None
            self.state.packages()
            self.searchUsed = False
            self.searchFinished()

    def searchFinished(self):
        if self.state.cached_packages == []:
            self.pdsMessageBox.showMessage(self.tr("No results found."),
                                           "dialog-information")
        else:
            self.pdsMessageBox.hideMessage()
        self.initializeGroupList()

    def startSearch(self):
        searchText = str(self.searchLine.text()).split()
        sourceModel = self.packageList.model().sourceModel()
        self.state.cached_packages = sourceModel.search(searchText)

    def setActionButton(self):
        self.actionButton.setEnabled(False)
        if self.state.state == self.state.ALL:
            menu = QMenu(self.actionButton)
            self.__install_action = menu.addAction(
                self.state.getActionIcon(self.state.INSTALL),
                self.state.getActionName(self.state.INSTALL), self.showBasket)
            self.__remove_action = menu.addAction(
                self.state.getActionIcon(self.state.REMOVE),
                self.state.getActionName(self.state.REMOVE), self.showBasket)
            self.actionButton.setMenu(menu)
        else:
            self.actionButton.setMenu(None)
        self.actionButton.setIcon(self.state.getActionIcon())
        self.actionButton.setText(self.state.getActionName())

    def actionStarted(self, operation):
        self.pdsMessageBox.hideMessage()
        self.progressDialog.reset()
        if not operation in [
                "System.Manager.updateRepository",
                "System.Manager.updateAllRepositories"
        ]:
            totalPackages = self.packageList.packageCount()
            self.operation.setTotalPackages(totalPackages)
            self.progressDialog.updateStatus(0, totalPackages,
                                             self.state.toBe())
        if self.isVisible():
            if operation in [
                    "System.Manager.updateRepository",
                    "System.Manager.updateAllRepositories"
            ]:
                self.progressDialog.repoOperationView()
            if self.basket.isVisible():
                self.basket._hide()
                QTimer.singleShot(0, self.progressDialog._show)
            else:
                self.progressDialog._show()

        if not self._started:
            self.progressDialog.disableCancel()
        else:
            self.progressDialog.enableCancel()

    repositoriesUpdated = pyqtSignal()

    def actionFinished(self, operation):
        if operation in ("System.Manager.installPackage",
                         "System.Manager.removePackage",
                         "System.Manager.updatePackage"):
            self.notifyFinished()

        if operation == "System.Manager.installPackage" and self._started:
            KIconLoader.updateAvailableIcons()
            self.summaryDialog.setDesktopFiles(self.operation.desktopFiles)
            self.summaryDialog.showSummary()

        if operation in ("System.Manager.updateRepository",
                         "System.Manager.updateAllRepositories"):
            self.repositoriesUpdated.emit()
        self.searchLine.clear()
        self.state.reset()
        self.progressDialog._hide()
        if not self.currentState == self.state.UPGRADE:
            self.switchState(self.currentState)
        self.initialize()

    def actionCancelled(self):
        self.progressDialog._hide()
        self.progressDialog.reset()
        self.switchState(self.currentState)
        self.groupFilter()

    def setActionEnabled(self):
        enabled = self.packageList.isSelected()
        self.actionButton.setEnabled(enabled)
        self.basket.setActionEnabled(enabled)

    def switchState(self, state):
        self.pdsMessageBox.hideMessage()
        self._states[state][1].setChecked(True)
        self.state.setState(state)
        self.currentState = state
        self._selectedGroups = []
        if not state == self.state.HISTORY:
            self.setActionButton()
            self.state.cached_packages = None
            if state == self.state.UPGRADE or (state == self.state.INSTALL and
                                               self.groupList.count() == 1):
                if not self._updatesCheckedOnce:
                    self._updatesCheckedOnce = self.state.updateRepoAction(
                        silence=True)
            self.checkUpdatesButton.setHidden(not state == self.state.UPGRADE)
            self.initialize()

    def emitStatusBarInfo(self, packages, packagesSize, extraPackages,
                          extraPackagesSize):
        self.selectionStatusChanged.emit(
            self.state.statusText(packages, packagesSize, extraPackages,
                                  extraPackagesSize))

    def setSelectAll(self, packages=None):
        if packages:
            self.packageList.reverseSelection(packages)

    def setReverseAll(self, packages=None):
        if packages:
            self.packageList.selectAll(packages)

    def toggleSelectAll(self, toggled):
        self._last_packages = self.packageList.model().getFilteredPackages()

        if toggled:
            if self.groupList.currentGroup() not in self._selectedGroups:
                self._selectedGroups.append(self.groupList.currentGroup())
            self.setReverseAll(self._last_packages)
        else:
            if self.groupList.currentGroup() in self._selectedGroups:
                self._selectedGroups.remove(self.groupList.currentGroup())
            self.setSelectAll(self._last_packages)

        self.packageList.setFocus()
        self.statusChanged()

    def showBasket(self):

        if self.basket.isVisible():
            return

        waitCursor()
        self.statusUpdater.wait()

        if self.currentState == self.state.ALL:
            action = {
                self.__remove_action: self.state.REMOVE,
                self.__install_action: self.state.INSTALL
            }.get(self.sender(), self.state.INSTALL)
            if action:
                if action == self.state.REMOVE:
                    installed_packages = self.state.iface.getInstalledPackages(
                    )
                    filtered_packages = filter(
                        lambda x: x not in installed_packages,
                        self.basket.model.selectedPackages())
                    if filtered_packages == self.basket.model.selectedPackages(
                    ):
                        restoreCursor()
                        QMessageBox(
                            self.tr("Select packages"),
                            self.
                            tr("You must select at least one installed package"
                               ), QMessageBox.Information, QMessageBox.Ok, 0,
                            0).exec_()
                        return
                    self.packageList.model().sourceModel().selectPackages(
                        filtered_packages, state=False)

                self.state.state = action

        self.basket._show()
        restoreCursor()

    def initializeUpdateTypeList(self):
        self.typeCombo.clear()
        UPDATE_TYPES = [[
            'normal',
            self.tr('All Updates'), ('system-software-update', 'ledgreen')
        ],
                        [
                            'security',
                            self.tr('Security Updates'),
                            ('security-medium', 'ledyellow')
                        ],
                        [
                            'critical',
                            self.tr('Critical Updates'),
                            ('security-low', 'ledred')
                        ]]

        for type in UPDATE_TYPES:
            self.typeCombo.addItem(KIcon(type[2]), type[1], QVariant(type[0]))
예제 #26
0
class WebDialog(PAbstractBox, Ui_WebDialog):
    finished = pyqtSignal()
    
    def __init__(self, parent):
        PAbstractBox.__init__(self, parent)
        self.setupUi(self)

        self.iface = backend.pm.Iface()   #parent.iface

        # PDS Settings
        self._animation = 1
        self._duration = 1
        self.enableOverlay()
        self.setOverlayOpacity(150)
        self._disable_parent_in_shown = True

        self.registerFunction(IN, lambda: parent.statusBar().hide())
        self.registerFunction(FINISHED, lambda: parent.statusBar().setVisible(not self.isVisible()))
        self._as = 'http://appinfo.pisilinux.org'
        self.cancelButton.clicked.connect(self._hide)
        self.cancelButton.setIcon(QIcon.fromTheme("cancel"))

        # Hide Scrollbars and context menu in webview
        self.webView.setContextMenuPolicy(Qt.NoContextMenu)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.webView.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)

        self.webView.page().setLinkDelegationPolicy(QtWebKitWidgets.QWebPage.DelegateAllLinks)
        self.webView.page().linkClicked.connect(self.showFullImage)

        self.tabWidget.removeTab(0)

        self.busy = QProgressIndicator(self, "white")
        self.busy.setMaximumSize(QSize(48, 48))
        self.webLayout.addWidget(self.busy)
        self.busy.hide()

        self._filesThread = PThread(self, self.getFiles, self.getFilesFinished)
        self.noconnection.hide()
        self.parent = parent
        
    def destroyed(self):
        self.finished.emit()

    def showFullImage(self, url):
        PreviewDialog(self, url)

    def showPage(self, addr):
        if network_available():
            self.webView.load(QUrl(addr))
        else:
            self._sync_template(status = False)
        self.animate(start = BOTCENTER, stop = MIDCENTER)

    def getFiles(self):
        files=self.iface.getPackageFiles(str(self.packageName.text()))
        self.filesList.addItems(files)
        self.filesList.sortItems()
        return files #self.iface.getPackageFiles(str(self.packageName.text()))

    def getFilesFinished(self):
        self.filesList.addItems(self._filesThread.get())
        self.filesList.sortItems()

    def _tabSwitched(self, index):
        if index == 0 and self.tabWidget.count() > 1:
            if self.filesList.count() == 0:
                self._filesThread.start()

    def _sync_template(self, status, package = '', summary = '', description = ''):
        def _replace(key, value):
            self.webView.page().mainFrame().evaluateJavaScript(\
                    '%s.innerHTML="%s";' % (key, value))

        self.busy.hide()
        self.busy.stopAnimation()

        if status:
            _replace('title', package)
            _replace('summary', summary)
            _replace('description', description)
            self.webWidget.show()
            self.noconnection.hide()
        else:
            self.noconnection.show()
            self.webWidget.hide()

        reset_proxy_settings()

    def showPackageDetails(self, package, installed, summary='', description=''):
        package = str(QVariant.value(package))
        summary = str(QVariant.value(summary))
        description = str(QVariant.value(description))
        
        self.packageName.setText(package)
        self.filesList.clear()
        
        
        self.tabWidget.insertTab(0, self.packageFiles, _translate("Packaga Manager",'Package Files'))
        self.tabWidget.currentChanged.connect(self._tabSwitched)

        if config.USE_APPINFO:
            self.webView.loadFinished.connect(lambda x: \
                    self._sync_template(x, package, summary, description))

            if network_available():
                set_proxy_settings()
                self.webWidget.hide()
                self.busy.show()
                self.busy.startAnimation()
                self.webView.load(QUrl('%s/?p=%s' % (self._as, package)))
            else:
                self._sync_template(status = False)
        else:
            self.tabWidget.removeTab(1)
        
        self._filesThread.start()

        if not installed:
            self.tabWidget.removeTab(0)
            self.tabWidget.currentChanged.disconnect(self._tabSwitched)

        self.animate(start = BOTCENTER, stop = MIDCENTER)

    def _hide(self):
        self.busy.stopAnimation()
        try:
            self.webView.loadFinished.disconnect()
        except:
            pass
        self.animate(start = MIDCENTER, stop = BOTCENTER, direction = OUT)
예제 #27
0
class MainWidget(QWidget, PM, Ui_MainWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)

        self.setupUi(self)
        self.parent = parent

        self._selectedGroups = []
        self._preexceptions  = []
        self._postexceptions = []

        self.state = StateManager(self)
        self.currentState = None
        self.completer = None
        self._updatesCheckedOnce = False

        #set style
        self._style = "/usr/share/kde4/apps/package-manager/data/style.qss"
        self.setStyleSheet(file(self._style).read())

        # Search Thread
        self._searchThread = PThread(self, self.startSearch, self.searchFinished)

        self.statusUpdater = StatusUpdater()
        self.basket = BasketDialog(self.state, self.parent)
        self._postexceptions.append(lambda: self.basket.setActionEnabled(True))
        self.searchButton.setIcon(KIcon("edit-find"))
        self.initializeUpdateTypeList()

        self.morewidgets = MoreWidgets(self.state, self.parent)
        self.morewidgets._show()

        self.webdialog = WebDialog(self.state, self.parent)

        model = PackageModel(self)
        proxy = PackageProxy(self)
        proxy.setSourceModel(model)
        self.packageList.setModel(proxy)
        self.packageList.setItemDelegate(PackageDelegate(self, self.parent))
        self.packageList.setColumnWidth(0, 32)

        self.connect(self.packageList.model(), SIGNAL("dataChanged(QModelIndex,QModelIndex)"), self.statusChanged)
        self.connect(self.packageList, SIGNAL("updateRequested()"), self.initialize)
        self.connect(self.morewidgets.randomPackageList, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.showWebdialog)

        self.updateSettings()
        self.setActionButton()

        self.operation = OperationManager(self.state)

        self.progressDialog = ProgressDialog(self.state, self.parent)
        self._preexceptions.append(self.progressDialog._hide)
        self.progressDialog.registerFunction(FINISHED, lambda: self.parent.statusBar().setVisible(not self.progressDialog.isVisible()))
        self.progressDialog.registerFunction(OUT, lambda: self.parent.statusBar().show())
        self.summaryDialog = SummaryDialog()

        self.connectOperationSignals()
        self.pdsMessageBox = PMessageBox(self.content)

    def connectMainSignals(self):
        self.connect(self.actionButton, SIGNAL("clicked()"), self.showBasket)
        self.connect(self.buttonMore, SIGNAL("clicked()"), self.showMoreWidgets)
        self.connect(self.checkUpdatesButton, SIGNAL("clicked()"), self.state.updateRepoAction)
        self.connect(self.searchButton, SIGNAL("clicked()"), self.searchActivated)
        self.connect(self.searchLine, SIGNAL("textEdited(const QString&)"), self.searchLineChanged)
        self.connect(self.searchLine, SIGNAL("returnPressed()"), self.searchActivated)
        self.connect(self.searchLine, SIGNAL("clearButtonClicked()"), self.groupFilter)
        self.connect(self.typeCombo, SIGNAL("activated(int)"), self.typeFilter)
        self.connect(self.stateTab, SIGNAL("currentChanged(int)"), self.switchState)
        self.connect(self.groupList, SIGNAL("groupChanged()"), self.groupFilter)
        self.connect(self.groupList, SIGNAL("groupChanged()"), lambda:self.searchButton.setEnabled(False))
        self.connect(self.packageList.select_all, SIGNAL("clicked(bool)"), self.toggleSelectAll)
        self.connect(self.statusUpdater, SIGNAL("selectedInfoChanged(int, QString, int, QString)"), self.emitStatusBarInfo)
        self.connect(self.statusUpdater, SIGNAL("selectedInfoChanged(QString)"), lambda message: self.emit(SIGNAL("selectionStatusChanged(QString)"), message))
        self.connect(self.statusUpdater, SIGNAL("finished()"), self.statusUpdated)

    def initialize(self):
        waitCursor()
        self.searchLine.clear()
        self._started = False
        self._last_packages = None
        self.state.reset()
        self.initializePackageList()
        self.initializeGroupList()
        self.initializeStatusUpdater()
        self.statusChanged()
        self._selectedGroups = []
        self.packageList.select_all.setChecked(False)
        self.initializeBasket()
        self.searchLine.setFocus(True)
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0:
                QTimer.singleShot(0, \
                lambda: self.pdsMessageBox.showMessage(i18n("All packages are up to date"), icon = "games-endturn"))
        if self.groupList.count() > 0:
            if self.state.inUpgrade():
                self.pdsMessageBox.hideMessage(force = True)
        restoreCursor()

    def initializeStatusUpdater(self):
        self.statusUpdater.calculate_deps = not self.state.state == self.state.ALL
        self.statusUpdater.setModel(self.packageList.model().sourceModel())

    def initializeBasket(self):
        waitCursor()
        self.basket.setModel(self.packageList.model().sourceModel())
        restoreCursor()

    def initializePackageList(self):
        self.packageList.model().reset()
        self.packageList.setPackages(self.state.packages())

        if self.completer:
            self.completer.deleteLater()
            del self.completer

        self.completer = QCompleter(self.state.packages(), self)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchLine.setCompleter(self.completer)

    def selectComponent(self, component):
        if not self.state.iface.operationInProgress():
            if self.basket.isVisible():
                self.basket._hide()

            self.stateTab.setCurrentIndex(1)
            self.switchState(self.state.INSTALL)

            if component in self.groupList._list:
                self.groupList.setCurrentItem(self.groupList._list[component])
                self.groupFilter()

    def updateSettings(self):

        self.packageList.showComponents = PMConfig().showComponents()
        self.packageList.showIsA = PMConfig().showIsA()
        self.packageList.setFocus()

    def searchLineChanged(self, text):
        self.searchButton.setEnabled(bool(text))
        if text == '':
            self.searchActivated()

    def statusUpdated(self):
        if self.statusUpdater.needsUpdate:
            self.statusUpdater.needsUpdate = False
            self.statusChanged()

    def statusChanged(self):
        self.setActionEnabled()
        if self.statusUpdater.isRunning():
            self.statusUpdater.needsUpdate = True
        else:
            self.emit(SIGNAL("updatingStatus()"))
            self.statusUpdater.start()

    def initializeGroupList(self):
        self.groupList.clear()
        self.groupList._list = {}
        self.groupList.setAlternatingRowColors(False)
        self.groupList.setIconSize(QSize(32, 32))
        self.groupList.setState(self.state)
        self.groupList.addGroups(self.state.groups())
        if self.state.state == self.state.UPGRADE:
            self.typeCombo.show()
        else:
            self.typeCombo.hide()
            self.state._typeFilter = 'normal'
        self.groupFilter()

    def packageFilter(self, text):
        self.packageList.model().setFilterRole(Qt.DisplayRole)
        self.packageList.model().setFilterRegExp(QRegExp(unicode(text), Qt.CaseInsensitive, QRegExp.FixedString))

    def typeFilter(self, index):
        if self.state.state == self.state.UPGRADE:
            filter = self.typeCombo.itemData(index).toString()
            if not self.state._typeFilter == filter:
                self.state._typeFilter = filter
                self.initializeGroupList()

    def groupFilter(self):
        waitCursor()
        self.packageList.resetMoreInfoRow()
        packages = self.state.groupPackages(self.groupList.currentGroup())
        self.packageList.model().setFilterRole(GroupRole)
        self.packageList.model().setFilterPackages(packages)
        self.packageList.scrollToTop()
        self.packageList.select_all.setChecked(self.groupList.currentGroup() in self._selectedGroups)
        restoreCursor()

    def searchActivated(self):
        if self.currentState == self.state.UPGRADE:
            if self.groupList.count() == 0 and not self.searchUsed:
                return

        if not self.searchLine.text() == '':
            self.pdsMessageBox.showMessage(i18n("Searching..."), busy = True)
            self.groupList.lastSelected = None
            self._searchThread.start()
            self.searchUsed = True
        else:
            self.state.cached_packages = None
            self.state.packages()
            self.searchUsed = False
            self.searchFinished()

    def searchFinished(self):
        if self.state.cached_packages == []:
            self.pdsMessageBox.showMessage(i18n("No results found."), "dialog-information")
        else:
            self.pdsMessageBox.hideMessage()
        self.initializeGroupList()

    def startSearch(self):
        searchText = str(self.searchLine.text()).split()
        sourceModel = self.packageList.model().sourceModel()
        self.state.cached_packages = sourceModel.search(searchText)

    def setActionButton(self):
        self.actionButton.setEnabled(False)
        if self.state.state == self.state.ALL:
            menu = QMenu(self.actionButton)
            self.__install_action = menu.addAction(self.state.getActionIcon(self.state.INSTALL),
                                                   self.state.getActionName(self.state.INSTALL),
                                                   self.showBasket)
            self.__remove_action = menu.addAction(self.state.getActionIcon(self.state.REMOVE),
                                                  self.state.getActionName(self.state.REMOVE),
                                                  self.showBasket)
            self.actionButton.setMenu(menu)
        else:
            self.actionButton.setMenu(None)
        self.actionButton.setIcon(self.state.getActionIcon())
        self.actionButton.setText(self.state.getActionName())

    def actionStarted(self, operation):
        self.pdsMessageBox.hideMessage()
        self.progressDialog.reset()
        if not operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            totalPackages = self.packageList.packageCount()
            extraPackages = self.packageList.extraPackagesCount()
            self.operation.setTotalPackages(totalPackages)
            self.operation.setExtraPackages(extraPackages)
            self.progressDialog.updateStatus(0, totalPackages, self.state.toBe())
        if self.isVisible():
            if operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
                self.progressDialog.repoOperationView()
            if self.basket.isVisible():
                self.basket._hide()
                QTimer.singleShot(0, self.progressDialog._show)
            else:
                self.progressDialog._show()

        if not self._started:
            self.progressDialog.disableCancel()
        else:
            self.progressDialog.enableCancel()

    def actionFinished(self, operation):
        if operation in ("System.Manager.installPackage",
                         "System.Manager.removePackage",
                         "System.Manager.updatePackage"):
            self.notifyFinished()

        if operation == "System.Manager.installPackage" and self._started:
            self.summaryDialog.setDesktopFiles(self.operation.desktopFiles)
            self.summaryDialog.showSummary()

        if operation in ("System.Manager.updateRepository",
                         "System.Manager.updateAllRepositories"):
            self.emit(SIGNAL("repositoriesUpdated()"))
        self.searchLine.clear()
        self.state.reset()
        self.progressDialog._hide()
        if not self.currentState == self.state.UPGRADE:
            self.switchState(self.currentState)
        self.initialize()

    def actionCancelled(self):
        self.progressDialog._hide()
        self.progressDialog.reset()
        self.switchState(self.currentState)
        self.groupFilter()

    def setActionEnabled(self):
        enabled = self.packageList.isSelected()
        self.actionButton.setEnabled(enabled)
        self.basket.setActionEnabled(enabled)

    def switchState(self, state):
        self.pdsMessageBox.hideMessage(force = True)
        self._states[state][1].setChecked(True)
        self.state.setState(state)
        self.currentState = state
        self._selectedGroups = []
        if not state == self.state.HISTORY:
            self.setActionButton()
            self.state.cached_packages = None
            if state == self.state.UPGRADE or (state == self.state.INSTALL and self.groupList.count() == 1):
                if not self._updatesCheckedOnce:
                    self._updatesCheckedOnce = self.state.updateRepoAction(silence = True)
            self.checkUpdatesButton.setHidden(not state == self.state.UPGRADE)
            self.initialize()
            # self.contentHistory.hide()
            self.content.show()
        # else:
            # self.contentHistory.show()
            # self.content.hide()

    def emitStatusBarInfo(self, packages, packagesSize, extraPackages, extraPackagesSize):
        self.emit(SIGNAL("selectionStatusChanged(QString)"), self.state.statusText(packages, packagesSize, extraPackages, extraPackagesSize))

    def setSelectAll(self, packages=None):
        if packages:
            self.packageList.reverseSelection(packages)

    def setReverseAll(self, packages=None):
        if packages:
            self.packageList.selectAll(packages)

    def toggleSelectAll(self, toggled):
        self._last_packages = self.packageList.model().getFilteredPackages()

        if toggled:
            if self.groupList.currentGroup() not in self._selectedGroups:
                self._selectedGroups.append(self.groupList.currentGroup())
            self.setReverseAll(self._last_packages)
        else:
            if self.groupList.currentGroup() in self._selectedGroups:
                self._selectedGroups.remove(self.groupList.currentGroup())
            self.setSelectAll(self._last_packages)

        # A hacky solution to repaint the list to take care of selection changes
        # FIXME Later
        self.packageList.setFocus()

        self.statusChanged()

    def showBasket(self):

        if self.basket.isVisible():
            return

        waitCursor()
        self.statusUpdater.wait()

        if self.currentState == self.state.ALL:
            action = {self.__remove_action:self.state.REMOVE,
                      self.__install_action:self.state.INSTALL}.get(self.sender(), self.state.INSTALL)
            if action:
                if action == self.state.REMOVE:
                    installed_packages = self.state.iface.getInstalledPackages()
                    filtered_packages = filter(lambda x: x not in installed_packages, self.basket.model.selectedPackages())
                    if filtered_packages == self.basket.model.selectedPackages():
                        restoreCursor()
                        QMessageBox(i18n("Select packages"),
                                    i18n("You must select at least one installed package"),
                                    QMessageBox.Information, QMessageBox.Ok, 0, 0).exec_()
                        return
                    self.packageList.model().sourceModel().selectPackages(filtered_packages, state = False)
                self.state.state = action

        self.basket._show()
        restoreCursor()


    def showMoreWidgets(self):
        if self.morewidgets.isVisible():
            return
        waitCursor()
        self.morewidgets._show()
        restoreCursor()

    def showWebdialog(self):
        packageName = str(unicode(self.morewidgets.randomPackageList.currentItem().text()))
        liste = []
        liste.append(packageName)
        print liste
        waitCursor()
        self.morewidgets._hide()
        #self.webdialog._show()
        restoreCursor()



        #self.packageList.setPackages(liste)
        self.packageList.selectAll(liste)
        #self.packageList.setItemDelegate(PackageDelegate(self, self, showDetailsButton=True))
        #self.packageList.setColumnWidth(0, 32)
        
        
        self.operation = OperationManager(self.state)
        reinstall = False
        answer = True
        actions = self.state.checkInstallActions(liste)
        if actions:
            answer = askForActions(actions,
                   i18n("Selected packages are already installed.<br>"
                        "If you continue, the packages will be reinstalled"),
                   i18n("Already Installed Packages"),
                   i18n("Installed Packages"))

        if not answer:
            self.initializePackageList()
            self.initializeBasket()            
            self.initializeStatusUpdater()  
            self.state.state = self.parent.cw.currentState
            self.parent.cw.initialize()     
            return

        if actions:
            reinstall = True
            
        if reinstall == False:
            self.initializeStatusUpdater() 
            self.initializeBasket()
            self.statusUpdated()
           
        self.showBasket()
        self.initializeBasket()    
        self.initializeStatusUpdater()    
        
    def initializeUpdateTypeList(self):
        self.typeCombo.clear()
        UPDATE_TYPES = [['normal', i18n('All Updates'), 'system-software-update'],
                        ['security', i18n('Security Updates'), 'security-medium'],
                        ['critical', i18n('Critical Updates'), 'security-low']]

        for type in UPDATE_TYPES:
            self.typeCombo.addItem(KIcon(type[2]), type[1], QVariant(type[0]))
예제 #28
0
class Widget(QWidget, ScreenWidget):
    name = "admin"

    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_RootPassWidget()
        self.ui.setupUi(self)
        self.intf = ctx.interface

        self.host_valid = True
        self.pass_valid = False

        if ctx.flags.install_type in [ctx.STEP_DEFAULT, ctx.STEP_LIVE]:
            self.pthread = PThread(self, self.startInit, self.dummy)

        self.pds_messagebox = PMessageBox(self)
        self.pds_messagebox.enableOverlay()

        self.connect(self.ui.pass1, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("textChanged(const QString &)"),
                     self.slotTextChanged)
        self.connect(self.ui.pass2, SIGNAL("returnPressed()"),
                     self.slotReturnPressed)
        self.connect(self.ui.hostname, SIGNAL("textChanged(const QString &)"),
                     self.slotHostnameChanged)

    def update(self):
        if self.host_valid and self.pass_valid:
            ctx.mainScreen.enableNext()
        else:
            ctx.mainScreen.disableNext()

    def shown(self):
        if ctx.installData.hostName:
            self.ui.hostname.setText(str(ctx.installData.hostName))
        else:
            # Use first added user's name as machine name if its exists
            release_hostname = yali.util.product_release()
            if self.ui.hostname.text() == '':
                self.ui.hostname.setText(release_hostname)

        if ctx.installData.rootPassword:
            self.ui.pass1.setText(ctx.installData.rootPassword)
            self.ui.pass2.setText(ctx.installData.rootPassword)

        self.update()
        self.checkCapsLock()
        self.ui.pass1.setFocus()

    def dummy(self):
        pass

    def execute(self):
        ctx.installData.rootPassword = unicode(self.ui.pass1.text())
        ctx.installData.hostName = unicode(self.ui.hostname.text())

        if ctx.flags.install_type in [ctx.STEP_DEFAULT, ctx.STEP_LIVE]:
            #FIXME:Refactor dirty code
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden,
                               ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
            else:
                self.pds_messagebox.setMessage(
                    _("Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True

    def startInit(self):
        self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)

    def startStorageInitialize(self):
        ctx.storageInitialized = yali.storage.initialize(
            ctx.storage, ctx.interface)
        self.initFinished()

    def initFinished(self):
        self.pds_messagebox.animate(start=CURRENT, stop=CURRENT, direction=OUT)
        disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
        if ctx.storageInitialized:
            if len(disks) == 1:
                ctx.storage.clearPartDisks = [disks[0].name]
                ctx.mainScreen.step_increment = 2
            else:
                ctx.mainScreen.step_increment = 1
            ctx.mainScreen.slotNext(dry_run=True)
        else:
            ctx.mainScreen.enableBack()

    def setCapsLockIcon(self, child):
        if type(child) == QLineEdit:
            if pardus.xorg.capslock.isOn():
                child.setStyleSheet("""QLineEdit {
                        background-image: url(:/gui/pics/caps.png);
                        background-repeat: no-repeat;
                        background-position: right;
                        padding-right: 35px;
                        }""")
            else:
                child.setStyleSheet("""QLineEdit {
                        background-image: none;
                        padding-right: 0px;
                        }""")

    def checkCapsLock(self):
        for child in self.ui.groupBox.children():
            self.setCapsLockIcon(child)

    def keyReleaseEvent(self, event):
        self.checkCapsLock()

    def slotTextChanged(self):

        password = str(self.ui.pass1.text())
        password_confirm = str(self.ui.pass2.text())

        if password and password == password_confirm:
            if len(password) < 4:
                self.intf.informationWindow.update(_('Password is too short.'),
                                                   type="error")
                self.pass_valid = False
            else:
                self.intf.informationWindow.hide()
                self.pass_valid = True
        else:
            self.pass_valid = False
            if password_confirm:
                self.intf.informationWindow.update(
                    _('Passwords do not match.'), type="error")

        if password.lower() == "root" or password_confirm.lower() == "root":
            self.pass_valid = False
            if password_confirm:
                self.intf.informationWindow.update(
                    _('Do not use your username as your password.'),
                    type="error")

        if self.pass_valid:
            self.intf.informationWindow.hide()

        self.update()

    def slotHostnameChanged(self, hostname):
        if len(hostname) > 64:
            self.host_valid = False
            self.intf.informationWindow.update(
                _('Hostname cannot be longer than 64 characters.'),
                type="error")
            self.update()
            return

        if not hostname.toAscii():
            self.host_valid = False
            self.update()
            return

        self.host_valid = yali.util.is_text_valid(hostname.toAscii())

        if not self.host_valid:
            self.intf.informationWindow.update(
                _('Hostname contains invalid characters.'), type="error")
        else:
            self.intf.informationWindow.hide()
        self.update()

    def slotReturnPressed(self):
        if ctx.mainScreen.isNextEnabled():
            ctx.mainScreen.slotNext()