예제 #1
0
class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.connect(self.lineedit, SIGNAL("returnPressed()"),
                     self.updateUi)
        self.setWindowTitle("Calculate")

        self.button = QPushButton("Eval")
        layout.addWidget(self.button)
        self.connect(self.button, SIGNAL("pressed()"), self.updateUi)


    def updateUi(self):
        try:
            text = unicode(self.lineedit.text())
            self.browser.append("{0} = <b>{1}</b>".format(text,
                                eval(text)))
        except:
            self.browser.append("<font color=red>{0} is invalid!</font>"
                                .format(text))
예제 #2
0
class showInstructionsDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.vBoxSizer = QVBoxLayout()
        self.hBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.setMinimumHeight(80)
        self.buttonBox.buttons()[0].setMinimumHeight(80)
        self.hBoxSizer.addWidget(self.buttonBox)
        cw = self.parent().parent()
        if cw.prm["storedBlocks"] > 0:
            storedInstr = cw.prm['b' +
                                 str(cw.prm['currentBlock'])]['instructions']
            if len(storedInstr) > 0:
                self.browser.append(storedInstr)
            else:
                self.browser.append(
                    self.tr("Sorry, there are no instructions for this task."))
        else:
            storedInstr = self.parent().parent().instructionsTF.toPlainText()
            if len(storedInstr) > 0:
                self.browser.append(storedInstr)
            else:
                self.browser.append(
                    self.tr("Sorry, there are no instructions for this task."))
        self.browser.append("\n\nPress the ESC key to exit this screen.")

        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.browser.setFont(font)

        self.vBoxSizer.addWidget(self.browser)
        self.vBoxSizer.addLayout(self.hBoxSizer)
        #self.vBoxSizer.setSizeConstraint(QLayout.SetFixedSize)

        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("Task Instructions"))
        #self.resize(900, 600)
        self.showFullScreen()
class showInstructionsDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
       
        self.vBoxSizer = QVBoxLayout()
        self.hBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.setMinimumHeight(80)
        self.buttonBox.buttons()[0].setMinimumHeight(80)
        self.hBoxSizer.addWidget(self.buttonBox)
        cw = self.parent().parent()
        if cw.prm["storedBlocks"] > 0:
            storedInstr = cw.prm['b'+ str(cw.prm['currentBlock'])]['instructions']
            if len(storedInstr) > 0:
                self.browser.append(storedInstr)
            else:
                self.browser.append(self.tr("Sorry, there are no instructions for this task."))
        else:
            storedInstr = self.parent().parent().instructionsTF.toPlainText()
            if len(storedInstr) > 0:
                self.browser.append(storedInstr)
            else:
                self.browser.append(self.tr("Sorry, there are no instructions for this task."))
        self.browser.append("\n\nPress the ESC key to exit this screen.")

        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.browser.setFont(font)
        
        self.vBoxSizer.addWidget(self.browser)
        self.vBoxSizer.addLayout(self.hBoxSizer)
        #self.vBoxSizer.setSizeConstraint(QLayout.SetFixedSize)
        
        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("Task Instructions"))
        #self.resize(900, 600)
        self.showFullScreen()
class dialogShowParDiff(QDialog):
    def __init__(self, parent, diffText):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)

        self.vBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.browser.append(diffText)
        self.browser.verticalScrollBar().setValue(
            self.browser.verticalScrollBar().minimum())

        cursor = self.browser.textCursor()
        cursor.setPosition(0)
        self.browser.setTextCursor(cursor)

        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.browser.setFont(font)

        self.vBoxSizer.addWidget(self.browser)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)
        self.vBoxSizer.addWidget(buttonBox)

        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("Diff"))

        screen = QDesktopWidget().screenGeometry()
        wd = screen.width() / 4
        ht = screen.height() / 3
        self.resize(wd, ht)
        self.show()
예제 #5
0
class dialogShowParDiff(QDialog):
    def __init__(self, parent, diffText):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
       
        self.vBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

      
        self.browser.append(diffText)
        self.browser.verticalScrollBar().setValue(self.browser.verticalScrollBar().minimum())

        cursor = self.browser.textCursor();
        cursor.setPosition(0);
        self.browser.setTextCursor(cursor);
        
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.browser.setFont(font)
        
        self.vBoxSizer.addWidget(self.browser)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)
        self.vBoxSizer.addWidget(buttonBox)
        
        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("Diff"))

        screen = QDesktopWidget().screenGeometry()
        wd = screen.width()/4
        ht = screen.height()/3
        self.resize(wd, ht)
        self.show()
예제 #6
0
class showFortuneDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
       
        self.vBoxSizer = QVBoxLayout()
        self.hBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.anotherFortuneButton = QPushButton(self.tr("One More!"), self)
        self.anotherFortuneButton.clicked.connect(self.onClickAnotherFortuneButton)
        self.hBoxSizer.addWidget(self.anotherFortuneButton)

        idx = random.choice(range(len(self.prm['appData']['fortunesList'])))

        self.browser.append(self.prm['appData']['fortunesList'][idx]['quote'])
        self.browser.append('\n')
        self.browser.append(self.prm['appData']['fortunesList'][idx]['author'])
        self.browser.append("In:" + self.prm['appData']['fortunesList'][idx]['source'])

        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.browser.setFont(font)
        
        self.vBoxSizer.addWidget(self.browser)
        self.vBoxSizer.addLayout(self.hBoxSizer)
        #self.vBoxSizer.setSizeConstraint(QLayout.SetFixedSize)
        
        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("pychoacoustics - fortunes"))
        self.resize(450, 450)
        self.show()
    def onClickAnotherFortuneButton(self):
        self.browser.clear()
        idx = random.choice(range(len(self.prm['appData']['fortunesList'])))

        self.browser.append(self.prm['appData']['fortunesList'][idx]['quote'])
        self.browser.append('\n')
        self.browser.append(self.prm['appData']['fortunesList'][idx]['author'])
        self.browser.append("In:" + self.prm['appData']['fortunesList'][idx]['source'])
예제 #7
0
class GuiGsucave(QWidget):

    def __init__(self):
        super(GuiGsucave, self).__init__()
        self.initUI()

    def initUI(self):

        fec_ini = Gsucave.ini_trim.strftime("%d/%m")  # @UndefinedVariable
        fec_fin = Gsucave.fin_trim.strftime("%d/%m")  # @UndefinedVariable

        lblreporte = QLabel(str.format("Ingrese la ruta del reporte de Enotria"
                                       " del {} al {}:", fec_ini, fec_fin))

        self.txtreporte = QLineEdit(unicode("X:\\Servicio al Cliente"
        "\\Seguimiento SAC\\Procesos Centralizados (CG)"
        "\\SSC - Servicio de Soporte Comercial\\Servicio de Soporte Comercial"
        "\\1.REPORTES SUCAVE POLIZAS ELECTRONICAS\\2014\\I trimestre"
        "\\Copia de ConsultaMa2014_il.xlsx"))
        
        btnreporte = QPushButton("...")
        btnreporte.setMaximumWidth(30)
        btnreporte.clicked.connect(self.elegir_base)

        hboxreporte = QHBoxLayout()
        hboxreporte.addWidget(self.txtreporte)
        hboxreporte.addWidget(btnreporte)

        lblsalida = QLabel(unicode("Ingrese la ruta de donde se generará "
                                   "el reporte de SUCAVE:"))

        self.txtsalida = QLineEdit("")
        btnsalida = QPushButton("...")
        btnsalida.setMaximumWidth(30)
        btnsalida.clicked.connect(self.elegir_salida)

        hboxsalida = QHBoxLayout()
        hboxsalida.addWidget(self.txtsalida)
        hboxsalida.addWidget(btnsalida)

        self.tbsalida = QTextBrowser()
        self.tbsalida.append("Haga click en Generar para generar el reporte"
                             " de SUCAVE.")

        btngenerar = QPushButton("Generar")
        btngenerar.clicked.connect(self.generar)
        btngenerar.setMinimumHeight(35)

        vbox = QVBoxLayout()
        vbox.addWidget(lblreporte)
        vbox.addLayout(hboxreporte)
        vbox.addWidget(lblsalida)
        vbox.addLayout(hboxsalida)
        vbox.addWidget(self.tbsalida)
        vbox.addWidget(btngenerar)

        self.setLayout(vbox)
        self.setWindowTitle("Generador Sucave")
        self.setWindowIcon(QIcon(":pacifico256.png"))
        self.setGeometry(300, 300, 450, 375)
        self.show()

    def generar(self):
        try:
            gen = Gsucave(self, str(self.txtreporte.text()),
                          str(self.txtsalida.text()))
            gen.ejecutar()
        except Exception as e:
            self.publish(str(e))
            # raise
            

    def publish(self, msj):
        self.tbsalida.append(msj)

    def elegir_base(self):
        ruta = unicode(str(QFileDialog.getOpenFileName(self, 'Elegir archivo',
                                self.txtreporte.text(), 'Excel (*.xls*)')))
        if ruta != '':
            self.txtreporte.setText(ruta)

    def elegir_salida(self):
        ruta = unicode(str(QFileDialog.getExistingDirectory
                   (self, 'Elegir carpeta', self.txtsalida.text())))

        if ruta != '':
            self.txtsalida.setText(ruta)
예제 #8
0
class TestPanel(QtGui.QWidget):
    def __init__(self, event_handler, app_status_file_path):
        QtGui.QWidget.__init__(self)
        self.buttons_status_tag = "BUTTONS STATUS"
        self.app_status_file_path = app_status_file_path
        self.event_handler = event_handler
        self.setWindowTitle("TEST PANEL")
        self.x_siz, self.y_siz = 600, 400

        self.read_sram_button = PushButton("READ SRAM",
                                           tip_msg=READ_SRAM_BTN_TIP)
        self.read_sram_button.clicked.connect(
            self.event_handler.read_sram_button_slot)

        self.test_sram_button = PushButton("TEST SRAM",
                                           tip_msg=TEST_SRAM_BTN_TIP)
        self.test_sram_button.clicked.connect(
            self.event_handler.test_sram_chip_slot)

        self.test_upload_button = PushButton("TEST UPLOAD",
                                             tip_msg=TEST_UPLOAD_BTN_TIP)
        self.test_upload_button.clicked.connect(
            self.event_handler.test_upload_slot)

        self.text_browser = QTextBrowser()

        self.digidiag_on_checkbox = CheckBox("Show dididiag data panels",
                                             tip_msg="Enable digidiag")
        self.digidiag_on_checkbox.clicked.connect(self.show_digidiag)
        config = configparser.ConfigParser()
        config.read(self.app_status_file_path)
        try:
            if config[self.buttons_status_tag]['digidiag_show'] == 'True':
                self.digidiag_on_checkbox.setChecked(True)
                self.show_digidiag()
        except KeyError:
            pass
        mainGrid = QtGui.QGridLayout()
        mainGrid.setSpacing(10)
        mainGrid.addWidget(self.read_sram_button, 0, 0)
        mainGrid.addWidget(self.test_sram_button, 0, 1)
        mainGrid.addWidget(self.test_upload_button, 0, 2)
        mainGrid.addWidget(self.digidiag_on_checkbox, 1, 0)
        mainGrid.addWidget(self.text_browser, 2, 0, 10, 3)
        self.setLayout(mainGrid)
        self.resize(self.x_siz, self.y_siz)

    def show_digidiag(self):
        if self.digidiag_on_checkbox.isChecked():
            self.event_handler.digidiag_show_event()
        else:
            self.event_handler.digidiag_hide_event()

    def update_app_status(self):
        config = configparser.ConfigParser()
        config.read(self.app_status_file_path)
        config[self.buttons_status_tag]['digidiag_show'] = str(
            self.digidiag_on_checkbox.isChecked())
        with open(self.app_status_file_path, 'w') as cf:
            config.write(cf)

    def text_append(self, text):
        self.text_browser.append(text)

    def closeEvent(self, event):
        self.event_handler.digidiag_hide_event()
        self.update_app_status()
예제 #9
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        self.mainwindow = parent

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.uni_diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        self.tabw.addTab(self.uni_diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Save
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).clicked.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        self.buttons.button(QDialogButtonBox.Save).clicked.connect(
            self.saveFile)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a "
              "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.tabw.setTabText(2, _("&Diff"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.buttons.button(QDialogButtonBox.Save).setText(_("Save as file"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages',
                             self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)
        diffFont = QFont("Monospace")
        diffFont.setStyleHint(QFont.TypeWriter)
        self.uni_diff.setFont(diffFont)

    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.setDiffText()
        self.messages.clear()

    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(
                htmldiff.htmldiff(self._text,
                                  text,
                                  _("Current Document"),
                                  _("Converted Document"),
                                  wrapcolumn=100))
        else:
            self.diff.clear()

    def setDiffText(self, text=''):
        if text:
            difflist = list(
                difflib.unified_diff(self._text.split('\n'), text.split('\n'),
                                     _("Current Document"),
                                     _("Converted Document")))
            diffHLstr = self.diffHighl(difflist)
            self.uni_diff.setHtml(diffHLstr)
        else:
            self.uni_diff.clear()

    def convertedText(self):
        return self._convertedtext or ''

    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()
        self.setDiffText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(
                _("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.ly_tool('convert-ly'))
        command += ['-f', fromVersion, '-t', toVersion, '-']

        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if os.name == "nt":
            # Python 2.7 subprocess on Windows chokes on unicode in env
            env = util.bytes_environ()
        else:
            env = dict(os.environ)
        if sys.platform.startswith('darwin'):
            try:
                del env['PYTHONHOME']
            except KeyError:
                pass
            try:
                del env['PYTHONPATH']
            except KeyError:
                pass
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env[b'LANGUAGE'] = b'C'
            else:
                env['LANGUAGE'] = 'C'

        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                                        env=env,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                out, err = proc.communicate(
                    util.platform_newlines(self._text).encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n"
                      "{message}\n").format(convert_ly=command[0], message=e))
                return
            out = util.universal_newlines(out.decode('UTF-8'))
            err = util.universal_newlines(err.decode('UTF-8'))
            self.messages.setPlainText(err)
            self.setConvertedText(out)
            self.setDiffText(out)
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' +
                                     _("The document has not been changed."))

    def saveFile(self):
        """Save content in tab as file"""
        tabdata = self.getTabData(self.tabw.currentIndex())
        doc = self.mainwindow.currentDocument()
        orgname = doc.url().toLocalFile()
        filename = os.path.splitext(
            orgname)[0] + '[' + tabdata.filename + ']' + '.' + tabdata.ext
        caption = app.caption(_("dialog title", "Save File"))
        filetypes = '{0} (*.txt);;{1} (*.htm);;{2} (*)'.format(
            _("Text Files"), _("HTML Files"), _("All Files"))
        filename = QFileDialog.getSaveFileName(self.mainwindow, caption,
                                               filename, filetypes)
        if not filename:
            return False  # cancelled
        with open(filename, 'wb') as f:
            f.write(tabdata.text.encode('utf-8'))

    def getTabData(self, index):
        """Get content of current tab from current index"""
        if index == 0:
            return FileInfo('message', 'txt', self.messages.toPlainText())
        elif index == 1:
            return FileInfo('html-diff', 'html', self.diff.toHtml())
        elif index == 2:
            return FileInfo('uni-diff', 'diff', self.uni_diff.toPlainText())

    def diffHighl(self, difflist):
        """Return highlighted version of input."""
        result = []
        for l in difflist:
            if l.startswith('-'):
                s = '<span style="color: red; white-space: pre-wrap;">'
            elif l.startswith('+'):
                s = '<span style="color: green; white-space: pre-wrap;">'
            else:
                s = '<span style="white-space: pre-wrap;">'
            h = l.replace('&', '&amp;').replace('<',
                                                '&lt;').replace('>', '&gt;')
            result.append(s + h + '</span>')
        return '<br>'.join(result)
class OWTextableDisplay(OWTextableBaseWidget):
    """A widget for displaying segmentations"""
    name = "Display"
    description = "Display or export the details of a segmentation"
    icon = "icons/Display.png"
    priority = 6001

    inputs = [('Segmentation', Segmentation, "inputData", widget.Single)]
    outputs = [('Bypassed segmentation', Segmentation, widget.Default),
               ('Displayed segmentation', Segmentation)]

    settingsHandler = VersionedSettingsHandler(
        version=__version__.rsplit(".", 1)[0])
    # Settings...
    displayAdvancedSettings = settings.Setting(False)
    customFormatting = settings.Setting(False)
    customFormat = settings.Setting(u'%(__content__)s')
    segmentDelimiter = settings.Setting(u'\\n')
    header = settings.Setting(u'')
    footer = settings.Setting(u'')
    encoding = settings.Setting('utf8')
    lastLocation = settings.Setting('.')
    basicFormatHTML = settings.Setting(True)

    # Predefined list of available encodings...
    encodings = getPredefinedEncodings()

    want_main_area = True

    def __init__(self, *args, **kwargs):
        """Initialize a Display widget"""
        super().__init__(*args, **kwargs)
        # Current general warning and error messages (as submited
        # through self.error(text) and self.warning(text)
        self._currentErrorMessage = ""
        self._currentWarningMessage = ""

        self.segmentation = None
        self.displayedSegmentation = Input(label=u'displayed_segmentation',
                                           text=u'')
        self.goto = 0
        self.browser = QTextBrowser()
        self.infoBox = InfoBox(widget=self.mainArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            sendIfPreCallback=self.updateGUI,
            infoBoxAttribute='infoBox',
        )

        # GUI...

        # NB: These are "custom" advanced settings, not those provided by
        # TextableUtils. Note also that there are two copies of the checkbox
        # controlling the same attribute, to simulate its moving from one
        # side of the widget to the other...
        self.advancedSettingsCheckBoxLeft = gui.checkBox(
            widget=self.controlArea,
            master=self,
            value='displayAdvancedSettings',
            label=u'Advanced settings',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Toggle advanced settings on and off."),
        )
        gui.separator(widget=self.controlArea, height=3)

        # Custom formatting box...
        formattingBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Formatting',
            orientation='vertical',
            addSpace=True,
        )
        gui.checkBox(
            widget=formattingBox,
            master=self,
            value='customFormatting',
            label=u'Apply custom formatting',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Check this box to apply custom formatting."),
        )
        gui.separator(widget=formattingBox, height=3)
        self.formattingIndentedBox = gui.indentedBox(widget=formattingBox, )
        headerLineEdit = gui.lineEdit(
            widget=self.formattingIndentedBox,
            master=self,
            value='header',
            label=u'Header:',
            labelWidth=131,
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"String that will be appended at the beginning of\n"
                     u"the formatted segmentation."),
        )
        headerLineEdit.setMinimumWidth(200)
        gui.separator(widget=self.formattingIndentedBox, height=3)
        gui.lineEdit(
            widget=self.formattingIndentedBox,
            master=self,
            value='customFormat',
            label=u'Format:',
            labelWidth=131,
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"String specifying how to format the segmentation.\n\n"
                     u"See user guide for detailed instructions."),
        )
        gui.separator(widget=self.formattingIndentedBox, height=3)
        gui.lineEdit(
            widget=self.formattingIndentedBox,
            master=self,
            value='segmentDelimiter',
            label=u'Segment delimiter:',
            labelWidth=131,
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Delimiter that will be inserted between segments.\n\n"
                     u"Note that '\\n' stands for carriage return and\n"
                     u"'\\t' for tabulation."),
        )
        gui.separator(widget=self.formattingIndentedBox, height=3)
        gui.lineEdit(
            widget=self.formattingIndentedBox,
            master=self,
            value='footer',
            label=u'Footer:',
            labelWidth=131,
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"String that will be appended at the end of the\n"
                     u"formatted segmentation."),
        )
        headerLineEdit.setMinimumWidth(200)
        gui.separator(widget=self.formattingIndentedBox, height=3)

        # Advanced export box
        self.advancedExportBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Export',
            orientation='vertical',
            addSpace=True,
        )
        encodingCombo = gui.comboBox(
            widget=self.advancedExportBox,
            master=self,
            value='encoding',
            items=type(self).encodings,
            sendSelectedValue=True,
            orientation='horizontal',
            label=u'File encoding:',
            labelWidth=151,
            tooltip=(u"Select the encoding of the file into which a\n"
                     u"displayed segmentation can be saved by clicking\n"
                     u"the 'Export' button below.\n\n"
                     u"Note that the displayed segmentation that is\n"
                     u"copied to the clipboard by clicking the 'Copy\n"
                     u"to clipboard' button below is always encoded\n"
                     u"in utf-8."),
        )
        addSeparatorAfterDefaultEncodings(encodingCombo)
        gui.separator(widget=self.advancedExportBox, height=3)
        exportBoxLine2 = gui.widgetBox(
            widget=self.advancedExportBox,
            orientation='horizontal',
        )
        gui.button(
            widget=exportBoxLine2,
            master=self,
            label=u'Export to file',
            callback=self.exportFile,
            tooltip=(u"Open a dialog for selecting the output file to\n"
                     u"which the displayed segmentation will be saved."),
        )
        gui.button(
            widget=exportBoxLine2,
            master=self,
            label=u'Copy to clipboard',
            callback=self.copyToClipboard,
            tooltip=(u"Copy the displayed segmentation to clipboard, in\n"
                     u"order to paste it in another application."
                     u"\n\nNote that the only possible encoding is utf-8."),
        )

        gui.rubber(self.controlArea)

        # Send button and checkbox
        self.sendButton.draw()

        # Main area

        # NB: This is the second copy of the advanced settings checkbox,
        # see above...
        self.advancedSettingsRightBox = gui.widgetBox(
            widget=self.mainArea,
            orientation='vertical',
        )
        self.advancedSettingsCheckBoxRight = gui.checkBox(
            widget=self.advancedSettingsRightBox,
            master=self,
            value='displayAdvancedSettings',
            label=u'Advanced settings',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Toggle advanced settings on and off."),
        )
        gui.separator(widget=self.advancedSettingsRightBox, height=3)

        self.advancedSettingsCheckBoxRightPlaceholder = gui.separator(
            widget=self.mainArea,
            height=25,
        )

        self.basicFormatBox = gui.widgetBox(
            widget=self.mainArea,
            orientation='vertical',
            box=u'Format',
            addSpace=False,
        )
        gui.checkBox(
            widget=self.basicFormatBox,
            master=self,
            value='basicFormatHTML',
            label=u'Display segmentation in rich text format (HTML)',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"TODO."),
        )
        self.navigationBox = gui.widgetBox(
            widget=self.mainArea,
            orientation='vertical',
            box=u'Navigation',
            addSpace=True,
        )
        self.gotoSpin = gui.spin(
            widget=self.navigationBox,
            master=self,
            value='goto',
            minv=1,
            maxv=1,
            orientation='horizontal',
            label=u'Go to segment:',
            labelWidth=180,
            callback=self.gotoSegment,
            tooltip=(u"Jump to a specific segment number."),
        )
        self.mainArea.layout().addWidget(self.browser)

        # Advanced export box
        gui.separator(widget=self.mainArea, height=3)
        self.basicExportBox = gui.widgetBox(
            widget=self.mainArea,
            box=u'Export',
            orientation='horizontal',
            addSpace=True,
        )
        gui.button(
            widget=self.basicExportBox,
            master=self,
            label=u'Save to file',
            callback=self.exportFile,
            tooltip=(u"Open a dialog for selecting the output file to\n"
                     u"which the displayed segmentation will be saved."),
        )
        gui.button(
            widget=self.basicExportBox,
            master=self,
            label=u'Copy to clipboard',
            callback=self.copyToClipboard,
            tooltip=(u"Copy the displayed segmentation to clipboard, in\n"
                     u"order to paste it in another application."),
        )

        # Info box...
        self.infoBox.draw()

        self.sendButton.sendIf()

    def inputData(self, newInput):
        """Process incoming data."""
        self.segmentation = newInput
        self.infoBox.inputChanged()
        self.sendButton.sendIf()

    def sendData(self):
        """Send segmentation to output"""
        if not self.segmentation:
            self.infoBox.setText(u'Widget needs input.', 'warning')
            self.send('Bypassed segmentation', None, self)
            self.send('Displayed segmentation', None, self)
            return

        self.send('Bypassed segmentation',
                  Segmenter.bypass(self.segmentation, self.captionTitle), self)
        # TODO: Check if this is correct replacement for textable v1.*, v2.*
        if 'format' in self._currentWarningMessage or \
                'format' in self._currentErrorMessage:
            self.send('Displayed segmentation', None, self)
            return
        if len(self.displayedSegmentation[0].get_content()) > 0:
            self.send('Displayed segmentation', self.displayedSegmentation,
                      self)
        else:
            self.send('Displayed segmentation', None, self)
        # TODO: Differes only in capitalization with a check before
        #       Is this intentional?
        if "Format" not in self._currentErrorMessage:
            message = u'%i segment@p sent to output.' % len(self.segmentation)
            message = pluralize(message, len(self.segmentation))
            self.infoBox.setText(message)
        self.sendButton.resetSettingsChangedFlag()

    def updateGUI(self):
        """Update GUI state"""
        self.controlArea.setVisible(self.displayAdvancedSettings)
        self.advancedSettingsCheckBoxRightPlaceholder.setVisible(
            self.displayAdvancedSettings)
        self.advancedSettingsCheckBoxLeft.setVisible(
            self.displayAdvancedSettings)
        self.advancedSettingsRightBox.setVisible(
            not self.displayAdvancedSettings)
        self.basicFormatBox.setVisible(not self.displayAdvancedSettings)
        self.basicExportBox.setVisible(not self.displayAdvancedSettings)
        self.browser.clear()
        if self.segmentation:
            if self.displayAdvancedSettings:
                customFormatting = self.customFormatting
            else:
                customFormatting = False
                self.autoSend = True

            self.controlArea.setDisabled(True)
            self.mainArea.setDisabled(True)
            self.infoBox.setText(u"Processing, please wait...", "warning")

            if customFormatting:
                self.navigationBox.setVisible(False)
                self.navigationBox.setDisabled(True)
                self.advancedExportBox.setDisabled(True)
                self.formattingIndentedBox.setDisabled(False)
                displayedString = u''
                progressBar = ProgressBar(self,
                                          iterations=len(self.segmentation))
                try:
                    displayedString = self.segmentation.to_string(
                        codecs.decode(self.customFormat, 'unicode_escape'),
                        codecs.decode(self.segmentDelimiter, 'unicode_escape'),
                        codecs.decode(self.header, 'unicode_escape'),
                        codecs.decode(self.footer, 'unicode_escape'),
                        True,
                        progress_callback=progressBar.advance,
                    )
                    self.infoBox.settingsChanged()
                    self.advancedExportBox.setDisabled(False)
                    self.warning()
                    self.error()
                except TypeError as type_error:
                    try:
                        self.infoBox.setText(type_error.message, 'error')
                    except AttributeError:
                        message = "Please enter a valid format (type error)."
                        self.infoBox.setText(message, 'error')
                except KeyError:
                    message = "Please enter a valid format (error: missing name)."
                    self.infoBox.setText(message, 'error')
                except ValueError:
                    message = "Please enter a valid format (error: missing "   \
                        + "variable type)."
                    self.infoBox.setText(message, 'error')
                self.browser.append(displayedString)
                self.displayedSegmentation.update(
                    displayedString,
                    label=self.captionTitle,
                )
                progressBar.finish()

            else:
                self.navigationBox.setVisible(self.basicFormatHTML)
                self.formattingIndentedBox.setDisabled(True)
                self.warning()
                self.error()
                progressBar = ProgressBar(self,
                                          iterations=len(self.segmentation))
                if self.basicFormatHTML or self.displayAdvancedSettings:
                    displayedString, summarized = self.segmentation.to_html(
                        True,
                        progressBar.advance,
                    )
                    self.navigationBox.setEnabled(
                        len(self.segmentation) > 1 and not summarized)
                else:
                    displayedString = self.segmentation.to_string(
                        formatting="%(__content__)s",
                        segment_delimiter="\n",
                        progress_callback=progressBar.advance,
                    )
                self.browser.append(displayedString)
                self.displayedSegmentation.update(
                    displayedString,
                    label=self.captionTitle,
                )
                self.gotoSpin.setRange(1, len(self.segmentation))
                if self.goto:
                    self.browser.setSource(QUrl("#%i" % self.goto))
                else:
                    self.browser.setSource(QUrl("#top"))
                self.advancedExportBox.setDisabled(False)
                self.infoBox.settingsChanged()
                progressBar.finish()

            self.controlArea.setDisabled(False)
            self.mainArea.setDisabled(False)

        else:
            self.goto = 0
            self.gotoSpin.setRange(0, 1)
            self.advancedExportBox.setDisabled(True)
            self.navigationBox.setVisible(True)
            self.navigationBox.setEnabled(False)
            self.formattingIndentedBox.setDisabled(True)

    def gotoSegment(self):
        if self.goto:
            self.browser.setSource(QUrl("#%i" % self.goto))
        else:
            self.browser.setSource(QUrl("#top"))

    def exportFile(self):
        """Display a FileDialog and export segmentation to file"""
        filePath = QFileDialog.getSaveFileName(
            self,
            u'Export segmentation to File',
            self.lastLocation,
        )
        if filePath:
            self.lastLocation = os.path.dirname(filePath)
            if self.displayAdvancedSettings:
                encoding = re.sub(r"[ ]\(.+", "", self.encoding)
            else:
                encoding = "utf8"
            outputFile = codecs.open(
                filePath,
                encoding=encoding,
                mode='w',
                errors='xmlcharrefreplace',
            )
            outputFile.write(
                #normalizeCarriageReturns(
                self.displayedSegmentation[0].get_content()
                #)
            )
            outputFile.close()
            QMessageBox.information(None, 'Textable',
                                    'Segmentation correctly exported',
                                    QMessageBox.Ok)

    def copyToClipboard(self):
        """Copy displayed segmentation to clipboard"""
        QApplication.clipboard().setText(
            #normalizeCarriageReturns(
            self.displayedSegmentation[0].get_content()
            #)
        )
        QMessageBox.information(None, 'Textable',
                                'Segmentation correctly copied to clipboard',
                                QMessageBox.Ok)

    def onDeleteWidget(self):
        if self.displayedSegmentation is not None:
            self.displayedSegmentation.clear()

    def setCaption(self, title):
        if 'captionTitle' in dir(self):
            changed = title != self.captionTitle
            super().setCaption(title)
            if changed:
                self.sendButton.settingsChanged()
        else:
            super().setCaption(title)

    def error(self, *args, **kwargs):
        # Reimplemented to track the current active error message
        if args:
            text_or_id = args[0]
        else:
            text_or_id = kwargs.get("text_or_id", None)

        if isinstance(text_or_id, str) or text_or_id is None:
            self._currentErrorMessage = text_or_id or ""
        return super().error(*args, **kwargs)

    def warning(self, *args, **kwargs):
        # Reimplemented to track the current active warning message
        if args:
            text_or_id = args[0]
        else:
            text_or_id = kwargs.get("text_or_id", None)

        if isinstance(text_or_id, str) or text_or_id is None:
            self._currentWarningMessage = text_or_id or ""
        return super().warning(*args, **kwargs)
예제 #11
0
class HardWidget(QWidget):
       
    def __init__(self,parent = None):
        super(HardWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px")#设置整体字体
            #分别返回各个函数的返回值
        #self.mymem = self.memory_stat()#返回内存信息
        #self.mydisk = self.disk_stat()#返回硬盘信息
        #self.mycpu = self.cpu_stat()#返回cpu信息
        #self.myload = self.load_stat()#返回负载信息
        #self.myuptime = self.uptime_stat()#返回运行时间
        #self.mypass = self.readText()#读取文件信息,内容为密码
            #引入tipDialog弹出窗口,并且将其设置为最前端,后面窗口不可操作
#         self.tipDlg = TipDialog()
#         self.tipDlg.setModal(True)
        
        self.a = float()#声明一个float类型的數,之后作为本类中某个函数的参数
            #声明一个label,书写超级密码,字体,长度120
        self.passLabel = QLabel(self.tr("Super Password:"******"times",11))
        self.passLabel.setFont(QFont("",11))
            #声明一个label,书写提示信息
        self.tipLabel  = QLabel(self.tr("Tip:input the password to get hardware information"))
            #声明一个文本框,用来输入密码
        self.lineEdit  = QLineEdit()
        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit.setEchoMode(QLineEdit.Password)
        self.lineEdit.setFixedWidth(250)
            #声明一个pushbutton,立即收集
        self.runButton = QPushButton(self.tr("Get"))
        self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
            #声明一个textBrower,用来显示收集的信息
        self.textArea = QTextBrowser()
        
            #布局一,横向布局,添加passLabel,lineEdit,runButton,设置前后的空白分别为20和280,中间充满
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.passLabel)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        hLayout1.addSpacing(280)
            #布局二,横向布局,添加tipLabe,提示信息显示,设置前面的空白为20,后边充满
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.tipLabel)
            #布局三,横向布局,添加textArea,设这前后的空白为20和60,中间充满
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textArea)
        hLayout3.addSpacing(60)
        
            #总其布局,纵向布局,将上面的三个布局加入其中,设置间隔为20,最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(40)
        self.setLayout(mainLayout)
        #runButton的槽函数链接
        self.connect(self.runButton, SIGNAL("clicked()"),self.run)

    def keyPressEvent(self, event): 
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            self.run()


    #获取内存信息的函数
    def memory_stat(self):
        mem = {}
        f = open("/proc/meminfo")
        lines = f.readlines()
        f.close()
        for line in lines:
            if len(line) < 2: continue
            name = line.split(':')[0]
            var = line.split(':')[1].split()[0]
            mem[name] = long(var)
        mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
        return mem
    #读取磁盘信息函数
    def getMntDistSize(self):
        cmd = "df -h --total | grep /var/lib/chost/disks"
        status = []
        output = ""
        hd = {}
        hd['available'] = 0
        hd['capacity'] = 0
        hd['free'] = 0
        hd['used'] = 0
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        disklist = QString(output).simplified().split(" ")
        num = len(disklist)
        if num < 5:
            return hd
        else:
            if QString(disklist[3]).contains("T"):
                hd['free'] = int(float(disklist[3].split("T")[0])*1024*1024*1024)
            else:
                hd['free'] = int(float(disklist[3].split("G")[0])*1024*1024)
            if QString(disklist[1]).contains("T"):
                hd['capacity'] = int(float(disklist[1].split("T")[0])*1024*1024*1024)
            else:
                hd['capacity'] = int(float(disklist[1].split("G")[0])*1024*1024)
            if QString(disklist[2]).contains("T"):
                hd['used'] = int(float(disklist[2].split("T")[0])*1024*1024*1024)
            else:
                hd['used'] = int(float(disklist[2].split("G")[0])*1024*1024)
                
            hd['available'] = hd['capacity'] - hd['used']
        return hd
        
    def total_disk_stat(self):
        cmd = "df -h --total | grep total"
        status = []
        output = ""
        hd = {}
        hd['available'] = 0
        hd['capacity'] = 0
        hd['free'] = 0
        hd['used'] = 0
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        disklist = QString(output).simplified().split(" ")
        num = len(disklist)
        if num < 5:
            return hd
        else:
            if QString(disklist[3]).contains("T"):
                hd['free'] = int(float(disklist[3].split("T")[0])*1024*1024*1024)
            else:
                hd['free'] = int(float(disklist[3].split("G")[0])*1024*1024)
            if QString(disklist[1]).contains("T"):
                hd['capacity'] = int(float(disklist[1].split("T")[0])*1024*1024*1024)
            else:
                hd['capacity'] = int(float(disklist[1].split("G")[0])*1024*1024)
            if QString(disklist[2]).contains("T"):
                hd['used'] = int(float(disklist[2].split("T")[0])*1024*1024*1024)
            else:
                hd['used'] = int(float(disklist[2].split("G")[0])*1024*1024)
                
            hd['available'] = hd['capacity'] - hd['used']
        return hd
    def disk_stat(self):
        hd={}
        hd['total'] = globalfunc.get_disk_size()
        return hd
    #读取cpu信息函数
    def cpu_stat(self):
        cpuinfo = {}
        cpu_info = globalfunc.get_cpu_info()
        cpuinfo["cpuinfo"] = cpu_info
        return cpuinfo
    #读取负载信息函数
    def load_stat(self):
        loadavg = {}
        f = open("/proc/loadavg")
        con = f.read().split()
        f.close()
        loadavg['lavg_1']=con[0]
        loadavg['lavg_5']=con[1]  #average load per five minute
        loadavg['lavg_15']=con[2]
        loadavg['nr']=con[3]
        loadavg['last_pid']=con[4]
        return loadavg
    #读取运行时间函数
    def uptime_stat(self):
        uptime = {}
        f = open("/proc/uptime")
        con = f.read().split()
        f.close()
        all_sec = float(con[0])
        MINUTE,HOUR,DAY = 60,3600,86400
        uptime['day'] = int(all_sec / DAY )
        uptime['hour'] = int((all_sec % DAY) / HOUR)
        uptime['minute'] = int((all_sec % HOUR) / MINUTE)
        uptime['second'] = int(all_sec % MINUTE)
        uptime['Free rate'] = float(con[1]) / float(con[0])
        return uptime
    #读取网络信息函数
    def net_stat(self):
        net = []
        f = open("/proc/net/dev")
        lines = f.readlines()
        f.close()
        for line in lines[2:]:
                con = line.split()
            #if line == "\n":
                if (len(con) == 16):
                    intf = {}
                    intf['interface'] = con[0].split(':')[0].rstrip()#first data includes two content
                    intf['ReceiveBytes'] = int(con[0].split(':')[1])
                    intf['ReceivePackets'] = int(con[1])
                    intf['ReceiveErrs'] = int(con[2])
                    intf['ReceiveDrop'] = int(con[3])
                    intf['ReceiveFifo'] = int(con[4])
                    intf['ReceiveFrames'] = int(con[5])
                    intf['ReceiveCompressed'] = int(con[6])
                    intf['ReceiveMulticast'] = int(con[7])
                    intf['TransmitBytes'] = int(con[8])
                    intf['TransmitPackets'] = int(con[9])
                    intf['TransmitErrs'] = int(con[10])
                    intf['TransmitDrop'] = int(con[11])
                    intf['TransmitFifo'] = int(con[12])
                    intf['Transmitcolls'] = int(con[13])
                    intf['Transmitcarrier'] = int(con[14])
                    intf['TransmitCompressed'] = int(con[15])
                    
                elif (len(con) == 17):
                    intf = {}
                    intf['interface'] = con[0]
                    intf['ReceiveBytes'] = int(con[1])
                    intf['ReceivePackets'] = int(con[2])
                    intf['ReceiveErrs'] = int(con[3])
                    intf['ReceiveDrop'] = int(con[4])
                    intf['ReceiveFifo'] = int(con[5])
                    intf['ReceiveFrames'] = int(con[6])
                    intf['ReceiveCompressed'] = int(con[7])
                    intf['ReceiveMulticast'] = int(con[8])
                    intf['TransmitBytes'] = int(con[9])
                    intf['TransmitPackets'] = int(con[10])
                    intf['TransmitErrs'] = int(con[11])
                    intf['TransmitDrop'] = int(con[12])
                    intf['TransmitFifo'] = int(con[13])
                    intf['Transmitcolls'] = int(con[14])
                    intf['Transmitcarrier'] = int(con[15])
                    intf['TransmitCompressed'] = int(con[16])
                net.append(intf)
        return net
        #将flaot类型的数,转换为string的函数
    def floatToString(self, a):
        if a <= 0 :
            e = int(a*100000000)
            b = QString().number(e)
            m = len(b)
            x = ""
        elif a > 0:
            e = int(a)
            x = QString().number(e)
            s = a - float(e)
            
            f = int(s*100000000)
            b = QString().number(f)
            m = len(b)
            
        if (8-m) == 0:
            n = b
        elif (8-m) == 1:
            n = "0" + b
        elif (8-m) == 2:
            n = "0" + "0" + b
        elif (8-m) == 3:
            n = "0" + "0" + "0" + b
        elif (8-m) == 4:
            n = "0" + "0" + "0" + "0" + b
        elif (8-m) == 5:
            n = "0" + "0" +"0" + "0" + "0" + b   
        else:
            n = "0" + "0" +"0" + "0" + "0" + "0" + b
        c = x +"."+ n
        return c
    
    #读文件,取密码
    def readText(self):
        return "cloudsterminal"
    
    #button运行函数
    def run(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        desktop = QApplication.desktop()
        self.mypass = self.readText()#读取文件信息,内容为密码
        if (self.lineEdit.text() == self.mypass):
                self.textArea.clear()
                self.lineEdit.clear()
      	        self.mymem = self.memory_stat()#返回内存信息
                self.mydisk = self.disk_stat()#返回硬盘信息
                self.mycpu = self.cpu_stat()#返回cpu信息
                self.myload = self.load_stat()#返回负载信息
                self.myuptime = self.uptime_stat()#返回运行时间
                usedText = QString().number(self.mymem['MemUsed'])
                totalText = QString().number(self.mymem['MemTotal'])
                freeText = QString().number(self.mymem['MemFree'])
                buffersText = QString().number(self.mymem['Buffers'])
                cachedText = QString().number(self.mymem['Cached'])
                self.textArea.append(self.tr("Memory:"))
                self.textArea.append(self.tr("Total Memory:") + "\t" + totalText + " \tKB "+ "\r\n" + self.tr("Used Memory:") + "\t" + usedText+ " \tKB "+ "\r\n" + self.tr("Free Memory:") + "\t" + freeText+ " \tKB "+ "\r\n" +"Buffers:\t\t"+ buffersText+ " \tKB "+ "\r\n" +"Cached:\t\t"+ cachedText+ " \tKB ")
                #self.textArea.setText(text2)
                self.textArea.append(" ")
                self.textArea.append(self.tr("Disk:"))
                self.textArea.append(self.tr("Total Disk:") + "\t" + self.mydisk["total"])
                self.textArea.append(" ")
                self.textArea.append(self.tr("Cpu Type:"))
                cpustr = ""
                for key in self.mycpu:
                    curcpu = key + ": " + self.mycpu[key] + "\n"
                    cpustr += curcpu
                self.textArea.append(cpustr)
                #self.textArea.append("\n")
                self.textArea.append(self.tr("Load information:"))
                self.textArea.append(self.tr("lavg_1:") + "\t" + self.myload['lavg_1'] +"\r\n" + self.tr("lavg_5:") + "\t" + self.myload['lavg_5'] +"\r\n" + self.tr("lavg_15:") + "\t" + self.myload['lavg_15'] +"\r\n" + self.tr("nr:") + "\t" + self.myload['nr'] +"\r\n" + self.tr("last_pid:") + "\t" + self.myload['last_pid'])
                self.textArea.append(" ")
                self.textArea.append(self.tr("Run Time:"))
                self.textArea.append(self.tr("Days:")+ "\t" + QString().number(self.myuptime['day']) + "\r\n" +self.tr("Hours:") + "\t"  + QString().number(self.myuptime['hour']) + "\r\n" +self.tr("Minutes:") + "\t" + QString().number(self.myuptime['minute']) + "\r\n" +self.tr("Seconds:") + "\t" + QString().number(self.myuptime['second']))
                a = self.floatToString(self.myuptime["Free rate"])
                self.textArea.append(self.tr("Free Rate:")+ "\t" + a)
                self.textArea.append(" ")
                
        elif self.lineEdit.text() == "":
            InfoHintDialog(self.tr("password is empty")).exec_()
            self.textArea.clear()
        else:
            InfoHintDialog(self.tr("password is wrong")).exec_()
            self.lineEdit.clear()
            
        
    def updateWindow(self):
        self.runButton.setText(self.tr("Get"))
        self.textArea.clear()
        self.passLabel.setText(self.tr("Super Password:"******"Tip:input the password to get hardware information"))
예제 #12
0
class LeapWindow(QMainWindow):
    #XXX tbd: refactor into model / view / controller
    #and put in its own modules...

    newLogLine = pyqtSignal([str])
    statusChange = pyqtSignal([object])

    def __init__(self, opts):
        super(LeapWindow, self).__init__()
        self.debugmode = getattr(opts, 'debug', False)

        self.vpn_service_started = False

        self.createWindowHeader()
        self.createIconGroupBox()

        self.createActions()
        self.createTrayIcon()
        if self.debugmode:
            self.createLogBrowser()

        # create timer
        self.timer = QTimer()

        # bind signals

        self.trayIcon.activated.connect(self.iconActivated)
        self.newLogLine.connect(self.onLoggerNewLine)
        self.statusChange.connect(self.onStatusChange)
        self.timer.timeout.connect(self.onTimerTick)

        widget = QWidget()
        self.setCentralWidget(widget)

        # add widgets to layout
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.headerBox)
        mainLayout.addWidget(self.statusIconBox)
        if self.debugmode:
            mainLayout.addWidget(self.statusBox)
            mainLayout.addWidget(self.loggerBox)
        widget.setLayout(mainLayout)

        #
        # conductor is in charge of all
        # vpn-related configuration / monitoring.
        # we pass a tuple of signals that will be
        # triggered when status changes.
        #
        config_file = getattr(opts, 'config_file', None)
        self.conductor = EIPConductor(
            watcher_cb=self.newLogLine.emit,
            config_file=config_file,
            status_signals=(self.statusChange.emit, ))

        self.trayIcon.show()

        self.setWindowTitle("Leap")
        self.resize(400, 300)

        self.set_statusbarMessage('ready')

        if self.conductor.autostart:
            self.start_or_stopVPN()

    def closeEvent(self, event):
        """
        redefines close event (persistent window behaviour)
        """
        if self.trayIcon.isVisible() and not self.debugmode:
            QMessageBox.information(self, "Systray",
                                    "The program will keep running "
                                    "in the system tray. To "
                                    "terminate the program, choose "
                                    "<b>Quit</b> in the "
                                    "context menu of the system tray entry.")
            self.hide()
            event.ignore()
        if self.debugmode:
            self.cleanupAndQuit()

    def setIcon(self, name):
        icon = self.Icons.get(name)
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)

    def setToolTip(self):
        """
        get readable status and place it on systray tooltip
        """
        status = self.conductor.status.get_readable_status()
        self.trayIcon.setToolTip(status)

    def iconActivated(self, reason):
        """
        handles left click, left double click
        showing the trayicon menu
        """
        #XXX there's a bug here!
        #menu shows on (0,0) corner first time,
        #until double clicked at least once.
        if reason in (QSystemTrayIcon.Trigger,
                      QSystemTrayIcon.DoubleClick):
            self.trayIconMenu.show()

    def createWindowHeader(self):
        """
        description lines for main window
        """
        #XXX good candidate to refactor out! :)
        self.headerBox = QGroupBox()
        self.headerLabel = QLabel("<font size=40><b>E</b>ncryption \
<b>I</b>nternet <b>P</b>roxy</font>")
        self.headerLabelSub = QLabel("<i>trust your \
technolust</i>")

        pixmap = QPixmap(':/images/leapfrog.jpg')
        frog_lbl = QLabel()
        frog_lbl.setPixmap(pixmap)

        headerLayout = QHBoxLayout()
        headerLayout.addWidget(frog_lbl)
        headerLayout.addWidget(self.headerLabel)
        headerLayout.addWidget(self.headerLabelSub)
        headerLayout.addStretch()
        self.headerBox.setLayout(headerLayout)

    def getIcon(self, icon_name):
        # XXX get from connection dict
        icons = {'disconnected': 0,
                 'connecting': 1,
                 'connected': 2}
        return icons.get(icon_name, None)

    def createIconGroupBox(self):
        """
        dummy icongroupbox
        (to be removed from here -- reference only)
        """
        icons = {
            'disconnected': ':/images/conn_error.png',
            'connecting': ':/images/conn_connecting.png',
            'connected': ':/images/conn_connected.png'
        }
        con_widgets = {
            'disconnected': QLabel(),
            'connecting': QLabel(),
            'connected': QLabel(),
        }
        con_widgets['disconnected'].setPixmap(
            QPixmap(icons['disconnected']))
        con_widgets['connecting'].setPixmap(
            QPixmap(icons['connecting']))
        con_widgets['connected'].setPixmap(
            QPixmap(icons['connected'])),
        self.ConnectionWidgets = con_widgets

        con_icons = {
            'disconnected': QIcon(icons['disconnected']),
            'connecting': QIcon(icons['connecting']),
            'connected': QIcon(icons['connected'])
        }
        self.Icons = con_icons

        self.statusIconBox = QGroupBox("Connection Status")
        statusIconLayout = QHBoxLayout()
        statusIconLayout.addWidget(self.ConnectionWidgets['disconnected'])
        statusIconLayout.addWidget(self.ConnectionWidgets['connecting'])
        statusIconLayout.addWidget(self.ConnectionWidgets['connected'])
        statusIconLayout.itemAt(1).widget().hide()
        statusIconLayout.itemAt(2).widget().hide()
        self.statusIconBox.setLayout(statusIconLayout)

    def createActions(self):
        """
        creates actions to be binded to tray icon
        """
        self.connectVPNAction = QAction("Connect to &VPN", self,
                                        triggered=self.hide)
        # XXX change action name on (dis)connect
        self.dis_connectAction = QAction("&(Dis)connect", self,
                                         triggered=self.start_or_stopVPN)
        self.minimizeAction = QAction("Mi&nimize", self,
                                      triggered=self.hide)
        self.maximizeAction = QAction("Ma&ximize", self,
                                      triggered=self.showMaximized)
        self.restoreAction = QAction("&Restore", self,
                                     triggered=self.showNormal)
        self.quitAction = QAction("&Quit", self,
                                  triggered=self.cleanupAndQuit)

    def createTrayIcon(self):
        """
        creates the tray icon
        """
        self.trayIconMenu = QMenu(self)

        self.trayIconMenu.addAction(self.connectVPNAction)
        self.trayIconMenu.addAction(self.dis_connectAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.maximizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)

    def createLogBrowser(self):
        """
        creates Browser widget for displaying logs
        (in debug mode only).
        """
        self.loggerBox = QGroupBox()
        logging_layout = QVBoxLayout()
        self.logbrowser = QTextBrowser()

        startStopButton = QPushButton("&Connect")
        startStopButton.clicked.connect(self.start_or_stopVPN)
        self.startStopButton = startStopButton

        logging_layout.addWidget(self.logbrowser)
        logging_layout.addWidget(self.startStopButton)
        self.loggerBox.setLayout(logging_layout)

        # status box

        self.statusBox = QGroupBox()
        grid = QGridLayout()

        self.updateTS = QLabel('')
        self.status_label = QLabel('Disconnected')
        self.ip_label = QLabel('')
        self.remote_label = QLabel('')

        tun_read_label = QLabel("tun read")
        self.tun_read_bytes = QLabel("0")
        tun_write_label = QLabel("tun write")
        self.tun_write_bytes = QLabel("0")

        grid.addWidget(self.updateTS, 0, 0)
        grid.addWidget(self.status_label, 0, 1)
        grid.addWidget(self.ip_label, 1, 0)
        grid.addWidget(self.remote_label, 1, 1)
        grid.addWidget(tun_read_label, 2, 0)
        grid.addWidget(self.tun_read_bytes, 2, 1)
        grid.addWidget(tun_write_label, 3, 0)
        grid.addWidget(self.tun_write_bytes, 3, 1)

        self.statusBox.setLayout(grid)

    @pyqtSlot(str)
    def onLoggerNewLine(self, line):
        """
        simple slot: writes new line to logger Pane.
        """
        if self.debugmode:
            self.logbrowser.append(line[:-1])

    def set_statusbarMessage(self, msg):
        self.statusBar().showMessage(msg)

    @pyqtSlot(object)
    def onStatusChange(self, status):
        """
        slot for status changes. triggers new signals for
        updating icon, status bar, etc.
        """

        print('STATUS CHANGED! (on Qt-land)')
        print('%s -> %s' % (status.previous, status.current))
        icon_name = self.conductor.get_icon_name()
        self.setIcon(icon_name)
        print 'icon = ', icon_name

        # change connection pixmap widget
        self.setConnWidget(icon_name)

    def setConnWidget(self, icon_name):
        #print 'changing icon to %s' % icon_name
        oldlayout = self.statusIconBox.layout()

        # XXX reuse with icons
        # XXX move states to StateWidget
        states = {"disconnected": 0,
                  "connecting": 1,
                  "connected": 2}

        for i in range(3):
            oldlayout.itemAt(i).widget().hide()
        new = states[icon_name]
        oldlayout.itemAt(new).widget().show()

    @pyqtSlot()
    def start_or_stopVPN(self):
        """
        stub for running child process with vpn
        """
        if self.vpn_service_started is False:
            self.conductor.connect()
            if self.debugmode:
                self.startStopButton.setText('&Disconnect')
            self.vpn_service_started = True

            # XXX what is optimum polling interval?
            # too little is overkill, too much
            # will miss transition states..

            self.timer.start(250.0)
            return
        if self.vpn_service_started is True:
            self.conductor.disconnect()
            # FIXME this should trigger also
            # statuschange event. why isn't working??
            if self.debugmode:
                self.startStopButton.setText('&Connect')
            self.vpn_service_started = False
            self.timer.stop()
            return

    @pyqtSlot()
    def onTimerTick(self):
        self.statusUpdate()

    @pyqtSlot()
    def statusUpdate(self):
        """
        called on timer tick
        polls status and updates ui with real time
        info about transferred bytes / connection state.
        """
        # XXX it's too expensive to poll
        # continously. move to signal events instead.

        if not self.vpn_service_started:
            return

        # XXX remove all access to manager layer
        # from here.
        if self.conductor.manager.with_errors:
            #XXX how to wait on pkexec???
            #something better that this workaround, plz!!
            time.sleep(10)
            print('errors. disconnect.')
            self.start_or_stopVPN()  # is stop

        state = self.conductor.poll_connection_state()
        if not state:
            return

        ts, con_status, ok, ip, remote = state
        self.set_statusbarMessage(con_status)
        self.setToolTip()

        ts = time.strftime("%a %b %d %X", ts)
        if self.debugmode:
            self.updateTS.setText(ts)
            self.status_label.setText(con_status)
            self.ip_label.setText(ip)
            self.remote_label.setText(remote)

        # status i/o

        status = self.conductor.manager.get_status_io()
        if status and self.debugmode:
            #XXX move this to systray menu indicators
            ts, (tun_read, tun_write, tcp_read, tcp_write, auth_read) = status
            ts = time.strftime("%a %b %d %X", ts)
            self.updateTS.setText(ts)
            self.tun_read_bytes.setText(tun_read)
            self.tun_write_bytes.setText(tun_write)

    def cleanupAndQuit(self):
        """
        cleans state before shutting down app.
        """
        # TODO:make sure to shutdown all child process / threads
        # in conductor
        self.conductor.cleanup()
        qApp.quit()
예제 #13
0
class QChatWidget(QWidget):
    def __init__(self, connectionManager, parent=None):
        QWidget.__init__(self, parent)

        self.connectionManager = connectionManager
        self.isDisabled = False
        self.wasCleared = False

        self.urlRegex = re.compile(constants.URL_REGEX)

        self.chatLog = QTextBrowser()
        self.chatLog.setOpenExternalLinks(True)

        self.chatInput = QTextEdit()
        self.chatInput.textChanged.connect(self.chatInputTextChanged)

        self.sendButton = QPushButton("Send")
        self.sendButton.clicked.connect(self.sendMessage)

        # Set the min height for the chatlog and a matching fixed height for the send button
        chatInputFontMetrics = QFontMetrics(self.chatInput.font())
        self.chatInput.setMinimumHeight(chatInputFontMetrics.lineSpacing() * 3)
        self.sendButton.setFixedHeight(chatInputFontMetrics.lineSpacing() * 3)

        hbox = QHBoxLayout()
        hbox.addWidget(self.chatInput)
        hbox.addWidget(self.sendButton)

        # Put the chatinput and send button in a wrapper widget so they may be added to the splitter
        chatInputWrapper = QWidget()
        chatInputWrapper.setLayout(hbox)
        chatInputWrapper.setMinimumHeight(chatInputFontMetrics.lineSpacing() * 3.7)

        # Put the chat log and chat input into a splitter so the user can resize them at will
        splitter = QSplitter(Qt.Vertical)
        splitter.addWidget(self.chatLog)
        splitter.addWidget(chatInputWrapper)
        splitter.setSizes([int(parent.height()), 1])

        hbox = QHBoxLayout()
        hbox.addWidget(splitter)
        self.setLayout(hbox)

        self.typingTimer = QTimer()
        self.typingTimer.setSingleShot(True)
        self.typingTimer.timeout.connect(self.stoppedTyping)

    def chatInputTextChanged(self):
        # Check if the text changed was the text box being cleared to avoid sending an invalid typing status
        if self.wasCleared:
            self.wasCleared = False
            return

        if str(self.chatInput.toPlainText())[-1:] == "\n":
            self.sendMessage()
        else:
            # Start a timer to check for the user stopping typing
            self.typingTimer.start(constants.TYPING_TIMEOUT)
            self.sendTypingStatus(constants.TYPING_START)

    def stoppedTyping(self):
        self.typingTimer.stop()
        if str(self.chatInput.toPlainText()) == "":
            self.sendTypingStatus(constants.TYPING_STOP_WITHOUT_TEXT)
        else:
            self.sendTypingStatus(constants.TYPING_STOP_WITH_TEXT)

    def sendMessage(self):
        if self.isDisabled:
            return

        self.typingTimer.stop()

        text = str(self.chatInput.toPlainText())[:-1]

        # Don't send empty messages
        if text == "":
            return

        # Convert URLs into clickable links
        text = self.__linkify(text)

        # Add the message to the message queue to be sent
        self.connectionManager.getClient(self.nick).sendChatMessage(text)

        # Clear the chat input
        self.wasCleared = True
        self.chatInput.clear()

        self.appendMessage(text, constants.SENDER)

    def sendTypingStatus(self, status):
        self.connectionManager.getClient(self.nick).sendTypingMessage(status)

    def showNowChattingMessage(self, nick):
        self.nick = nick
        self.appendMessage(
            "You are now securely chatting with " + self.nick + " :)", constants.SERVICE, showTimestampAndNick=False
        )

        self.appendMessage(
            "It's a good idea to verify the communcation is secure by selecting "
            '"authenticate buddy" in the options menu.',
            constants.SERVICE,
            showTimestampAndNick=False,
        )

    def appendMessage(self, message, source, showTimestampAndNick=True):
        color = self.__getColor(source)

        if showTimestampAndNick:
            timestamp = (
                '<font color="'
                + color
                + '">('
                + utils.getTimestamp()
                + ") <strong>"
                + (self.connectionManager.nick if source == constants.SENDER else self.nick)
                + ":</strong></font> "
            )
        else:
            timestamp = ""

        # If the user has scrolled up (current value != maximum), do not move the scrollbar
        # to the bottom after appending the message
        shouldScroll = True
        scrollbar = self.chatLog.verticalScrollBar()
        if scrollbar.value() != scrollbar.maximum() and source != constants.SENDER:
            shouldScroll = False

        self.chatLog.append(timestamp + message)

        # Move the vertical scrollbar to the bottom of the chat log
        if shouldScroll:
            scrollbar.setValue(scrollbar.maximum())

    def __linkify(self, text):
        matches = self.urlRegex.findall(text)

        for match in matches:
            text = text.replace(match[0], '<a href="%s">%s</a>' % (match[0], match[0]))

        return text

    def __getColor(self, source):
        if source == constants.SENDER:
            if qtUtils.isLightTheme:
                return "#0000CC"
            else:
                return "#6666FF"
        elif source == constants.RECEIVER:
            if qtUtils.isLightTheme:
                return "#CC0000"
            else:
                return "#CC3333"
        else:
            if qtUtils.isLightTheme:
                return "#000000"
            else:
                return "#FFFFFF"

    def disable(self):
        self.isDisabled = True
        self.chatInput.setReadOnly(True)

    def enable(self):
        self.isDisabled = False
        self.chatInput.setReadOnly(False)
예제 #14
0
    class UnInstallPage(QWizardPage):
        setProgress = pyqtSignal(int)
        message = pyqtSignal(str)

        def __init__(self, parent):
            QWizardPage.__init__(self)
            self.parent = parent

            self.setLayout(QGridLayout())
            self.setTitle('Uninstallation')
            self.setSubTitle('All selected components will be removed.')

            self.layout().addWidget(QLabel(u'Uninstallation progress'), 0, 0)
            self.progress = QProgressBar()
            self.progress.setMaximum(0)
            self.layout().addWidget(self.progress, 1, 0, 1, 2)

            self.log = QTextBrowser()
            self.layout().addWidget(self.log, 2, 0, 1, 2)

            self.setProgress.connect(self.progress.setValue)
            self.message.connect(self.log.append)
            self.is_done = False

        def initializePage(self):
            self.components = self.wizard().components
            self.startUninstallation()

        def startUninstallation(self):
            self.path = str(self.parent.options.install_path)

            self.w = Worker(lambda: self.uninstall(self.path, self.components))
            self.w.done.connect(self.endUninstall)
            self.w.error.connect(self.parent.printError)

            self.w.start()

        def uninstall(self, path, components):
            self.message.emit('Start uninstalling...')
            schema = Config(open('config/uninstall.yml'))

            self.progress.setMaximum(len(components))

            component_names = [x.name for x in components]

            i = 0
            for component in components:
                if component.name in component_names:
                    i += 1
                    self.setProgress.emit(i)
                    component.uninstall(schema[component.name], message=self.message.emit)

        def endUninstall(self):
            self.log.append(u'Finished')
            self.is_done = True
            self.completeChanged.emit()

        def isComplete(self):
            if self.is_done:
                self.wizard().finished.emit(1)
            return self.is_done
예제 #15
0
    class InstallPage(QWizardPage):
        setProgress = pyqtSignal(int)
        message = pyqtSignal(str)

        def __init__(self, parent):
            QWizardPage.__init__(self)
            self.parent = parent

            self.setLayout(QGridLayout())
            self.setTitle('Installation')
            self.setSubTitle('All selected components will be extracted.')

            self.layout().addWidget(QLabel(u'Installation progress'), 0, 0)
            self.progress = QProgressBar()
            self.progress.setMaximum(0)
            self.layout().addWidget(self.progress, 1, 0, 1, 2)

            self.log = QTextBrowser()
            self.layout().addWidget(self.log, 2, 0, 1, 2)

            self.setProgress.connect(self.progress.setValue)
            self.message.connect(self.log.append)
            self.is_done = False

        def initializePage(self):
            self.components = self.wizard().components
            self.startInstallation()

        def startInstallation(self):
            self.distrib_path = str(self.field('distrib_path').toString())
            self.path = str(self.field('path').toString())

            self.w = Worker(lambda: self.install(self.distrib_path, self.path))
            self.w.done.connect(self.endInstall)
            self.w.error.connect(self.parent.printError)

            self.w.start()

        def install(self, src, destination):
            self.message.emit(u'Started...')
            self.progress.setMaximum(len(self.components))
            for i, component in enumerate(self.components):
                self.setProgress.emit(i)
                component.install(destination, message=self.message.emit)

            self.generateUninstallList(destination, src, self.components)

        def generateUninstallList(self, install_path, distrib_path, components):
            self.message.emit(u'Generating uninstall list...')

            with open('config/uninstall.yml', 'w') as f:
                l = ''
                for i, component in enumerate(components):
                    file_list = {component.name: component.uninstall_info}
                    l += yaml.dump(file_list, default_flow_style=False, indent=4, allow_unicode=True,
                                   encoding="utf-8")
                f.write(l)
                f.close()

        def endInstall(self):
            self.log.append(u'Finished')
            self.setProgress.emit(len(self.components))
            self.is_done = True
            self.completeChanged.emit()

        def isComplete(self):
            if self.is_done:
                self.wizard().finished.emit(1)
            return self.is_done
예제 #16
0
class Window(QWidget):
 
    def __init__(self):

        QWidget.__init__(self)
        self.rawstr = r"""(?:^.*Track .*?\d*\D*)(\d{1,})(?:\D*of.*?)(\d{1,})(?:.*?MB written.*$)"""
        self.compile_obj = re.compile(self.rawstr, re.MULTILINE)
        
        self.textBrowser = QTextBrowser(self)
        self.lineEdit = QLineEdit(self)
        self.startButton = QPushButton(self.tr("Start"), self)
        self.stopButton = QPushButton(self.tr("Stop"), self)
        self.stopButton.setEnabled(False)
        
        self.list1 = QStringList()
        self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.startCommand)
        self.connect(self.startButton, SIGNAL("clicked()"), self.startCommand)
        self.connect(self.stopButton, SIGNAL("clicked()"), self.stopCommand)

        layout = QGridLayout(self)
        layout.setSpacing(8)
        layout.addWidget(self.textBrowser, 0, 0)
        layout.addWidget(self.lineEdit, 1, 0)
        layout.addWidget(self.startButton, 1, 1)
        layout.addWidget(self.stopButton, 1, 2)

 
        self.process = QProcess()
        self.connect(self.process, SIGNAL("readyReadStandardOutput()"), self.readOutput)
        self.connect(self.process, SIGNAL("readyReadStandardError()"), self.readErrors)
        self.connect(self.process, SIGNAL("finished(int)"), self.resetButtons)

    def startCommand(self):
        a=self.lineEdit.text().split(" ")
        self.process.start(a.first(), a.mid(1))

        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.textBrowser.clear()

         
        if  self.process.exitCode():
            self.textBrowser.setText(
                QString("*** Failed to run %1 ***").arg(self.lineEdit.text())
                )
            self.resetButtons()
            return

    def stopCommand(self):
        self.resetButtons()
        self.process.terminate()
        QTimer.singleShot(5000, self.process, SLOT("kill()"))


    def readOutput(self):
        a= self.process.readAllStandardOutput().data()
        match_obj = self.compile_obj.search(a)
        
        if match_obj:
            all_groups = match_obj.groups()
            group_1 = float(match_obj.group(1))
            group_2 = float(match_obj.group(2))
            g=int(group_1*100.0/group_2)
            if group_1:
                self.textBrowser.append(QString(str(g)))

    def readErrors(self):
        a= self.process.readAllStandardError().data()
        self.textBrowser.append("error: " + QString(a))
        
    def resetButtons(self,  i):
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
class showFortuneDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.vBoxSizer = QVBoxLayout()
        self.hBoxSizer = QVBoxLayout()
        self.browser = QTextBrowser()
        self.browser.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self.anotherFortuneButton = QPushButton(self.tr("One More!"), self)
        self.anotherFortuneButton.clicked.connect(
            self.onClickAnotherFortuneButton)
        self.hBoxSizer.addWidget(self.anotherFortuneButton)

        idx = random.choice(range(len(self.prm['appData']['fortunesList'])))

        self.browser.append(self.prm['appData']['fortunesList'][idx]['quote'])
        self.browser.append('\n')
        self.browser.append(self.prm['appData']['fortunesList'][idx]['author'])
        self.browser.append("In:" +
                            self.prm['appData']['fortunesList'][idx]['source'])

        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.browser.setFont(font)

        self.vBoxSizer.addWidget(self.browser)
        self.vBoxSizer.addLayout(self.hBoxSizer)
        #self.vBoxSizer.setSizeConstraint(QLayout.SetFixedSize)

        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("pychoacoustics - fortunes"))
        self.resize(450, 450)
        self.show()

    def onClickAnotherFortuneButton(self):
        self.browser.clear()
        idx = random.choice(range(len(self.prm['appData']['fortunesList'])))

        self.browser.append(self.prm['appData']['fortunesList'][idx]['quote'])
        self.browser.append('\n')
        self.browser.append(self.prm['appData']['fortunesList'][idx]['author'])
        self.browser.append("In:" +
                            self.prm['appData']['fortunesList'][idx]['source'])
예제 #18
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a "
              "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages',
                             self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)

    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.messages.clear()

    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(
                htmldiff.htmldiff(self._text,
                                  text,
                                  _("Current Document"),
                                  _("Converted Document"),
                                  wrapcolumn=100))
        else:
            self.diff.clear()

    def convertedText(self):
        return self._convertedtext or ''

    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(
                _("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']

        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'

        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                                        universal_newlines=True,
                                        env=env,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n"
                      "{message}\n").format(convert_ly=convert_ly, message=e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' +
                                     _("The document has not been changed."))
예제 #19
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        
        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        self.mainwindow = parent
        
        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.uni_diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(checked=
            QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()
        
        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        self.tabw.addTab(self.uni_diff, '')
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Reset | QDialogButtonBox.Save |
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).clicked    .connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        self.buttons.button(QDialogButtonBox.Save).clicked.connect(self.saveFile)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)
        
        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()
        
    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(_(
            "If checked, the messages of convert-ly are appended as a "
            "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.tabw.setTabText(2, _("&Diff"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.buttons.button(QDialogButtonBox.Save).setText(_("Save as file"))
        self.setCaption()
    
    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages', self.copyCheck.isChecked())
    
    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)
        diffFont = QFont("Monospace")
        diffFont.setStyleHint(QFont.TypeWriter)
        self.uni_diff.setFont(diffFont)
    
    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())
    
    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.setDiffText()
        self.messages.clear()
    
    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(htmldiff.htmldiff(
                self._text, text,
                _("Current Document"), _("Converted Document"),
                wrapcolumn=100))
        else:
            self.diff.clear()
            
    def setDiffText(self, text=''):
        if text:
            difflist = list(difflib.unified_diff(
                    self._text.split('\n'), text.split('\n'), 
                    _("Current Document"), _("Converted Document")))
            diffHLstr = self.diffHighl(difflist)
            self.uni_diff.setHtml(diffHLstr)
        else:
            self.uni_diff.clear()
    
    def convertedText(self):
        return self._convertedtext or ''
    
    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()
        self.setDiffText()
        
    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(_(
                "Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']
        
        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'
        
        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                    universal_newlines = True,
                    env = env,
                    stdin = subprocess.PIPE,
                    stdout = subprocess.PIPE,
                    stderr = subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(_(
                    "Could not start {convert_ly}:\n\n"
                    "{message}\n").format(convert_ly = convert_ly, message = e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            self.setDiffText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' + _("The document has not been changed."))

    def saveFile(self):
        """Save content in tab as file"""
        tabdata = self.getTabData(self.tabw.currentIndex())
        doc = self.mainwindow.currentDocument()
        orgname = doc.url().toLocalFile()
        filename = os.path.splitext(orgname)[0] + '['+tabdata.filename+']'+'.'+tabdata.ext
        caption = app.caption(_("dialog title", "Save File"))
        filetypes = '{0} (*.txt);;{1} (*.htm);;{2} (*)'.format(_("Text Files"), _("HTML Files"), _("All Files"))
        filename = QFileDialog.getSaveFileName(self.mainwindow, caption, filename, filetypes)
        if not filename:
            return False # cancelled
        f = open(filename, 'w')
        f.write(tabdata.text.encode('utf-8'))
        f.close()
		
    def getTabData(self, index):
        """Get content of current tab from current index"""
        if index == 0:
            return FileInfo('message', 'txt', self.messages.toPlainText())
        elif index == 1:
            return FileInfo('html-diff', 'html', self.diff.toHtml())
        elif index == 2:
            return FileInfo('uni-diff', 'diff', self.uni_diff.toPlainText())
            
    def diffHighl(self, difflist):
        """Return highlighted version of input."""
        result = []
        for l in difflist:
            if l.startswith('-'):
                s = '<span style="color: red; white-space: pre-wrap;">'
            elif l.startswith('+'):
                s = '<span style="color: green; white-space: pre-wrap;">'
            else:
                s = '<span style="white-space: pre-wrap;">'
            h = l.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
            result.append(s + h + '</span>')
        return '<br>'.join(result)
예제 #20
0
class MiniCalculation(QDialog):
    AppName = u"迷你计算器"

    def __init__(self, parent=None):
        super(MiniCalculation, self).__init__(parent)
        self.btnHelpState = False
        self.setWindowTitle(MiniCalculation.AppName)
        self.txtBrower = QTextBrowser()
        self.txtLine = QLineEdit()
        self.txtLine.setPlaceholderText(u"请输入表达式,按回车结束...")

        self.btnCal = QPushButton(u"计算")
        self.btnClear = QPushButton(u"清空")
        self.btnHelp = QPushButton(u"特殊函数表>>")
        self.btnHelp.setCheckable(True)
        self.btnHelp.setChecked(True)

        mathList = [s for s in dir(math) if not s.startswith("__")]
        self.listWidget = QListWidget()
        self.listWidget.addItems(mathList)
        for i in range(len(mathList)):
            item = self.listWidget.item(i)
            strFun = item.text() + '.__doc__'
            item.setToolTip(eval(str(strFun)))
        self.listWidget.setMaximumWidth(100)

        midLay = QHBoxLayout()
        midLay.addWidget(self.btnCal)
        midLay.addWidget(self.btnClear)
        midLay.addStretch()
        midLay.addWidget(self.btnHelp)

        bottomLay = QHBoxLayout()
        bottomLay.addWidget(self.txtBrower)
        bottomLay.addWidget(self.listWidget)

        lay = QVBoxLayout()
        lay.addWidget(self.txtLine)
        lay.addItem(midLay)
        lay.addItem(bottomLay)

        self.resize(450, 300)
        self.setLayout(lay)
        self.updateUI()

        self.btnCal.clicked.connect(self.btnCalClicked)
        self.btnClear.clicked.connect(self.txtLine.clear)
        self.btnClear.clicked.connect(self.txtBrower.clear)
        self.btnHelp.clicked.connect(self.updateUI)
        self.listWidget.itemDoubleClicked.connect(self.listItemDoubleClicked)

    def updateUI(self):
        state = not self.btnHelp.isChecked()
        self.listWidget.setHidden(state)
        text = u"特殊函数表>>" if state else u"特殊函数表<<"
        self.btnHelp.setText(text)

    def btnCalClicked(self):
        try:
            txt = str(self.txtLine.text())
            self.txtBrower.append("%s = <b>%s</b>" % (txt, eval(txt)))
        except UnicodeEncodeError:
            QMessageBox.warning(self,u"QData -- 迷你计算机",
                    u"表达式中存在中文或全角字符\n",
                    QMessageBox.Ok)
        except:
            self.txtBrower.append("<font color=red>%s <b>is invalid</b>" % txt)

    def listItemDoubleClicked(self):
        item = self.listWidget.currentItem()
        self.txtLine.insert(item.text())
        self.txtLine.setFocus()
예제 #21
0
class NetWidget(QWidget):
       
    def __init__(self,parent = None):
        super(NetWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px")#设置整体的字体大小
        
        
        self.auto = False
        self.pro = QProcess(self)
#         self.tipDlg = TipDialog()
#         self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作
        
            #初始化comBox控件,并且为其添加选项
        self.comBox = QComboBox()
        self.comBox.setFixedWidth(120)
        self.comBox.insertItem(0, self.tr("ping"))
        self.comBox.insertItem(1, self.tr("ifconfig"))
        self.comBox.insertItem(2, self.tr("display"))
        #self.comBox.insertItem(3, self.tr("traceroute"))
        self.comBox.insertItem(4, self.tr("top"))
        self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联
        """
        #初始话控件设置
        #lineEdit,固定长度
        #runButton,显示字符串,信号量
        #pingLabel,当前显示字符
        #textBrower
          """ 
        self.lineEdit = QLineEdit()
        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit.setFixedWidth(250)
        self.runButton = QPushButton(self.tr("Run"))
        self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
        self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked)
        self.pingLabel = QLabel()#初始话,之后在函数操作中会改变
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser = QTextBrowser()
        """
            #布局一上,横向布局
            #将comBox,lineEdit,runButton添加到布局中
            #设置前面空为20和后面空为280
            """
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.comBox)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        #hLayout1.addStretch()
        hLayout1.addSpacing(280)
        
            #布局二中,横向布局
            #将pingLabel添加到布局中,并且诶设置前面的空白为20
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.pingLabel)
        
            #布局三下
            #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textBrowser)
        hLayout3.addSpacing(60)
        
            #主题布局总,纵向布局
            #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(40)
        self.setLayout(mainLayout)
        
        
        self.thread = MyThread()
        self.connect(self.thread,SIGNAL("getoutput"),self.append)
        
        
    def append(self,actionType):
        self.textBrowser.clear()
        self.textBrowser.append(actionType)
        #cursor = QTextCursor()
        #self.runButton.setText(self.tr("Stop"))
        
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.Start)
        self.textBrowser.setTextCursor(cursor)
        #changeLabel = QLabel()
    
    def onActivated(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        """#comBox的相应函数,随着comBox中字符串的改变,分别控制pingLabel的显示,以及lineEdit和textBrower的显示清除和可用状态
            #如果comBox当前的字符串文字为ping
            #pingLabel的文字设置为"提示:请在文本框中输入要ping的目标地址,然后点击执行获取结果",保持当前大小
            #lineEdit中内容清除,设置为不可用
            #textBrower清空"""
        if(self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setDisabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为ifconfig
            #类上所说
        elif(self.comBox.currentText() == "ifconfig"):
            self.pingLabel.setText(self.tr("Tip:get the net information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为display
        elif(self.comBox.currentText() == "display"):
            self.pingLabel.setText(self.tr("Tip:get the resolution information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
        
        elif(self.comBox.currentText() == "top"):
    
            self.pingLabel.setText(self.tr("Tip:run tom command"))
            self.pingLabel.adjustSize()
            self.lineEdit.setEnabled(False)
            self.lineEdit.clear()
            self.textBrowser.clear()
            #按钮的响应函数
    def runButton_clicked(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        #self.pro = QProcess(self)#外部程序使用声明
        desktop = QApplication.desktop()#获得桌面
        self.textBrowser.clear()#清除
        cmdstr = QString()
        center = QString()
        goal = QString()
        #comBox当前text为ping
        if (self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            if (self.runButton.text() == self.tr("Run")) :
                center = self.lineEdit.text().trimmed()
                if not center:
                    InfoHintDialog(self.tr("please input the IP address")).exec_()
#                     self.tipDlg.setTip(self.tr("请输入ping地址!!!"))
#                     self.tipDlg.show()
#                     self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
                    self.runButton.setText(self.tr("Run"))
                else:
                    self.comBox.setDisabled(True)
                    self.pro = QProcess(self)
                    self.runButton.setText(self.tr("stop ping"))
                    cmdstr = "ping " +center
                    self.textBrowser.clear()
                    self.textBrowser.append(self.tr(" ping ")+center+self.tr(" result:"))
            else:
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
                self.pro.close()
        elif(self.comBox.currentText() == "ifconfig"):
            self.pro = QProcess(self)
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            cmdstr = "ifconfig"
#             #如果comBox当前为traceroute
#         elif(self.comBox.currentText() == "traceroute"):
#                 goal = self.lineEdit.text()
#                 if (self.runButton.text() == u"执行"):
#                     if( goal.isEmpty() or goal.isNull() ):
#                         InfoHintDialog(u'请输入tracer地址:').exec_()
# #                         self.tipDlg.setTip(self.tr("请输入tracer地址:"))
# #                         self.tipDlg.show()
# #                         self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
# #                         
#                         #QMessageBox.information(self,self.tr("错误"),self.tr("请输入traceroute的目标地址"))
#                         #return
#                     else:
#                         self.proc = QProcess(self)
#                         #self.textBrowser.clear()
#                         cmdstrc = "traceroute -n "+ goal
#                         self.proc.start(cmdstrc)
#                         self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR)
#                         self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR)
#                         if self.proc.waitForStarted(10) == True:
#                             self.comBox.setDisabled(True)
#                             self.runButton.setText(self.tr("停止执行"))
#                 else:
#                     self.runButton.setText(self.tr("执行"))
#                     self.comBox.setDisabled(False)
#                     self.proc.close()
#             #如果comBox当前为display
        elif (self.comBox.currentText() == "display"):
            self.pro = QProcess(self)
            cmdstr = "../lib/ccr_jytcapi display"
            self.textBrowser.clear()
            #如果当前命令cmdstr不为空,则
        elif (self.comBox.currentText() == "top"):
            if self.runButton.text() == self.tr("Run") :
                self.thread.start()
                self.comBox.setDisabled(True)
                self.runButton.setText(self.tr("stop top"))
            else:
                self.textBrowser.clear()
                self.thread.auto = False
                #self.thread.destroyed()
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
        if (cmdstr != ""):
                self.pro.start(cmdstr)#开启执行命令
                self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数
                self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数
            
            #读取控制台输出
    def read(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardOutput())
        self.textBrowser.append(res)#添加到text框
        #读取错误
    def readError(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardError())
        self.textBrowser.append(res)
    def readR(self):
        
        res = QString.fromLocal8Bit(self.proc.readAllStandardOutput())
        #self.textBrowser.clear()
        self.textBrowser.append(res)
        


    def readErrorR(self):

        res = QString.fromLocal8Bit(self.proc.readAllStandardError())
        self.textBrowser.append(res)
        
    def updateWindow(self):
        if self.pro.isOpen():
            self.pro.close()
            
        self.thread.auto = False
        self.comBox.setDisabled(False)
        self.comBox.setCurrentIndex(0)
        self.runButton.setText((self.tr("Run")))
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser.clear()
예제 #22
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ""
        self._convertedtext = ""
        self._encoding = None

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(checked=QSettings().value("convert_ly/copy_messages", True) not in (False, "false"))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, "")
        self.tabw.addTab(self.diff, "")

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset | QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)

        layout = QVBoxLayout()
        self.setLayout(layout)

        top = QHBoxLayout()
        top.addWidget(self.fromVersionLabel)
        top.addWidget(self.fromVersion)
        top.addWidget(self.reason)
        top.addStretch()
        top.addWidget(self.toVersionLabel)
        top.addWidget(self.toVersion)

        layout.addLayout(top)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        util.saveDialogSize(self, "convert_ly/dialog/size", QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a " "comment to the end of the document.")
        )
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue("convert_ly/copy_messages", self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData("editor").font
        self.diff.setFont(font)

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()

    def setConvertedText(self, text=""):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(makeHtmlDiff(self._text, text))
        else:
            self.diff.clear()

    def convertedText(self):
        return self._convertedtext or ""

    def setDocument(self, doc):
        v = documentinfo.info(doc).versionString()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or "UTF-8"
        self.setConvertedText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(_("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        convert_ly = os.path.join(info.bindir(), info.convert_ly)

        # on Windows the convert-ly command is not directly executable, but
        # must be started using the LilyPond-provided Python interpreter
        if os.name == "nt":
            if not os.access(convert_ly, os.R_OK) and not convert_ly.endswith(".py"):
                convert_ly += ".py"
            command = [info.python(), convert_ly]
        else:
            command = [convert_ly]
        command += ["-f", fromVersion, "-t", toVersion, "-"]

        # if the user wants english messages, do it also here
        env = None
        if QSettings().value("lilypond_settings/no_translation", False) in (True, "true"):
            env = dict(os.environ)
            env["LANGUAGE"] = "C"

        with util.busyCursor():
            try:
                proc = subprocess.Popen(
                    command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n" "{message}\n").format(convert_ly=convert_ly, message=e)
                )
                return
            self.messages.setPlainText(err.decode("UTF-8"))
            self.setConvertedText(out.decode("UTF-8"))
            if not out or self._convertedtext == self._text:
                self.messages.append("\n" + _("The document has not been changed."))
예제 #23
0
class QChatWidget(QWidget):
    def __init__(self, connectionManager, parent=None):
        QWidget.__init__(self, parent)

        self.connectionManager = connectionManager
        self.isDisabled = False
        self.wasCleared = False

        self.urlRegex = re.compile(constants.URL_REGEX)

        self.chatLog = QTextBrowser()
        self.chatLog.setOpenExternalLinks(True)

        self.chatInput = QTextEdit()
        self.chatInput.textChanged.connect(self.chatInputTextChanged)

        self.sendButton = QPushButton("Send")
        self.sendButton.clicked.connect(self.sendMessage)

        # Set the min height for the chatlog and a matching fixed height for the send button
        chatInputFontMetrics = QFontMetrics(self.chatInput.font())
        self.chatInput.setMinimumHeight(chatInputFontMetrics.lineSpacing() * 3)
        self.sendButton.setFixedHeight(chatInputFontMetrics.lineSpacing() * 3)

        hbox = QHBoxLayout()
        hbox.addWidget(self.chatInput)
        hbox.addWidget(self.sendButton)

        # Put the chatinput and send button in a wrapper widget so they may be added to the splitter
        chatInputWrapper = QWidget()
        chatInputWrapper.setLayout(hbox)
        chatInputWrapper.setMinimumHeight(chatInputFontMetrics.lineSpacing() *
                                          3.7)

        # Put the chat log and chat input into a splitter so the user can resize them at will
        splitter = QSplitter(Qt.Vertical)
        splitter.addWidget(self.chatLog)
        splitter.addWidget(chatInputWrapper)
        splitter.setSizes([int(parent.height()), 1])

        hbox = QHBoxLayout()
        hbox.addWidget(splitter)
        self.setLayout(hbox)

        self.typingTimer = QTimer()
        self.typingTimer.setSingleShot(True)
        self.typingTimer.timeout.connect(self.stoppedTyping)

    def chatInputTextChanged(self):
        # Check if the text changed was the text box being cleared to avoid sending an invalid typing status
        if self.wasCleared:
            self.wasCleared = False
            return

        if str(self.chatInput.toPlainText())[-1:] == '\n':
            self.sendMessage()
        else:
            # Start a timer to check for the user stopping typing
            self.typingTimer.start(constants.TYPING_TIMEOUT)
            self.sendTypingStatus(constants.TYPING_START)

    def stoppedTyping(self):
        self.typingTimer.stop()
        if str(self.chatInput.toPlainText()) == '':
            self.sendTypingStatus(constants.TYPING_STOP_WITHOUT_TEXT)
        else:
            self.sendTypingStatus(constants.TYPING_STOP_WITH_TEXT)

    def sendMessage(self):
        if self.isDisabled:
            return

        self.typingTimer.stop()

        text = str(self.chatInput.toPlainText())[:-1]

        # Don't send empty messages
        if text == '':
            return

        # Convert URLs into clickable links
        text = self.__linkify(text)

        # Add the message to the message queue to be sent
        self.connectionManager.getClient(self.nick).sendChatMessage(text)

        # Clear the chat input
        self.wasCleared = True
        self.chatInput.clear()

        self.appendMessage(text, constants.SENDER)

    def sendTypingStatus(self, status):
        self.connectionManager.getClient(self.nick).sendTypingMessage(status)

    def showNowChattingMessage(self, nick):
        self.nick = nick
        self.appendMessage("You are now securely chatting with " + self.nick +
                           " :)",
                           constants.SERVICE,
                           showTimestampAndNick=False)

        self.appendMessage(
            "It's a good idea to verify the communcation is secure by selecting "
            "\"authenticate buddy\" in the options menu.",
            constants.SERVICE,
            showTimestampAndNick=False)

    def appendMessage(self, message, source, showTimestampAndNick=True):
        color = self.__getColor(source)

        if showTimestampAndNick:
            timestamp = '<font color="' + color + '">(' + utils.getTimestamp() + ') <strong>' + \
                        (self.connectionManager.nick if source == constants.SENDER else self.nick) + \
                        ':</strong></font> '
        else:
            timestamp = ''

        # If the user has scrolled up (current value != maximum), do not move the scrollbar
        # to the bottom after appending the message
        shouldScroll = True
        scrollbar = self.chatLog.verticalScrollBar()
        if scrollbar.value() != scrollbar.maximum(
        ) and source != constants.SENDER:
            shouldScroll = False

        self.chatLog.append(timestamp + message)

        # Move the vertical scrollbar to the bottom of the chat log
        if shouldScroll:
            scrollbar.setValue(scrollbar.maximum())

    def __linkify(self, text):
        matches = self.urlRegex.findall(text)

        for match in matches:
            text = text.replace(match[0],
                                '<a href="%s">%s</a>' % (match[0], match[0]))

        return text

    def __getColor(self, source):
        if source == constants.SENDER:
            if qtUtils.isLightTheme:
                return '#0000CC'
            else:
                return '#6666FF'
        elif source == constants.RECEIVER:
            if qtUtils.isLightTheme:
                return '#CC0000'
            else:
                return '#CC3333'
        else:
            if qtUtils.isLightTheme:
                return '#000000'
            else:
                return '#FFFFFF'

    def disable(self):
        self.isDisabled = True
        self.chatInput.setReadOnly(True)

    def enable(self):
        self.isDisabled = False
        self.chatInput.setReadOnly(False)
예제 #24
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        
        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        
        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(checked=
            QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()
        
        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Reset |
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        top = QHBoxLayout()
        top.addWidget(self.fromVersionLabel)
        top.addWidget(self.fromVersion)
        top.addWidget(self.reason)
        top.addStretch()
        top.addWidget(self.toVersionLabel)
        top.addWidget(self.toVersion)
        
        layout.addLayout(top)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        
    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(_(
            "If checked, the messages of convert-ly are appended as a "
            "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()
    
    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages', self.copyCheck.isChecked())
    
    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)
        
    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
    
    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(htmldiff.htmldiff(
                self._text, text,
                _("Current Document"), _("Converted Document"),
                wrapcolumn=100))
        else:
            self.diff.clear()
    
    def convertedText(self):
        return self._convertedtext or ''
    
    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()
        
    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(_(
                "Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']
        
        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'
        
        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                    universal_newlines = True,
                    env = env,
                    stdin = subprocess.PIPE,
                    stdout = subprocess.PIPE,
                    stderr = subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(_(
                    "Could not start {convert_ly}:\n\n"
                    "{message}\n").format(convert_ly = convert_ly, message = e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' + _("The document has not been changed."))
예제 #25
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setWindowFlags(Qt.FramelessWindowHint
                            | Qt.WindowMinimizeButtonHint)
        self.setWindowTitle(u"鱿鱼")
        self.setFixedSize(800, 600)
        self.setObjectName('principal')
        self.createGUI()

    def createGUI(self):
        self.frame_window = QWidget(self)
        self.frame_window.setGeometry(0, 0, 800, 40)
        self.frame_window.setObjectName('frame_window')
        self.title_frame = QLabel(self.frame_window)
        self.title_frame.setGeometry(0, 0, 800, 40)
        self.title_frame.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.title_frame.setFont(QFont("微软雅黑", 20, QFont.Bold))
        self.title_frame.setText(u" 鱿鱼-阿里云白名单设置")
        self.title_frame.setObjectName('title_frame')
        # buttons
        clsfont = self.font() or QFont()
        clsfont.setFamily('Webdings')
        self.button_close = QPushButton('r', self.frame_window, font=clsfont)
        self.button_close.setGeometry(760, 0, 40, 40)
        self.button_close.setObjectName('button_close')
        self.button_close.setToolTip(u'关闭')
        self.button_close.enterEvent(
            self.button_close.setCursor(Qt.PointingHandCursor))
        self.button_min = QPushButton('0', self.frame_window, font=clsfont)
        self.button_min.setGeometry(720, 0, 40, 40)
        self.button_min.setObjectName('button_min')
        self.button_min.setToolTip(u'最小化')
        self.button_min.enterEvent(
            self.button_min.setCursor(Qt.PointingHandCursor))
        ###左边选择栏部分
        self.GroupBox_checkbox = QGroupBox(self)
        self.GroupBox_checkbox.setTitle(u'选择白名单组')
        self.GroupBox_checkbox.setGeometry(10, 50, 200, 540)
        self.ecs_test = QCheckBox(u'测试环境服务器', self.GroupBox_checkbox)
        self.ecs_test.enterEvent(self.ecs_test.setCursor(
            Qt.PointingHandCursor))
        self.ecs_test.setChecked(True)
        self.ecs_test.setGeometry(20, 30, 150, 30)
        self.rds_mysql = QCheckBox(u'MySQL数据库', self.GroupBox_checkbox)
        self.rds_mysql.enterEvent(
            self.rds_mysql.setCursor(Qt.PointingHandCursor))
        self.rds_mysql.setChecked(True)
        self.rds_mysql.setGeometry(20, 60, 150, 30)
        self.rds_sqlserver = QCheckBox(u'SQLServer数据库', self.GroupBox_checkbox)
        self.rds_sqlserver.enterEvent(
            self.rds_sqlserver.setCursor(Qt.PointingHandCursor))
        self.rds_sqlserver.setChecked(True)
        self.rds_sqlserver.setGeometry(20, 90, 150, 30)
        ###右边IP设置部分
        self.GroupBox_ipset = QGroupBox(self)
        self.GroupBox_ipset.setTitle(u'公网IP配置')
        self.GroupBox_ipset.setGeometry(220, 50, 570, 200)
        self.label_outip = QLabel(self.GroupBox_ipset,
                                  objectName="label_outip")
        self.label_outip.setText(u'公网IP:')
        self.label_outip.setGeometry(15, 30, 75, 30)
        self.line_outip = QLineEdit(self.GroupBox_ipset)
        self.line_outip.setMinimumWidth(200)
        self.line_outip.setGeometry(85, 30, 150, 30)
        self.line_outip.setFont(QFont("Timers", 13, QFont.Bold))
        self.line_outip.setStyleSheet("color:green")
        self.button_getip = QPushButton(u'自动获取公网IP',
                                        self.GroupBox_ipset,
                                        objectName="button_getip")
        self.button_getip.setToolTip(u'从ip138上抓取本机公网IP')
        self.button_getip.enterEvent(
            self.button_getip.setCursor(Qt.PointingHandCursor))
        self.button_getip.setGeometry(300, 30, 110, 30)
        self.button_setup = QPushButton(u'添加',
                                        self.GroupBox_ipset,
                                        objectName="button_setup")
        self.button_setup.enterEvent(
            self.button_setup.setCursor(Qt.PointingHandCursor))
        self.button_setup.setToolTip(u'将该IP添加至已选白名单组中')
        self.button_setup.setGeometry(430, 30, 110, 30)
        ###右边消息输出部分
        self.GroupBox_text = QGroupBox(self)
        self.GroupBox_text.setGeometry(220, 260, 570, 330)
        self.browser_text = QTextBrowser(self.GroupBox_text)
        self.browser_text.setGeometry(0, 0, 570, 330)
        self.browser_text.setFont(QFont("Roman times", 12))
        self.browser_text.setObjectName('browser_text')

        # conexiones
        self.button_close.clicked.connect(self.close)
        self.button_min.clicked.connect(self.showMinimized)
        self.button_getip.clicked.connect(self.auto_ip)
        self.button_setup.clicked.connect(self.setup)

    def auto_ip(self):
        self.line_outip.clear()
        self.button_getip.setEnabled(False)
        self.th_get_ip = GETIP()
        self.th_get_ip.ip_line_Signal.connect(self.show_ip_info)
        self.th_get_ip.start()

    def show_ip_info(self, ip=None, status=1):
        self.button_getip.setEnabled(True)
        if status:
            self.line_outip.setText(ip)
        else:
            self.browser_text.append(ip)

    def setup(self):
        myip = self.line_outip.text()
        if myip and validate_ip(myip):
            check_list = []
            if self.ecs_test.isChecked():
                check_list.append('ecs_test')
            if self.rds_mysql.isChecked():
                check_list.append('rds_mysql')
            if self.rds_sqlserver.isChecked():
                check_list.append('rds_sqlserver')
            if len(check_list) == 0:
                self.browser_text.append(u'没什么事可做的~')
            else:
                self.button_setup.setEnabled(False)
                self.th_setup = SETIP(myip, check_list)
                self.th_setup.text_browser_Signal.connect(self.show_text)
                self.th_setup.start()
        else:
            self.browser_text.append(u'请填入正确的IP地址!')

    def show_text(self, text=None, end=0):
        if end:
            self.button_setup.setEnabled(True)
        if text:
            self.browser_text.append(text)

    def mousePressEvent(self, event):
        self.offset = event.pos()

    def mouseMoveEvent(self, event):
        x = event.globalX()
        y = event.globalY()
        x_w = self.offset.x()
        y_w = self.offset.y()
        self.move(x - x_w, y - y_w)