Ejemplo n.º 1
0
    def __init__(self, parent=None):
        KStatusNotifierItem.__init__(self, parent)
        self.setTitle('synaptiks')
        self.setIconByName('synaptiks')
        self.setCategory(KStatusNotifierItem.Hardware)
        self.setStatus(KStatusNotifierItem.Passive)
        self.setup_actions()

        self._config = SynaptiksTrayConfiguration(self)

        try:
            self.touchpad = Touchpad.find_first(Display.from_qt())
        except Exception as error:
            # show an error message
            from synaptiks.kde.error import get_localized_error_message
            error_message = get_localized_error_message(error)
            options = KMessageBox.Options(KMessageBox.Notify |
                                          KMessageBox.AllowLink)
            KMessageBox.error(None, error_message, '', options)
            # disable all touchpad related actions
            for act in (self.touchpad_on_action, self.preferences_action):
                act.setEnabled(False)
            # disable synaptiks autostart, the user can still start synaptiks
            # manually again, if the reason of the error is fixed
            self._config.findItem('Autostart').setProperty(False)
            self._config.writeConfig()
        else:
            self.activateRequested.connect(self.show_configuration_dialog)
            # setup the touchpad manager
            self.setup_manager(self.touchpad)
Ejemplo n.º 2
0
 def unpackError(self, err):
     self.progress.setRange(0, 100)
     self.progress.reset()
     self.enableButtonOk(True)
     self.status.setText(i18n("Unpacking failed."))
     KMessageBox.error(self, i18n("An error occurred:\n\n%1",
         self.unpackJob.errorString()))
Ejemplo n.º 3
0
def dialogInputBox(message = _("Text"), ontType = "string"):
    if (ontType == "date"):
        parameters = ["zenity", "--calendar", "--title=" + PROGRAM_NAME, "--text=" + message, "--date-format=%Y-%m-%d"]

    else:
        parameters = ["kdialog", "--title", PROGRAM_NAME, "--inputbox", message]

    try:
        dialogProcess = subprocess.Popen(parameters, stdout=subprocess.PIPE)
        dialogProcess.wait()
        value = u""
        for line in iter(dialogProcess.stdout.readline, ''):
            value += toUnicode(line)

        # Cleaning last "\n".
        if (value[-1] == "\n"):
            value = value[:-1]

        print(toUtf8("dialogInputBox:%s" % value))

    except:
        value = None
        KMessageBox.error(None, "Zenity and KDialog are required to edit resources.")

    return value
Ejemplo n.º 4
0
    def onSendClick(self):
        for provider in self.providerpluginlist:
            if(provider.getObjectname() == self.ui.providerList.selectedItems()[0].text()):
                sms = provider
        if self.ui.smstext.toPlainText() != "":
            if self.ui.phonenr.text() != "":
                self.getLogin()
                try:
                    sms.setConfig(self.config)
                except Exception:
                    self.onConfigClick()
                    return
                sms.clearNrs()
                for nr in re.findall("(\+\d*)", self.ui.phonenr.text()):
                    sms.addNr(nr)
                sms.setText(self.ui.smstext.toPlainText())
                savenr = self.ui.phonenr.text()
                try:
                    sms.execute()
#                    self.notification.setText(i18n("Wurde erfolgreich an <i>%1</i> geschickt!").arg(savenr ))
#                    self.notification.setTitle("Erfolg!")
#                    self.notification.sendEvent()
                    KMessageBox.information(None, i18n("SMS sendet successfully to " + savenr + ". Service: "+sms.getProvidername()), i18n("Success!"))
                except Exception, error:
                    KMessageBox.error(None, i18n(error.message), i18n("Sendproblems"))
                self.ui.phonenr.clear()
                self.ui.smstext.clear()
            else:
                KMessageBox.error(None, i18n("Please fill in a phonenr"), i18n("Please fill in a phonenr"))
Ejemplo n.º 5
0
    def askForPIN(self):
        if "pin" in self.iface.capabilities(self.package)["modes"] and self.iface.requiresPIN(self.package, self.device):
            # Loop 3 times by default
            for c in range(self.pinDialog.maxTries):
                # Clear textbox
                self.pinDialog.setPassword("")
                if self.pinDialog.exec_():
                    # Clicked OK
                    pin = self.pinDialog.password()

                    # Send PIN to the card, returns True if PIN is valid.
                    if self.iface.sendPIN(self.package, self.device, str(pin)):
                        self.pin = str(pin)
                        self.ui.lineEditPIN.setText(self.pin)
                        return True
                else:
                    break

            # Verification failed for 3 times
            if c == self.pinDialog.maxTries-1:
                KMessageBox.error(self, i18n("You've typed the wrong PIN code for 3 times"))
                return False
            else:
                # Canceled
                return True

        else:
            # PIN is already entered or the backend doesn't support PIN operations
            return True
Ejemplo n.º 6
0
 def file2String(self, path):
     if(os.path.isfile(path)):
         f = open(path, 'r')
         return f.read()
     else:
         KMessageBox.error(None, i18n("No path on this file"), i18n("No path"))
         raise RuntimeError("No path")
Ejemplo n.º 7
0
def dialogList(parameters = [], message = _("Select")):
    value = label = None

    try:
        if parameters:
            parameters = ["kdialog", "--title", PROGRAM_NAME, "--radiolist", message] \
                            + parameters
            dialogProcess = subprocess.Popen(parameters, stdout=subprocess.PIPE)
            dialogProcess.wait()
            value = u""
            for line in iter(dialogProcess.stdout.readline, ''):
                value += toUnicode(line)

            # Cleaning last "\n".
            if (value[-1] == "\n"):
                value = value[:-1]

            try:
                label = toUnicode(parameters[parameters.index(value) + 1])

            except:
                label = toUnicode(value)

        print(toUtf8("dialogList:%s" % value))

    except:
        KMessageBox.error(None, "Zenity and KDialog are required to edit resources.")

    return value, label
    def init(self):
        self.translateUI()
        try:
            self.openCache(apt.progress.OpProgress())
        except ExceptionPkgCacheBroken:
            s = _("Software database is broken")
            t = _("It is impossible to install or remove any software. "
                  "Please use the package manager \"Adept\" or run "
                  "\"sudo apt-get install -f\" in a terminal to fix "
                  "this issue at first.")
            KMessageBox.error(self, t, s)
            sys.exit(1)
        self.updateLanguagesList()
        self.updateSystemDefaultListbox()

        if not self._cache.havePackageLists:
            yesText = _("_Update").replace("_", "&")
            noText = _("_Remind Me Later").replace("_", "&")
            yes = KGuiItem(yesText, "dialog-ok")
            no = KGuiItem(noText, "process-stop")
            text = "<big><b>%s</b></big>\n\n%s" % (
              _("No language information available"),
              _("The system does not have information about the "
                "available languages yet. Do you want to perform "
                "a network update to get them now? "))
            text = text.replace("\n", "<br />")
            res = KMessageBox.questionYesNo(self, text, "", yes, no)
            if res == KMessageBox.Yes:
                self.setEnabled(False)
                self.update()
                self.openCache(apt.progress.OpProgress())
                self.updateLanguagesList()
                self.setEnabled(True)
    def pkgChanges(self, mode):

        if mode == "install":
            items = self.ui.listViewLanguagesInst.selectedItems()
        else:
            items = self.ui.listViewLanguagesUninst.selectedItems()
            
        if len(items) == 1:
            elm = items[0]
            li = self._localeinfo.listviewStrToLangInfoMap[unicode(elm.text())]
            langPkg = li.languagePkgList["languagePack"]
            if langPkg.available:
                if (mode == "install") and (not langPkg.installed):
                    langPkg.doChange = self.ui.checkBoxTr.isChecked()
                elif (mode == "uninstall") and langPkg.installed:
                    langPkg.doChange = True
            try:
                self._cache.tryChangeDetails(li)
                for langPkg in li.languagePkgList.values():
                  langPkg.doChange = False
            except ExceptionPkgCacheBroken:
                s = _("Software database is broken")
                t = _("It is impossible to install or remove any software. "
                      "Please use the package manager \"Adept\" or run "
                      "\"sudo apt-get install -f\" in a terminal to fix "
                      "this issue at first.")
                KMessageBox.error(self, t, s)
                sys.exit(1)

        (to_inst, to_rm) = self._cache.getChangesList()
        if len(to_inst) == len(to_rm) == 0:
            return
        # first install
        self.setCursor(Qt.WaitCursor)
        self.setEnabled(False)
        self.run_pkg_manager(to_inst,to_rm)
        self.setCursor(Qt.ArrowCursor)
        self.setEnabled(True)
        
#        kdmscript = "/etc/init.d/kdm"
#        if os.path.exists("/var/run/kdm.pid") and os.path.exists(kdmscript):
#            subprocess.call(["invoke-rc.d","kdm","reload"])

        #self.run_pkg_manager(to_inst, to_rm)

        if self.returncode == 0:
            if (mode == "install"):
                KMessageBox.information( self, _("All selected components have now been installed for %s.  Select them from Country/Region & Language.") % unicode(items[0].text()), _("Language Installed") )
            elif (mode == "uninstall"):
                KMessageBox.information( self, _("Translations and support have now been uninstalled for %s.") % unicode(items[0].text()), _("Language Uninstalled") )
            # Resync the cache to match packageManager changes, then update views
            self._cache.open(None)
            self.updateLanguagesList()
            self.updateSystemDefaultListbox()
            if mode == "install":
                self.checkInstallableComponents()
        else:
            KMessageBox.sorry(self, _("Failed to set system language."), _("Language Not Set"))
            self._cache.clear() # undo all selections
Ejemplo n.º 10
0
 def shown(self):
     if ctx.sources:
         self.creator(ctx.sources)
     else:
         KMessageBox.error(
             self,
             "There isn't any Windows User Sources to migrate! Check your Windows Partition..."
         )
Ejemplo n.º 11
0
 def show_error_dialog(self, message, details=None):
     """
     Convenience method for showing an error dialog.
     """
     if details is None:
         KMessageBox.error(None, message)
     else:
         KMessageBox.detailedError(None, message, details)
Ejemplo n.º 12
0
    def applyChanges(self):
        ui = self.ui
        connectionName = unicode(ui.lineConnectionName.text())

        try:
            self.iface.updateConnection(self.lastEditedPackage, connectionName, self.collectDataFromUI())
        except Exception, e:
            KMessageBox.error(self.baseWidget, unicode(e))
            return
Ejemplo n.º 13
0
 def __call__(self):
     try:
         return self.f()
     except _HandledException:
         raise
     except Exception, e:
         txt = "".join(traceback.format_exception(*sys.exc_info()))
         KMessageBox.error(None, txt, i18n("Error in action '{}'").format(self.f.__name__))
         raise _HandledException(txt)
Ejemplo n.º 14
0
    def deleteBackup(self):
	global backupInstance
	boxresult = KMessageBox.questionYesNo(None, "Really delete backup '" + self.backupList.currentText() + "'?")
	if boxresult == KMessageBox.Yes:
	  resulttype, result = backupInstance.deleteBackup( str(self.backupList.currentText()) )
	  if result != "ERROR":
	    KMessageBox.information(None, self.backupList.currentText() + ' deleted.')
	    self.backupList.removeItem(self.backupList.currentIndex())
	  else:
	    KMessageBox.error(None, result[0]['message'])
Ejemplo n.º 15
0
 def handler(package, exception, args):
     if exception:
         if self.ui.checkToggler.isChecked():
             self.ui.checkToggler.setChecked(False)
         else:
             self.ui.checkToggler.setChecked(True)
         if "Comar.PolicyKit" in exception._dbus_error_name:
             KMessageBox.error(self, i18n("Access denied."))
         else:
             KMessageBox.error(self, unicode(exception))
Ejemplo n.º 16
0
    def __fail(self, message=None):
        '''Handle Failed Install Gracefully'''

        logging.exception('Installation failed.')
        self.__backend.unmount()
        self.progress_bar.hide()
        if not message:
            message = _('Installation failed.')
        KMessageBox.error(self.__mainWindow, message)
        sys.exit(1)
Ejemplo n.º 17
0
 def convertAbsoluteToRelative(self):
     """
     Converts the selected music expression or all toplevel expressions to \relative ones.
     """
     text, start = self.doc.selectionOrDocument()
     try:
         ly.tools.absoluteToRelative(text, start).applyToCursor(EditCursor(self.doc.doc))
     except ly.NoMusicExpressionFound:
         KMessageBox.error(
             self.doc.app.mainwin, i18n("Please select a music expression, enclosed in << ... >> or { ... }.")
         )
Ejemplo n.º 18
0
    def useBackup(self):
        global backupInstance, config, mainwin, backupwin
	resulttype, result = backupInstance.login( config.username, config.password, self.backupList.currentText() )
	if resulttype != "ERROR":
	  self.hide()
	  backupwin = BackupWindow()
	  mainwin = backupwin
	  mainwin.show()
	  backupwin.updateVolumeName( self.backupList.currentText() )
	else:
	  KMessageBox.error(None, result[0]['message'])
Ejemplo n.º 19
0
 def unpackFinished(self, exitCode, exitStatus):
     self.progress.setRange(0, 100)
     self.progress.reset()
     self.enableButtonOk(True)
     if exitStatus == QProcess.NormalExit and exitCode == 0:
         self.status.setText(i18n("Unpacking finished."))
         self.info.lilypond.setText(self.lilypond)
         KDialog.done(self, KDialog.Accepted)
     else:
         self.status.setText(i18n("Unpacking failed."))
         KMessageBox.error(self, i18n("An error occurred:\n\n%1",
             str(self.unpackJob.readAllStandardOutput())))
Ejemplo n.º 20
0
    def applyChanges(self):
        ui = self.ui
        connectionName = unicode(ui.lineProfileName.text())
        connections = self.iface.connections(self.lastEditedPackage)

        if (self.isEditBox) or (not connectionName in connections):
            try:
                self.iface.updateConnection(self.lastEditedPackage, connectionName, self.collectDataFromUI())
            except Exception, e:
                KMessageBox.error(self.baseWidget, unicode(e))
                ui.lineProfileName.setFocus()
                return
Ejemplo n.º 21
0
 def __call__(self):
     try:
         return self.f()
     except _HandledException:
         raise
     except Exception as e:
         txt = "".join(traceback.format_exception(*sys.exc_info()))
         # TODO: Use the i18n() wrapper here. Unfortunately, Python3 currently
         # says "TypeError: i18n(): argument 1 has unexpected type 'str'",
         # and that is rather unfortunate for the catch-all handler.
         KMessageBox.error(None, txt, "Error in action '{}'".format(self.f.__name__))
         raise _HandledException(txt)
Ejemplo n.º 22
0
    def __init__(self, datadir, options, file="", parent=None, name=None,
                 modal=0, fl=0):
        GDebiKDEDialog.__init__(self,parent)
        GDebiCommon.__init__(self,datadir,options,file)
        # load the icon
        self.setWindowIcon(KIcon("application-x-deb"))
        # first, we load all the default descriptions -- pyuic doesn't use
        # gettext as default (FIXME, copy code from language-selector)
        self.textLabel1.setText(_("Package:"))
        self.textLabel1_2.setText(_("Status:"))
        self.detailsButton.setText(_("Details"))
        self.tabWidget2.setTabText(0,_("Description"))
        self.tabWidget2.setTabText(1,_("Details"))
        self.tabWidget2.setTabText(2,_("Included Files"))
        self.cancelButton.setText(__("kdelibs","&Cancel"))
        self.installButton.setText(_("&Install Package"))
        self.downloadButton.setText(_("&Download Package"))
        self.DetailsVersionLabel.setText(_("<b>Version:</b>"))
        self.DetailsMaintainerLabel.setText(_("<b>Maintainer:</b>"))
        self.DetailsPriorityLabel.setText(_("<b>Priority:</b>"))
        self.DetailsSectionLabel.setText(_("<b>Section:</b>"))
        self.DetailsSizeLabel.setText(_("<b>Size:</b>"))
        # translation finished
        self.setDisabled(True)
        self.PackageProgressBar.setEnabled(True)
        self.detailsButton.hide()
        self.downloadButton.hide()
        self.installButton.setIcon(KIcon("dialog-ok"))
        self.cancelButton.setIcon(KIcon("dialog-cancel"))
        self.show()
        self.kapp = KApplication.kApplication() #incidently, this stops it crashing on quit, no idea why, jriddell
        self.kapp.processEvents() #run because openCache takes a while to do its thing
        self.cprogress = CacheProgressAdapter(self.PackageProgressBar)
        if not self.openCache():
            KMessageBox.error(self, '<b>' + self.error_header + '</b><br>' + self.error_body,
                self.error_header)
            sys.exit(1)
        # try to open the file
        if file != "" and os.path.exists(file):
            self.open(file)
        else:
            header = _("The package file does not exist")
            body = _("A nonexistent file has been selected for installation. Please select an existing .deb package file.")
            KMessageBox.error(self, '<b>' + header + '</b><br>' + body, header)
            sys.exit(1)

        self.setEnabled(True)
        self.PackageProgressBar.hide()
        self.connect(self.cancelButton, SIGNAL("clicked()"), self.cancelButtonClicked)
        self.connect(self.installButton, SIGNAL("clicked()"), self.installButtonClicked)
        self.connect(self.downloadButton, SIGNAL("clicked()"), self.downloadButtonClicked)
        self.connect(self.detailsButton, SIGNAL("clicked()"), self.detailsButtonClicked)
Ejemplo n.º 23
0
    def addBackup(self):
	global backupInstance, config
	text, result = QtGui.QInputDialog.getText(self, 'Add Backup', 'Backup Name:')
	if result:
	  resulttype, result = backupInstance.addBackup( str(text), config.workstation_id, config.workstation_name )
	  if resulttype != "ERROR":
	    KMessageBox.information(None, text + ' added.')
	    self.backupList.addItem(text)
	  else:
	    messagetext = result[0]['message']
	    if messagetext == "":
	      messagetext = result[0]['label']
	    KMessageBox.error(None, messagetext)
Ejemplo n.º 24
0
    def loginSubmit(self):
	self.loginButton.setEnabled(False)
	global backupInstance, config
	backupInstance = Provider.getInstance( self.providerBox.currentText(), config )
	resulttype, result = backupInstance.login( str(self.usernameEdit.text()), str(self.passwordEdit.text()), config.backupName )
	if resulttype != "ERROR":
	  # success
	  self.hide()
	  
	  global mainwin, choosebackuplocation
	  choosebackuplocation = BackupLocationWindow()
	  choosebackuplocation.show()
	  mainwin = choosebackuplocation
	else:
	  KMessageBox.error(None, result[0]['message'])
	
	self.loginButton.setEnabled(True)
Ejemplo n.º 25
0
    def doExport(self, exporter):
        filePath = exporter.getFilePath()

        if filePath != None:
            # if a path is set, than it is configurable
            fileTypes = exporter.getFileTypes()
            if fileTypes:
                filterStr = ' '.join(fileTypes)
            else:
                filterStr = ''
            # TODO make remote url work
            fileDialog = KFileDialog(KUrl(filePath), filterStr, self)
            fileDialog.setSelection(os.path.basename(filePath))
            fileDialog.setCaption(i18n('Export Vocabulary'))
            #fileDialog.setConfirmOverwrite(True)
            fileDialog.setOperationMode(KFileDialog.Saving)
            if fileDialog.exec_() != KFileDialog.Accepted:
                return

            filePath = unicode(fileDialog.selectedFile())

            # TODO setConfirmOverwrite() doesn't work right now, so...
            while filePath and os.path.exists(filePath) \
                and KMessageBox.warningYesNo(self,
                    i18n('The given file "%1" already exists. Overwrite?',
                        os.path.basename(filePath))) == KMessageBox.No:

                fileDialog.setSelection(os.path.basename(filePath))
                if fileDialog.exec_() != KFileDialog.Accepted:
                    return
                filePath = unicode(fileDialog.selectedFile())

            if not filePath:
                return

            exporter.setFilePath(unicode(filePath))

        exporter.setEntries(self.vocabularyModel.getVocabulary())
        try:
            if not exporter.write():
                KMessageBox.error(self, i18n('Error saving file'))
        except Exception, e:
            KMessageBox.error(self, i18n('Error saving file: %1', unicode(e)))
            print unicode(e).encode(locale.getpreferredencoding())
Ejemplo n.º 26
0
def convertLy(mainwin):
    """
    Run the current document through convert-ly.
    """
    doc = mainwin.currentDocument()
    text = doc.text()
    docVersion = ly.version.getVersion(text)
    lilyVersion = ly.version.LilyPondInstance(lilyPondCommand()).version()
    
    if not docVersion:
        KMessageBox.sorry(mainwin, i18n(
            "Can't determine the LilyPond version of the current document."
            " Please add a \\version statement with the correct version."))
    elif not lilyVersion:
        KMessageBox.sorry(mainwin, i18n(
            "Can't determine the version of LilyPond. "
            "Please check your LilyPond installation."))
    elif docVersion >= lilyVersion:
        KMessageBox.information(mainwin, i18n(
            "This LilyPond document is already up-to-date."))
    else:
        # Ok, let's run convert-ly.
        # We add the from-version. Only in that case convert-ly wants to
        # read from stdin.
        try:
            out, err = Popen(
                (convertLyCommand(), "-f", str(docVersion), "-"),
                stdin=PIPE, stdout=PIPE, stderr=PIPE
                ).communicate(text.encode('utf8'))
            if out:
                doc.setText("{0}\n\n%{{\n{1}\n%}}\n".format(out.decode('utf8'), err.decode('utf8')))
                KMessageBox.information(mainwin, i18n(
                 "The document has been processed with convert-ly. You'll find "
                 "the messages of convert-ly in a comment block at the end. "
                 "You still may have to edit some parts manually."))
            else:
                msg = "<br><br>" + err.decode('utf8').replace('\n', '<br>')
                KMessageBox.information(mainwin, i18n(
                 "The document has been processed with convert-ly, but "
                 "remained unchanged. This is the message given by "
                 "convert-ly: %1", msg))
        except OSError as e:
            msg = unicode(e)
            KMessageBox.error(mainwin, i18n("Could not start convert-ly: %1", msg))
Ejemplo n.º 27
0
	def search(self):
		global result
		global s
		if self.searchBox.text() == "":
			KMessageBox.error(None,"Search for something...")
			return
		else:
			self.resultList.clear()
			result = s.search(str(self.searchBox.text()))
			if not result:
				self.resultList.addItem("Nothing found :(")
			else:
				for i in range(0,len(result.playlist.tracks)):
					tracktext = self.formatResult(result.playlist.tracks[i])
				#	tracktext = str(track)
					self.resultList.addItem(tracktext)
					
				#s.play(result.playlist.tracks.)
		return
Ejemplo n.º 28
0
    def __init__(self, args):
        self.getLogin()
        self.providerPluginManager = PluginManager("providerplugins","providerplugins", providerplugins.Provider.Provider)
        aboutData = KAboutData (
            "Wrapper", 
            "blubb", 
            ki18n("Wrapper for kontact"), 
            "sdaf", 
            ki18n("Displays a KMessageBox popup"), 
            KAboutData.License_GPL, 
            ki18n("(c) 2010"), 
            ki18n("This is a wrapper for kontact to access the multimobileservice"), 
            "http://puzzle.ch", 
            "*****@*****.**"
        )
 
        KCmdLineArgs.init(sys.argv, aboutData)
        
        cmdoptions = KCmdLineOptions()
        cmdoptions.add("nr <speed>", ki18n("The phone nr"))
        cmdoptions.add("smsfile <file>", ki18n("The smsfile"))
        cmdoptions.add("smstext <text>", ki18n("The smstext"))
        cmdoptions.add("plugin <string>", ki18n("The pluginname"))
        KCmdLineArgs.addCmdLineOptions(cmdoptions)
        app = KApplication()
        lineargs = KCmdLineArgs.parsedArgs()
        plugin = self.getRightPlugin(lineargs.getOption("plugin"))
        plugin.addNr(lineargs.getOption("nr"))
        if lineargs.getOption("smsfile") != "":
            plugin.setText(self.file2String(lineargs.getOption("smsfile")))
        elif lineargs.getOption("smstext") != "":
            plugin.setText(lineargs.getOption("smstext"))
        else:
            KMessageBox.error(None, i18n("No text defined.."), i18n("Text undefined"))
            raise RuntimeError("No text defined!")
        plugin.setConfig(self.config)
        try:
            plugin.execute()
            KMessageBox.information(None, i18n("Your SMS was sendet successfull to "+lineargs.getOption("nr")+" with Plugin "+plugin.getObjectname()), i18n("Success"))
        except Exception, e:
            KMessageBox.error(None, i18n(e), i18n("Error"))
Ejemplo n.º 29
0
    def applyChanges(self):
        def collectDataFromUI():
            data = {}

            data["device_id"] = self.device
            data["name"] = self.connectionName
            data["auth"] = "pin"

            if self.pin and self.ui.checkBoxRemember.isChecked():
                data["auth_pin"] = self.pin

            return data

        self.connectionName = str(self.ui.comboBoxOperators.itemData(self.ui.comboBoxOperators.currentIndex()).toString())

        try:
            self.iface.updateConnection(self.package, self.connectionName, collectDataFromUI())
            self.accept()
        except Exception, e:
            KMessageBox.error(self, unicode(e))
            return
Ejemplo n.º 30
0
 def saveLogAs(self):
     startDir, fileName = os.path.split(self.doc.localPath())
     fileName = (os.path.splitext(fileName)[0] or "lilypond") + ".log"
     dlg = KEncodingFileDialog(startDir, 'utf-8', '',
         i18n("Save LilyPond Log as"),
         KEncodingFileDialog.Saving, self)
     dlg.setSelection(fileName)
     dlg.setConfirmOverwrite(True)
     if not dlg.exec_():
         return # Cancelled
     encoding = dlg.selectedEncoding()
     fileName = dlg.selectedFile()
     text = (self.textCursor().selection().toPlainText()
             or self.toPlainText())
     try:
         with open(fileName, 'w') as f:
             f.write(text.encode(encoding, 'replace'))
             f.write('\n')
     except (OSError, IOError) as e:
         KMessageBox.error(self,
             i18n("Could not save LilyPond log:\n\n%1", unicode(e)))
Ejemplo n.º 31
0
def dialogTextInputBox(message = _("Text"), value = "", ontType = "string"):
    try:
        if (ontType == "date"):
            oldYear = ""
            oldMonth = ""
            oldDay = ""
            if value:
                oldYear = "--year=%s" % value[:4]
                oldMonth = "--month=%s" % value[5:7]
                oldDay = "--day=%s" % value[8:10]

            parameters = ["zenity", "--calendar", "--title=" + PROGRAM_NAME, "--text=" + message, oldYear, oldMonth, oldDay, "--date-format=%Y-%m-%d"]

        elif (ontType == "sparql"):
            parameters = ["kdialog", "--title", PROGRAM_NAME, "--textinputbox", message, value, "800", "600"]

        else:
            parameters = ["kdialog", "--title", PROGRAM_NAME, "--textinputbox", message, value]

        dialogProcess = subprocess.Popen(parameters, stdout=subprocess.PIPE)
        dialogProcess.wait()
        value = u""
        for line in iter(dialogProcess.stdout.readline, ''):
            value += toUnicode(line)

        # Cleaning last "\n".
        if (value[-1] == "\n"):
            value = value[:-1]

        print(toUtf8("dialogTextInputBox:%s" % value))

    except:
        value = None
        KMessageBox.error(None, "Zenity and KDialog are required to edit resources.")

    return value
Ejemplo n.º 32
0
 def validate(self):
     """Checks if the input is acceptable.
     
     If this method returns True, the dialog is accepted when OK is clicked.
     Otherwise a messagebox could be displayed, and the dialog will remain
     visible.
     """
     # strip off whitespace
     name = self.name.text().strip()
     self.name.setText(name)
     
     if not name:
         self.setCurrentPage(self.firstPage)
         self.name.setFocus()
         KMessageBox.error(self, i18n("Please enter a session name."))
         if self._originalName:
             self.name.setText(self._originalName)
         return False
     
     if name == 'none':
         self.setCurrentPage(self.firstPage)
         self.name.setFocus()
         KMessageBox.error(self, i18n(
             "Please do not use the name '%1'.", "none"))
         return False
     
     if '&' in name:
         self.setCurrentPage(self.firstPage)
         self.name.setFocus()
         KMessageBox.error(self, i18n(
             "Please do not use the ampersand (&) character "
             "in a session name."))
         return False
         
     if self._originalName != name and name in self.sm.names():
         self.setCurrentPage(self.firstPage)
         self.name.setFocus()
         if KMessageBox.warningContinueCancel(self, i18n(
             "Another session with the name %1 exists already.\n\n"
             "Do you want to overwrite it?", name), None,
             KStandardGuiItem.overwrite(), KStandardGuiItem.cancel(),
             "session_overwrite") == KMessageBox.Cancel:
             return False
         
     return True
Ejemplo n.º 33
0
 def format_failed(self, message):
     self.__mainWindow.unsetCursor()
     self.__mainWindow.ui_format_dest.setEnabled(True)
     # TODO sort through error types (message.get_dbus_name()) in backend,
     # individual functions in frontend for each error type.
     KMessageBox.error(self.__mainWindow, str(message))