Exemple #1
0
class UpdateDialog(QDialog):
    """The dialog for update."""
    def __init__(self):
        super(UpdateDialog, self).__init__()
        vbox = QVBoxLayout(self)
        self.closed = False
        self.setModal(True)
        self.resize(500, 250)

        vbox.addWidget(QLabel(u"Actualización de la lista de episodios:"))
        self.text = QPlainTextEdit()
        self.text.setReadOnly(True)
        vbox.addWidget(self.text)

        bbox = QDialogButtonBox(QDialogButtonBox.Cancel)
        bbox.rejected.connect(self.reject)
        vbox.addWidget(bbox)

    def append(self, text):
        """Append some text in the dialog."""
        self.text.appendPlainText(text.strip())

    def closeEvent(self, event):
        """It was closed."""
        self.closed = True
Exemple #2
0
class UpdateDialog(QDialog):
    """The dialog for update."""
    def __init__(self):
        super(UpdateDialog, self).__init__()
        vbox = QVBoxLayout(self)
        self.closed = False
        self.setModal(True)
        self.resize(500, 250)

        vbox.addWidget(QLabel(u"Actualización de la lista de episodios:"))
        self.text = QPlainTextEdit()
        self.text.setReadOnly(True)
        vbox.addWidget(self.text)

        bbox = QDialogButtonBox(QDialogButtonBox.Cancel)
        bbox.rejected.connect(self.reject)
        vbox.addWidget(bbox)

    def append(self, text):
        """Append some text in the dialog."""
        self.text.appendPlainText(text.strip())

    def closeEvent(self, event):
        """It was closed."""
        self.closed = True
Exemple #3
0
class LogDialog(QDialog):
    def __init__(self, parent, rpt_file_path):
        self.rpt_file_path = rpt_file_path

        QDialog.__init__(self, parent)

        self.setWindowTitle('Log: ' + self.rpt_file_path)

        main_lay = QVBoxLayout(self)

        self.txt_log = QPlainTextEdit(self)
        self.txt_log.setMinimumWidth(500)
        self.txt_log.setMinimumHeight(300)
        main_lay.addWidget(self.txt_log)

        self.btn_close = QPushButton('Close')
        self.btn_close.clicked.connect(self.close_dialog)
        main_lay.addWidget(self.btn_close)

        self.fill_txt()

    def close_dialog(self):
        self.close()

    def fill_txt(self):
        with codecs.open(self.rpt_file_path, 'r', encoding='UTF-8') as inp_f:
            lines = inp_f.read().splitlines()

        for line in lines:
            self.txt_log.appendPlainText(line.replace('\b', ''))

        # Scroll up
        self.txt_log.moveCursor(QTextCursor.Start)
        self.txt_log.ensureCursorVisible()
Exemple #4
0
class DumpWindow(QDialog):
    def __init__(self, parent, uri):
        QDialog.__init__(self, parent)

        if uri.startswith('unix://'):
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(uri[len('unix://'):])
        elif uri.startswith('tcp://'):
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            parsed = re.split('[:/]', uri[len('tcp://'):])
            addr = (parsed[0], int(parsed[1]))
            self.sock.connect(addr)
        else:
            raise Exception('Unsupported server URI `%s' % uri)

        self.sock.setblocking(False)

        self.fLayout = QVBoxLayout(self)
        self.setLayout(self.fLayout)

        self.fTextArea = QPlainTextEdit(self)
        self.fLayout.addWidget(self.fTextArea)

        self.resize(500, 600)
        self.setWindowTitle(self.tr("Dump Window"))

        self.fTimerId = self.startTimer(100)
        self.fTmpData = b""

    def __del__(self):
        self.sock.close()

    def timerEvent(self, event):
        if event.timerId() == self.fTimerId:
            self.dump()

        QDialog.timerEvent(self, event)

    def dump(self):
        while True:
            try:
                c = self.sock.recv(1)
            except:
                break

            if c == b"\n":
                self.fTextArea.appendPlainText(str(self.fTmpData, encoding="utf-8", errors="ignore"))
                self.fTmpData = b""
            else:
                self.fTmpData += c
Exemple #5
0
class TextLogger(logging.Handler):
    ''' A logger to record the users actions and write them to a QPlainTextEdit widget.
    '''
    def __init__(self, parent):
        super(TextLogger, self).__init__()

        self.widget = QPlainTextEdit(parent)
        self.widget.setReadOnly(True)

    def emit(self, record):
        ''' Log a message.
        Args:
            record (str) : the message to log.
        '''
        message = self.format(record)
        self.widget.appendPlainText(message)
    def print_result(self, result, history):
        """
            Print processing result
        """
        self.result = result
        self.history = history

        message = "Filter " + self.history['process'] + "    params: "
        for param in self.history['params'].keys():
            message += " " + param + " : " + str(
                self.history['params'][param]) + " |"

        self.historyBox.appendPlainText(message)

        if result['type'] == "sensor":
            self.draw_chart(self.result['data'])

        elif result['type'] == "sensor list":
            self.draw_multiple_chart(self.result['data'])

        elif result['type'] == "dict list":
            field = QPlainTextEdit()
            field.setReadOnly(True)
            for elem in self.result['data']:
                tmp = ""
                for key in elem.keys():
                    tmp += key + " : " + str(elem[key]) + " "
                field.appendPlainText(tmp)

            self.clear_layout(self.resultFrame.layout())
            self.resultFrame.layout().addWidget(field)

        elif result['type'] == "dict":
            field = QPlainTextEdit()
            field.setReadOnly(True)
            data = self.result['data']
            for key in data.keys():
                field.appendPlainText(key + " : " + str(data[key]))

            self.clear_layout(self.resultFrame.layout())
            self.resultFrame.layout().addWidget(field)
        else:
            print "undefined result"

        self.base_thread.quit()
Exemple #7
0
class ListEditor(QDialog):

    def __init__(self, parent=None):
        """Create layout for the blocked domains"""
        super(ListEditor, self).__init__(parent)
        self.setWindowTitle("Website Blocklist")
        # Create widgets
        self.tableView = QPlainTextEdit()


        # if not os.path.isfile(os.path.join(config_dir, 'blocklist')):
        #     self.createBlockFile()
        # self.loadBlockFile()

        layout = QVBoxLayout()
        layout.addWidget(self.tableView)
        self.saveButton = QPushButton("Done")
        self.saveButton.clicked.connect(self.closeList)
        layout.addWidget(self.saveButton, 0, Qt.AlignRight)

        self.setLayout(layout)

    def loadBlockFile(self):
        """If a site block file exists, load it"""
        file = open(homedir + "blocklist")
        self.tableView.appendPlainText(file.read())
        print(file)
        file.close()

    def createBlockFile(self):
        """Create a new site block file"""
        file = open(homedir + "blocklist", 'w')
        file.write("# Add one website per line #\nexample.com\n")
        file.close()

    def updateBlocks(self):
        """Write blocked sites to file"""
        file = open(homedir + "blocklist", 'w+')
        file.write(list.tableView.toPlainText())

    def closeList(self):
        """Hide the list"""
        self.updateBlocks()
        list.hide()
class ListEditor(QDialog):

    def __init__(self, parent=None):
        """Create layout for the blocked domains"""
        super(ListEditor, self).__init__(parent)
        self.setWindowTitle("Website Blocklist")
        # Create widgets
        self.tableView = QPlainTextEdit()
	config_dir="~/"

        if not os.path.isfile(os.path.join(config_dir, 'blocklist')):
            self.createBlockFile()
        self.loadBlockFile()

        layout = QVBoxLayout()
        layout.addWidget(self.tableView)
        self.saveButton = QPushButton("Done")
        self.saveButton.clicked.connect(self.closeList)
        layout.addWidget(self.saveButton, 0, Qt.AlignRight)

        self.setLayout(layout)

    def loadBlockFile(self):
        """If a site block file exists, load it"""
        file = open(homedir + "blocklist")
        self.tableView.appendPlainText(file.read())
        file.close()

    def createBlockFile(self):
        """Create a new site block file"""
        file = open(homedir + "blocklist", 'w')
        file.write("# Add one website per line #\nexample.com\n")
        file.close()

    def updateBlocks(self):
        """Write blocked sites to file"""
        file = open(homedir + "blocklist", 'w+')
        file.write(list.tableView.toPlainText())

    def closeList(self):
        """Hide the list"""
        self.updateBlocks()
        list.hide()
class ListEditor(QDialog):

    def __init__(self, parent=None):
        # Create layout for the blocked domains
        super(ListEditor, self).__init__(parent)
        self.setWindowTitle("Website Blocklist")
        # Create widgets
        self.tableView  = QPlainTextEdit()
        self.tableView.appendPlainText("# Add one website per line #\nexample.com\n")

        layout = QVBoxLayout()
        layout.addWidget(self.tableView)
        self.saveButton = QPushButton("Done")
        self.saveButton.clicked.connect(self.closeList)
        layout.addWidget(self.saveButton, 0, Qt.AlignRight)
        
        self.setLayout(layout)
    
    def closeList(self):
        # Hide the list
        """docstring for closeList"""
        list.hide()
class SystemLog(object):
    def __init__(self, display_name, source_name):
        self.display_name = display_name
        self.source_name = source_name  # FIXME: need to handle rotated logs
        self.last_filename = os.path.join(get_home_path(), display_name)
        self.content = ''
        self.edit = QPlainTextEdit()
        self.normal_font = self.edit.font()
        self.monospace_font = QFont('monospace')

        self.edit.setUndoRedoEnabled(False)
        self.edit.setReadOnly(True)
        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setPlainText(
            'Click "Refresh" to download {0}.'.format(display_name))

        self.monospace_font.setStyleHint(QFont.TypeWriter)

    def log(self, message, bold=False, pre=False):
        if bold:
            self.edit.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
        elif pre:
            self.edit.appendHtml(u'<pre>{0}</pre>'.format(message))
        else:
            self.edit.appendPlainText(message)

    def reset(self):
        self.content = None

        self.edit.setPlainText('')
        self.edit.setFont(self.normal_font)

    def set_content(self, content):
        self.content = content

        self.edit.setPlainText('')
        self.edit.setFont(self.monospace_font)
        self.edit.setPlainText(content)
class SystemLog(object):
    def __init__(self, display_name, source_name):
        self.display_name   = display_name
        self.source_name    = source_name # FIXME: need to handle rotated logs
        self.last_filename  = os.path.join(get_home_path(), display_name)
        self.content        = ''
        self.edit           = QPlainTextEdit()
        self.normal_font    = self.edit.font()
        self.monospace_font = QFont('monospace')

        self.edit.setUndoRedoEnabled(False)
        self.edit.setReadOnly(True)
        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setPlainText('Click "Refresh" to download {0}.'.format(display_name))

        self.monospace_font.setStyleHint(QFont.TypeWriter)

    def log(self, message, bold=False, pre=False):
        if bold:
            self.edit.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
        elif pre:
            self.edit.appendHtml(u'<pre>{0}</pre>'.format(message))
        else:
            self.edit.appendPlainText(message)

    def reset(self):
        self.content = None

        self.edit.setPlainText('')
        self.edit.setFont(self.normal_font)

    def set_content(self, content):
        self.content = content

        self.edit.setPlainText('')
        self.edit.setFont(self.monospace_font)
        self.edit.setPlainText(content)
Exemple #12
0
class DebugLogWidget(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.canMonitor = parent

    def addToWidget(self, vbox):
        self.text = QPlainTextEdit(self.canMonitor)
        self.text.setReadOnly(True)
        vbox.addWidget(self.text)

        hbox = QHBoxLayout()
        hbox.setAlignment(Qt.AlignRight | Qt.AlignBottom)
        self.clearButton = QPushButton("Clear", self.canMonitor)
        self.clearButton.clicked.connect(self._clearText)
        hbox.addWidget(self.clearButton)

        vbox.addLayout(hbox)

    @pyqtSlot()
    def _clearText(self):
        self.text.clear()

    def addLineToLog(self, line):
        self.text.appendPlainText(line)
Exemple #13
0
class AsciidocEditor(WithSingleIO, QWidget):
    """Asciidoc editor
    """

    def __init__(self, params, parent=None):
        self.base_dir = os.path.dirname(__file__)
        QWidget.__init__(self, parent)

        self.setMinimumWidth(300)
        self.setMinimumHeight(300)

        # create widgets
        self._editor_widget = mixin(
                        WithFind,
                        WidthMqHighlighter,
                        WithMqEditIO,
                        WithBasicIdentationManager,
                        WithLineHighlight,
                        WithFixedFont,
                        WithLineNumbers,
                        WithViewPortMargins,
                        WithWordCompletionMulty_,
                        WithCompletion,
                        QPlainTextEdit)(self)
        self.webview = QWebView(self)
        #self.webview.load(QUrl("/home/maiquel/develop/developing/main/qt/qadoc/bin/__builds/documents.html"))
        self.splitter = QSplitter(Qt.Horizontal)
        self.splitter.addWidget(self._editor_widget)
        self.splitter.addWidget(self.webview)
        self.splitter.setSizes([self.size().width(), self.size().width()])

        self.splitterv = QSplitter(Qt.Vertical)
        self.splitterv.addWidget(self.splitter)
        self.log_widget = QPlainTextEdit()
        self.splitterv.addWidget(self.log_widget)

        layout = QVBoxLayout(self)
        layout.addWidget(self.splitterv)
        layout.setMargin(0)
        self.setLayout(layout)

        # proc_compile
        self.proc_compile = QProcess()
        self.proc_compile.finished.connect(self.proc_compile_finished)
        self.proc_compile.error.connect(self.proc_compile_error)
        self.proc_compile.readyReadStandardOutput.connect(self.proc_compile_readyReadStandardOutput)
        self.proc_compile.readyReadStandardError.connect(self.proc_compile_readyReadStandardError)

        WithSingleIO.__init__(self, params)


    def bw_add_command_list(self, command_list):
        command_list += [
                ("generate preview asciidoc",    "pp", 1.0, "self.get_current_widget().command_generate_preview('asciidoc -a toc -a data-uri -a icons  -a iconsdir="+self.base_dir+"/adoc/icons/')"),
                ("generate preview asciidoc style_sheet no images embeded",    "pp", 1.0, "self.get_current_widget().command_generate_preview('asciidoc -a toc --attribute  stylesheet="+self.base_dir+"/adoc/mq_red.css  -a icons  -a iconsdir="+self.base_dir+"/adoc/icons/')"),
                ("generate preview asciidoc style_sheet",    "pp", 1.2, "self.get_current_widget().command_generate_preview('asciidoc -a toc --attribute  stylesheet="+self.base_dir+"/adoc/mq_red.css    -a data-uri -a icons  -a iconsdir="+self.base_dir+"/adoc/icons/')"),
                ("generate preview slidy", "pp slides", 0.8, "self.get_current_widget().command_generate_preview('asciidoc  -a toc -b slidy    -a data-uri -a icons')"),
                ("generate preview slidy2", "pp slides", 0.9, "self.get_current_widget().command_generate_preview('asciidoc -a toc  -b slidy2    -a data-uri -a icons')"),
                ("generate preview asciidoctor", "pp", 0.7, "self.get_current_widget().command_generate_preview('asciidoctor -a toc  -a data-uri -a icons')"),
                ("generate preview deck.js", "pp slides", 0.7, "self.get_current_widget().command_generate_preview('asciidoc -a toc  -b deckjs    -a data-uri -a icons')"),

                ("generate pdf small", "", 0., """self.get_current_widget().command_generate_document('a2x --verbose -d article --icons --dblatex-opts "-T native -P doc.pdfcreator.show=0 -P doc.collab.show=0 -P latex.output.revhistory=0 -P doc.toc.show=1 -P table.title.top" -f pdf  -D /tmp/adoc/ ')"""),
                ("generate pdf book", "", 0., """self.get_current_widget().command_generate_document('a2x --verbose -d book --icons --dblatex-opts "-T native -P doc.pdfcreator.show=0 -P doc.collab.show=0 -P latex.output.revhistory=0 -P doc.toc.show=1 -P table.title.top" -f pdf  -D /tmp/adoc/ ')"""),
               ]
        super(AsciidocEditor, self).bw_add_command_list(command_list)
        self._editor_widget.bw_add_command_list(command_list)
        command_list += [
                    ("focus editor",    "fe", 0.5, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self._editor_widget.setFocus();"),
                    ("focus preview",    "fp", 0.5, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self.webview.setFocus();"),

                    ("increase font webview",    "if if", 0.7, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self.webview.setTextSizeMultiplier(_self.webview.textSizeMultiplier()+0.1);"),
                    ("decrease font webview",    "df df", 0.7, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self.webview.setTextSizeMultiplier(_self.webview.textSizeMultiplier()-0.1);"),
            ]


    def copy2tmp(self):
        if not os.path.exists(TEMP_DIR):
            os.mkdir(TEMP_DIR)
        source = os.listdir(self.base_dir)
        destination = TEMP_DIR
        for files in source:
            shutil.move(files,destination)        

    def command_generate_preview(self, adoc_command):
        self.command_save_file()
        #self.compile(backend + " -b deckjs  -o " + self.get_html_output() + "  " + TEMP_DIR + "pr.adoc")
        #asciidoc --verbose -a data-uri -a icons -a toc -a max-width=55em -o __builds/index.html /home/maiquel/Documents/qadoc/adoc/index.adoc
        #self.compile(adoc_command + " --attribute  stylesheet=/home/maiquel/inet.prj/miow/widgets/adoc/mq_red.css    -a data-uri -a icons  -o " + self.get_html_output() + "  " + TEMP_DIR + "pr.adoc")
        self.compile(adoc_command + ' -o ' +self.get_html_output() + '  ./"' +  self.file_name + '"')
        if self.webview.url() != QUrl("file://" + self.get_html_output()):
            self.webview.load(QUrl(self.get_html_output()))

    def command_generate_document(self, adoc_command):
        self.command_save_file()
        self.compile(adoc_command + "  " + TEMP_DIR + "pr.adoc")
        if self.webview.url() != QUrl("file://" + self.get_html_output()):
            self.webview.load(QUrl(self.get_html_output()))

    def compile(self, command):
        self.log(command)
        self.proc_compile.start(command)


    def bw_lock_command_window(self):
        return self._editor_widget.completer.popup().isVisible()

    def focusInEvent(self, focus_event):
        super(AsciidocEditor, self).focusInEvent(focus_event)
        self._editor_widget.setFocus()

    def get_html_output(self):
        return TEMP_DIR + "pr.html"
    def proc_compile_finished(self, result, exit_status):
        self.log("compilation finished")
        if self.webview.url().toString() == "":
            self.webview.load(QUrl(self.get_html_output()))
        else:
            self.webview.reload()

    def proc_compile_error(self, q_process_error):
        self.log("compilation error")
        print(q_process_error)
    def proc_compile_readyReadStandardOutput(self):
        result = self.proc_compile.readAllStandardOutput();
        self.log(result)

    def proc_compile_readyReadStandardError(self):
        result = str(self.proc_compile.readAllStandardError())
        self.log(result)

    def log(self, text):
        self.log_widget.appendPlainText(unicode(text))
Exemple #14
0
class SimpleConnectWidget(QWidget):
    """
    this widget displays a combobox with a list of instruments which the
    user can connect to, it also has a refresh button
    """
    def __init__(self, parent=None):
        super(SimpleConnectWidget, self).__init__(parent)

        # main layout of the form is the verticallayout

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")

        # moved the script stuff to a separate widget that lives in the toolbar

        self.labelLayout = QHBoxLayout()
        self.labelLayout.setObjectName("labelLayout")

        self.portLabel = QLabel(self)
        self.portLabel.setText("Availiable Ports")
        self.instrLabel = QLabel(self)
        self.instrLabel.setText("Instruments")

        self.labelLayout.addWidget(self.portLabel)
        self.labelLayout.addWidget(self.instrLabel)

        self.verticalLayout.addLayout(self.labelLayout)

        self.ports = QComboBox(self)
        self.ports.addItems(refresh_device_port_list())
        self.ports.setObjectName("cbb_ports")

        self.instruments = QComboBox(self)
        self.instruments.addItems(utils.list_drivers(interface="real")[0])
        self.ports.setObjectName("cbb_instrs")

        self.cbbLayout = QHBoxLayout()
        self.cbbLayout.setObjectName("cbbLayout")

        self.cbbLayout.addWidget(self.ports)
        self.cbbLayout.addWidget(self.instruments)

        self.verticalLayout.addLayout(self.cbbLayout)

        self.connectButton = QPushButton(self)
        self.connectButton.setText("Connect the instrument")
        self.connectButton.setObjectName("connectButton")

        self.refreshButton = QPushButton(self)
        self.refreshButton.setText("refresh the port list")
        self.refreshButton.setObjectName("refreshButton")

        self.verticalLayout.addWidget(self.connectButton)
        self.verticalLayout.addWidget(self.refreshButton)
        self.headerTextEdit = QPlainTextEdit("")
        fontsize = self.headerTextEdit.fontMetrics()

        pal = QPalette()
        textc = QColor(245, 245, 240)
        pal.setColor(QPalette.Base, textc)
        self.headerTextEdit.setPalette(pal)
        # d3d3be
        #        self.headerTextEdit.ba
        self.headerTextEdit.setFixedHeight(fontsize.lineSpacing() * 8)
        self.verticalLayout.addWidget(self.headerTextEdit)

        # moved the start stop button to the toolbar only

        self.setLayout(self.verticalLayout)

        self.connect(self.connectButton, SIGNAL('clicked()'),
                     self.on_connectButton_clicked)
        self.connect(self.refreshButton, SIGNAL('clicked()'),
                     self.on_refreshButton_clicked)

    def on_connectButton_clicked(self):
        """Connect a given instrument through a given port"""
        port = self.ports.currentText()
        instrument_name = self.instruments.currentText()

        # load the module which contains the instrument's driver
        if __name__ == "__main__":

            class_inst = import_module(instrument_name)

        else:

            class_inst = import_module("." + instrument_name,
                                       package=utils.LABDRIVER_PACKAGE_NAME)
        msg = ""
        #        msg.append("example")
        #        msg.append("</span>")
        self.headerTextEdit.appendHtml(msg)
        #        self.headerTextEdit.appendPlainText(msg)
        try:

            i = class_inst.Instrument(port)
            self.headerTextEdit.appendPlainText("%s" % (i.identify()))
            self.headerTextEdit.appendHtml(
                "The connection to the instrument %s through the port %s <span style=\" color:#009933;\" >WORKED</span>\n"
                % (instrument_name, port))

            i.close()

        except:

            self.headerTextEdit.appendHtml(
                "The connection to the instrument %s through the port %s <span style=\" color:#ff0000;\" >FAILED</span>\n"
                % (instrument_name, port))

    def on_refreshButton_clicked(self):
        """Refresh the list of the availiable ports"""
        self.ports.clear()
        self.ports.addItems(refresh_device_port_list())
Exemple #15
0
class VNAWidget(QWidget):
    settings = None
    def __init__(self):
        super(VNAWidget, self).__init__()
        self.setWindowTitle("VNA Window")
        layout = QVBoxLayout(self)

        self.plot_layout = QHBoxLayout()
        layout.addLayout(self.plot_layout)
        self.mag_plot = PlotWidget()
        self.mag_plot.addLegend()
        self.plot_layout.addWidget(self.mag_plot)

        self.message_box = QPlainTextEdit()
        layout.addWidget(self.message_box)

        self.form_layout = QFormLayout()
        layout.addLayout(self.form_layout)

        self.dataset_edit = QLineEdit("TestSample")
        save_file_button = QPushButton("HDF5 File")
        self.save_file_edit = QLineEdit("C:\\_Data\\test.h5")
        # self.form_layout.addRow("VNA Address", self.address_combo_box)
        self.form_layout.addRow(save_file_button, self.save_file_edit)
        dataset_button = QPushButton("Dataset")
        self.form_layout.addRow(dataset_button, self.dataset_edit)

        self.button_layout = QHBoxLayout()
        layout.addLayout(self.button_layout)
        grab_trace_button = QPushButton("Grab Trace")
        save_button = QPushButton("Save")
        self.button_layout.addWidget(grab_trace_button)
        self.button_layout.addWidget(save_button)

        self.freqs = None
        self.mags = None
        self.phases = None
        self.vna = None
        self.current_vna_addr = None
        self.vna_params = None

        save_file_button.clicked.connect(self.change_save_file)
        dataset_button.clicked.connect(self.change_dataset)
        grab_trace_button.clicked.connect(self.grab_trace)
        save_button.clicked.connect(self.save_trace)

    def get_vna(self):
        return instruments['VNA']

    def grab_trace(self):
        vna = self.get_vna()
        self.freqs = vna.do_get_xaxis()
        self.mags, self.phases = vna.do_get_data()
        self.replot()
        self.vna_params =  vna.get_parameter_values(query=True)
        self.message("VNA Params")
        self.message("----------")
        for k, v in self.vna_params.items():
            self.message(k, ":", v)
        self.message("")

    def replot(self):
        self.mag_plot.clear()
        self.mag_plot.plotItem.legend.setParent(None)
        self.mag_plot.addLegend()
        if self.freqs is None:
            return
        self.mag_plot.plot(self.freqs, self.mags, pen='g', name='Data')

    def message(self, *objs):
        self.message_box.appendPlainText(" ".join([str(o) for o in objs]))

    def change_save_file(self):
        filename = QFileDialog.getSaveFileName(
            self, "Save File", self.save_file_edit.text(),
            "HDF5 files (*.h5 *.hdf5)", options=QFileDialog.DontConfirmOverwrite
        )
        self.save_file_edit.setText(filename)

    def change_dataset(self):
        dialog = QDialog()
        layout = QVBoxLayout(dialog)
        model = H5File(h5py.File(str(self.save_file_edit.text())))
        tree_view = H5View()
        tree_view.setModel(model)
        tree_view.setSelectionMode(QAbstractItemView.SingleSelection)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(dialog.accept)
        button_box.rejected.connect(dialog.reject)
        layout.addWidget(tree_view)
        layout.addWidget(button_box)
        if dialog.exec_():
            #self.dataset_edit.setText(tree_view.selected_path()[1:])
            dsname = model.itemFromIndex(tree_view.selectedIndexes()[0]).fullname[1:]
            self.dataset_edit.setText(dsname)


    def get_h5group(self):
        filename = str(self.save_file_edit.text())
        h5file = datasrv.get_file(filename)
        path = str(self.dataset_edit.text())
        return h5helpers.resolve_path(h5file, path)

    def save_trace_csv(self):
        default_name = time.strftime("trace_%Y%m%d_%H%M%S.dat")
        save_path = str(self.save_path_edit.text())
        default_filename = os.path.join(save_path, default_name)
        filename = str(QFileDialog.getSaveFileName(self, "Save Trace", default_filename))
        data = numpy.array([self.freqs, self.mags, self.phases]).transpose()
        numpy.savetxt(filename, data)

    def save_trace(self):
        group = self.get_h5group()
        if 'freqs' in group:
            reply = QMessageBox.question(self, "", "Dataset exists in file, Overwrite?", QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.No:
                return

        group['freqs'] = self.freqs
        group['mags'] = self.mags
        group['phases'] = self.phases
        h5helpers.set_scale(group, 'freqs', 'mags')
        h5helpers.set_scale(group, 'freqs', 'phases')
        h5helpers.update_attrs(group, self.vna_params)
        self.message("Saved in file %s" % group.get_fullname())
 def ShowWorking(self):
     getcontext().prec = 3
     working = QPlainTextEdit()
     working.setWindowTitle("Kc calculation")
     reactants = []
     products = []
     for x in self._CurrentReaction.GetReactants():
         if x.GetUsed():
             reactants.append(x)
     for x in self._CurrentReaction.GetProducts():
         if x.GetUsed():
             products.append(x)
     working.appendPlainText("Concentration = moles / volume")
     volume = self._CurrentReaction.GetVolume()
     working.appendPlainText("Volume = "+str(volume)+" dm^3")
     pvalues = []
     rvalues = []
     for x in products:
         working.appendPlainText("Concentration of "+x.GetFormula()+" = "+str(Decimal(x.GetConcentration(volume)) + Decimal(0.0))+" mol dm^-3")
         pvalues.append(x.GetConcentration(volume))
         pvalues.append(x.GetSRatio())
     for x in reactants:
         working.appendPlainText("Concentration of "+x.GetFormula()+" = "+str(Decimal(x.GetConcentration(volume)) + Decimal(0.0))+" mol dm^-3")
         rvalues.append(x.GetConcentration(volume))
         rvalues.append(x.GetSRatio())
     kcvalue = "Value of Kc ="
     x = 0
     while x < len(pvalues):
         kcvalue += " ("+str(Decimal(pvalues[x]) + Decimal(0.0))+")^"
         x += 1
         kcvalue += str(pvalues[x])
         x += 1
     kcvalue += " /"
     x = 0
     while x < len(rvalues):
         kcvalue += " ("+str(Decimal(rvalues[x]) + Decimal(0.0))+")^"
         x += 1
         kcvalue += str(rvalues[x])
         x += 1
     working.appendPlainText(kcvalue)
     rproductsum = 0
     for x in reactants:
         rproductsum += x.GetSRatio()
     pproductsum = 0
     for x in products:
         pproductsum += x.GetSRatio()
     working.appendPlainText("There are "+str(len(reactants))+" reactants, with units mol dm^-3.")
     working.appendPlainText("The product of these units is mol^"+str(rproductsum)+" dm^"+str(rproductsum * -3)+".")
     working.appendPlainText("There are "+str(len(products))+" products, with units mol dm^-3.")
     working.appendPlainText("The product of these units is mol^"+str(pproductsum)+" dm^"+str(pproductsum * -3)+".")
     working.appendPlainText("The product units must be divided by the reactant units, so")
     working.appendPlainText(self._CurrentReaction.GetKc())
     self._ExtraWindows.append(working)
     working.show()
Exemple #17
0
class Ui_MainWindow(object):
	def setupUi(self, MainWindow):
		MainWindow.setObjectName(_fromUtf8("MainWindow"))
		MainWindow.resize(300, 270)
		self.centralwidget = QWidget(MainWindow)
		self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
		self.buttonSave = QPushButton(self.centralwidget)
		self.buttonSave.setGeometry(QRect(120, 235, 71, 32))
		self.buttonSave.setObjectName(_fromUtf8("buttonSave"))
		self.inputFolder = QLineEdit(self.centralwidget)
		self.inputFolder.setGeometry(QRect(130, 10, 131, 23))
		self.inputFolder.setObjectName(_fromUtf8("inputFolder"))
		self.buttonSelectFolder = QToolButton(self.centralwidget)
		self.buttonSelectFolder.setGeometry(QRect(263, 10, 27, 23))
		self.buttonSelectFolder.setToolButtonStyle(Qt.ToolButtonIconOnly)
		self.buttonSelectFolder.setAutoRaise(False)
		self.buttonSelectFolder.setArrowType(Qt.NoArrow)
		self.buttonSelectFolder.setObjectName(_fromUtf8("buttonSelectFolder"))
		self.labelFolder = QLabel(self.centralwidget)
		self.labelFolder.setGeometry(QRect(10, 13, 101, 16))
		self.labelFolder.setObjectName(_fromUtf8("labelFolder"))
		self.inputLogin = QLineEdit(self.centralwidget)
		self.inputLogin.setGeometry(QRect(130, 40, 161, 23))
		self.inputLogin.setObjectName(_fromUtf8("inputLogin"))
		self.inputPassword = QLineEdit(self.centralwidget)
		self.inputPassword.setGeometry(QRect(130, 70, 161, 23))
		self.inputPassword.setObjectName(_fromUtf8("inputPassword"))
		self.labelLogin = QLabel(self.centralwidget)
		self.labelLogin.setGeometry(QRect(10, 42, 62, 16))
		self.labelLogin.setObjectName(_fromUtf8("labelLogin"))
		self.labelPassword = QLabel(self.centralwidget)
		self.labelPassword.setGeometry(QRect(10, 72, 62, 16))
		self.labelPassword.setObjectName(_fromUtf8("labelPassword"))
		self.output = QPlainTextEdit(self.centralwidget)
		self.output.setEnabled(True)
		self.output.setGeometry(QRect(10, 100, 281, 131))
		self.output.viewport().setProperty("cursor", QCursor(Qt.IBeamCursor))
		self.output.setReadOnly(True)
		self.output.setObjectName(_fromUtf8("output"))
		font = QApplication.font()
		font.setPointSize(11)
		self.output.setFont(font)
		MainWindow.setCentralWidget(self.centralwidget)

		self.retranslateUi(MainWindow)
		self.connectSignals()
		QMetaObject.connectSlotsByName(MainWindow)

	def retranslateUi(self, MainWindow):
		MainWindow.setWindowTitle(QApplication.translate("MainWindow", "TDS Dropbox setup", None, QApplication.UnicodeUTF8))
		self.buttonSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8))
		self.buttonSelectFolder.setText(QApplication.translate("MainWindow", "...", None, QApplication.UnicodeUTF8))
		self.labelFolder.setText(QApplication.translate("MainWindow", "Folder to sync", None, QApplication.UnicodeUTF8))
		self.labelLogin.setText(QApplication.translate("MainWindow", "Login", None, QApplication.UnicodeUTF8))
		self.labelPassword.setText(QApplication.translate("MainWindow", "Password", None, QApplication.UnicodeUTF8))

	def connectSignals(self):
		QObject.connect(self.buttonSelectFolder, SIGNAL("clicked()"), self.selectFolder)
		QObject.connect(self.centralwidget, SIGNAL("folderIsSet(PyQt_PyObject)"), self.setFolder)
		QObject.connect(self.buttonSave, SIGNAL("clicked()"), self.validateData)
		

	def selectFolder(self):
		folder = QFileDialog.getExistingDirectory(self.centralwidget, "Choose folder to sync", os.getenv("HOME"))
		QObject.emit(self.centralwidget, SIGNAL("folderIsSet(PyQt_PyObject)"), folder)

	def setFolder(self, folder):
		self.inputFolder.setText(folder)

	def validateData(self):
		validate = True
		if (len(self.inputFolder.text()) == 0):
			self.error("You haven't choose the dir to sync!")
			validate = False
		if (len(self.inputLogin.text()) == 0):
			self.error("You havent enter the login!")
			validate = False
		if (len(self.inputPassword.text()) == 0):
			self.error("You haven't enter the password!")
			validate = False
		if (validate):
			self.lockGui()
			self.out("setup start")
			self.setupSync({"folder": self.inputFolder.text(), "login": self.inputLogin.text(), "password": self.inputPassword.text()})
			self.unlockGui()

	def lockGui(self):
		self.inputFolder.setReadOnly(True)
		self.inputLogin.setReadOnly(True)
		self.inputPassword.setReadOnly(True)
		self.buttonSave.setDisabled(True)
		self.buttonSelectFolder.setDisabled(True)

	def unlockGui(self):
		self.inputFolder.setReadOnly(False)
		self.inputLogin.setReadOnly(False)
		self.inputPassword.setReadOnly(False)
		self.buttonSave.setDisabled(False)
		self.buttonSelectFolder.setDisabled(False)

	def setupSync(self, data):
		p = Popen(["./letssync.sh", "-u%(login)s" % data, "-p%(password)s" % data, "%(folder)s" % data])
		if (p.wait() != 0):
			self.error("an error occuring during setup!")
		else:
			self.out("setup complete!")

	def error(self, message):
		self.out("ERROR: {}".format(message))

	def out(self, message):
		self.output.appendPlainText("{0} :: {1}".format(datetime.now().strftime("%H:%M"), message))
class BluetoothWindow(QMainWindow):

    def __init__(self, inbuf, outbuf,parent=None):

        super(BluetoothWindow, self).__init__(parent)

        self.sendbuf=outbuf
        self.receivebuf=inbuf
        
        self.output=QPlainTextEdit()

        self.output.setReadOnly(True)
        self.output.setLineWrapMode(QPlainTextEdit.WidgetWidth)
        
        self.hor = QHBoxLayout()
        self.ver = QVBoxLayout()
        
        def updateValue(key, value):
            pidvalues[key] = float(value)
            print key, "updated to", value
        
        for k, v in pidvalues.iteritems():
            label = QLabel(k)
            edit = QLineEdit(str(v))
            button = QPushButton("Update")
            l = QHBoxLayout()
            l.addWidget(label, 2)
            l.addWidget(edit, 5)
            l.addWidget(button, 2)
            self.ver.addLayout(l)   
            button.clicked.connect(lambda clicked, label=label, edit=edit: updateValue(label.text(), edit.text()))        
        
        self.hor.addWidget(self.output)
        self.hor.addLayout(self.ver)
        
        w = QWidget()
        w.setLayout(self.hor)
        self.setCentralWidget(w)
        
        SampleTimeInSec = (pidvalues["PID_SAMPLE_TIME"]) / 1000.0
        
        for i in range(4):
          pid_params.append(pid_params_typedef())
        
        pid_params[pidvalues["PID_THROTTLE"]].kp = pidvalues["KP_THROTTLE"];
        pid_params[pidvalues["PID_THROTTLE"]].ki = pidvalues["KI_THROTTLE"] * SampleTimeInSec;
        pid_params[pidvalues["PID_THROTTLE"]].kd = pidvalues["KD_THROTTLE"] / SampleTimeInSec;
        pid_params[pidvalues["PID_THROTTLE"]].min = pidvalues["MIN_THROTTLE"];
        pid_params[pidvalues["PID_THROTTLE"]].max = pidvalues["MAX_THROTTLE"];

        pid_params[pidvalues["PID_PITCH"]].kp = pidvalues["KP_PITCH"];
        pid_params[pidvalues["PID_PITCH"]].ki = pidvalues["KI_PITCH"] * SampleTimeInSec; 
        pid_params[pidvalues["PID_PITCH"]].kd = pidvalues["KD_PITCH"] / SampleTimeInSec;
        pid_params[pidvalues["PID_PITCH"]].min = pidvalues["MIN_PITCH"];
        pid_params[pidvalues["PID_PITCH"]].max = pidvalues["MAX_PITCH"];

        pid_params[pidvalues["PID_ROLL"]].kp = pidvalues["KP_ROLL"];
        pid_params[pidvalues["PID_ROLL"]].ki = pidvalues["KI_ROLL"] * SampleTimeInSec;
        pid_params[pidvalues["PID_ROLL"]].kd = pidvalues["KD_ROLL"] / SampleTimeInSec;
        pid_params[pidvalues["PID_ROLL"]].min = pidvalues["MIN_ROLL"];
        pid_params[pidvalues["PID_ROLL"]].max = pidvalues["MAX_ROLL"];
        
        pid_params[pidvalues["PID_YAW"]].kp = pidvalues["KP_YAW"];
        pid_params[pidvalues["PID_YAW"]].ki = pidvalues["KI_YAW"] * SampleTimeInSec;
        pid_params[pidvalues["PID_YAW"]].kd = pidvalues["KD_YAW"] / SampleTimeInSec;
        pid_params[pidvalues["PID_YAW"]].min = pidvalues["MIN_YAW"];
        pid_params[pidvalues["PID_YAW"]].max = pidvalues["MAX_YAW"];

        for i in pid_params:
           print i              
 
    def receiveText(self):
          
#        | 2-5   | Roll    | [-pi, pi]   |
#        | 6-9   | Pitch   | [-pi, pi]   |
#        | 10-13 | Yaw     | [-pi, pi]   |
#        | 14-17 | Height  | [0, 10m]  |
#        | 18-21 | Battery | [0, 100%] |
        
        rolldata=""
        pitchdata=""
        yawdata=""
        heightdata=""
        batterydata=""
        
        for i in range(4):
            rolldata+=self.receivebuf.pop(0)
        
        for i in range(4):
            pitchdata+=self.receivebuf.pop(0)
        
        for i in range(4):
            yawdata+=self.receivebuf.pop(0)
        
        for i in range(4):
            heightdata+=self.receivebuf.pop(0)
        
        for i in range(4):
            batterydata+=self.receivebuf.pop(0)
        
        roll=struct.unpack('f', rolldata)
        pitch=struct.unpack('f', pitchdata)
        yaw=struct.unpack('f', yawdata)
        
        self.output.appendPlainText("p "+str(pitch[0])+", r "+str(roll[0])+", y "+str(yaw[0]))
        
        ## pids 
        data.pitch = pitch[0]
        data.roll = roll[0]
        data.yaw = yaw[0]
                
        global lastThrottle
                
        pid_output.throttle = self.pid_compute(pidvalues["PID_THROTTLE"], lastThrottle, command.throttle);
        pid_output.pitch = self.pid_compute(pidvalues["PID_PITCH"], data.pitch, command.pitch);
        pid_output.roll = self.pid_compute(pidvalues["PID_ROLL"], data.roll, command.roll);
        pid_output.yaw = self.pid_compute(pidvalues["PID_YAW"], data.yaw, command.yaw);
        
        #Save last throttle value
        lastThrottle = pid_output.throttle * 2 * ( pidvalues["MAX_THROTTLE"] / MOTOR_SPEED_MAX) - pidvalues["MIN_THROTTLE"];
    

        #Add offset to throttle
        pid_output.throttle += MOTOR_SPEED_HALF;
        
        self.motors_pid_apply()
                
        ## update gui
        self.repaint()   

    def motor_name(self, motor):
        if (motor == MOTOR_RIGHT_BACK):
            return "RIGHT__BACK"
        elif (motor == MOTOR_LEFT_BACK):
            return "LEFT___BACK"
        elif (motor == MOTOR_RIGHT_FRONT):
            return "RIGHT_FRONT"
        elif (motor == MOTOR_LEFT_FRONT):
            return "LEFT__FRONT"
        else:
            return "UNKNOWN"

    def motors_set_speed(self, motor, value):
        self.output.appendPlainText("motor "+str(self.motor_name(motor))+", value "+str(int(value)))
        

    def motors_pid_apply(self):
      self.motors_set_speed(MOTOR_RIGHT_FRONT, pid_output.throttle - pid_output.pitch - pid_output.roll - pid_output.yaw);
      self.motors_set_speed(MOTOR_LEFT_FRONT, pid_output.throttle - pid_output.pitch + pid_output.roll + pid_output.yaw);
      self.motors_set_speed(MOTOR_RIGHT_BACK, pid_output.throttle + pid_output.pitch - pid_output.roll + pid_output.yaw);
      self.motors_set_speed(MOTOR_LEFT_BACK, pid_output.throttle + pid_output.pitch + pid_output.roll - pid_output.yaw);
                
                
    def pid_compute(self, index, input, setpoint):
     
      pid = pid_params[index]
      retVal = 0

      #Compute all the working error variables*/
      error = setpoint - input;
      pid.iterm += pid.ki * error;
      if (pid.iterm > pid.max) :
        pid.iterm = pid.max;
      else:
        if (pid.iterm < pid.min):
          pid.iterm = pid.min;
          
      dInput = (input - pid.lastInput);

      #Compute PID Output*/
      retVal = (pid.kp * error + pid.iterm - pid.kd * dInput);
      if (retVal > pid.max):
        retVal = pid.max;
      else:
         if (retVal < pid.min):
           retVal = pid.min;

      #Remember some variables for next time*/
      pid.lastInput = input;
      pid_params[index] = pid
      return retVal        
      
    def reset(self):
        self.output.clear()
Exemple #19
0
class RestEditor(WithSingleIO, QWidget):
    """Restructredtext editor
    """

    def __init__(self, params, parent=None):
        QWidget.__init__(self, parent)

        self.setMinimumWidth(300)
        self.setMinimumHeight(300)

        # create widgets
        self._editor_widget = mixin(
                        WithFind,
                        WithMqEditIO,
                        WithBasicIdentationManager,
                        WithLineHighlight,
                        WithFixedFont,
                        WithLineNumbers,
                        WithViewPortMargins,
                        WithWordCompletionMulty_,
                        WithCompletion,
                        QPlainTextEdit)(self)
        self.webview = QWebView(self)
        #self.webview.load(QUrl("/home/maiquel/develop/developing/main/qt/qadoc/bin/__builds/documents.html"))
        self.splitter = QSplitter(Qt.Horizontal)
        self.splitter.addWidget(self._editor_widget)
        self.splitter.addWidget(self.webview)
        self.splitter.setSizes([self.size().width(), self.size().width()])

        self.splitterv = QSplitter(Qt.Vertical)
        self.splitterv.addWidget(self.splitter)
        self.log_widget = QPlainTextEdit()
        self.splitterv.addWidget(self.log_widget)

        layout = QVBoxLayout(self)
        layout.addWidget(self.splitterv)
        layout.setMargin(0)
        self.setLayout(layout)

        # proc_compile
        self.proc_compile = QProcess()
        self.proc_compile.finished.connect(self.proc_compile_finished)
        self.proc_compile.error.connect(self.proc_compile_error)
        self.proc_compile.readyReadStandardOutput.connect(self.proc_compile_readyReadStandardOutput)
        self.proc_compile.readyReadStandardError.connect(self.proc_compile_readyReadStandardError)

        WithSingleIO.__init__(self, params)


    def bw_add_command_list(self, command_list):
        command_list += [
                ("generate preview restructuretext",    "pp", 1.0, "self.get_current_widget().command_generate_preview('rst2html')"),
               ]
        super(RestEditor, self).bw_add_command_list(command_list)
        self._editor_widget.bw_add_command_list(command_list)
        command_list += [
                    ("focus editor",    "fe", 0.5, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self._editor_widget.setFocus();"),
                    ("focus preview",    "fp", 0.5, 
                     "import ctypes; _self = ctypes.cast(" + str(id(self)) + ", ctypes.py_object).value;"
                     "_self.webview.setFocus();"),
            ]


    def command_generate_preview(self, backend):
        self.command_save_file()
        if not os.path.exists(TEMP_DIR):
            os.mkdir(TEMP_DIR)
        temp_source_file = open(TEMP_DIR + 'pr.rst','wt')
        temp_source_file.write(self._editor_widget.toPlainText())
        temp_source_file.close()
        self.compile(backend + " --stylesheet=./widgets/rst2html.style " + TEMP_DIR + "pr.rst" + "   " + self.get_html_output())
        if self.webview.url() != QUrl("file://" + self.get_html_output()):
            self.webview.load(QUrl(self.get_html_output()))

    def compile(self, command):
        self.log(command)
        self.proc_compile.start(command)


    def bw_lock_command_window(self):
        return self._editor_widget.completer.popup().isVisible()

    def focusInEvent(self, focus_event):
        super(RestEditor, self).focusInEvent(focus_event)
        self._editor_widget.setFocus()

    def get_html_output(self):
        return TEMP_DIR + "pr.html"
    def proc_compile_finished(self, result, exit_status):
        self.log("compilation finished")
        if self.webview.url().toString() == "":
            self.webview.load(QUrl(self.get_html_output()))
        else:
            self.webview.reload()

    def proc_compile_error(self, q_process_error):
        self.log("compilation error")
        print(q_process_error)
    def proc_compile_readyReadStandardOutput(self):
        result = self.proc_compile.readAllStandardOutput();
        self.log(result)

    def proc_compile_readyReadStandardError(self):
        result = str(self.proc_compile.readAllStandardError())
        self.log(result)

    def log(self, text):
        self.log_widget.appendPlainText(text)
Exemple #20
0
class BR_JobDock(QDockWidget):
    transcode_data = pyqtSignal([dict], [str])
    job_complete = pyqtSignal()

    def __init__(self, job, passes, job_id, closesig, source, parent=None):
        name = source.title
        super().__init__(name, parent)
        self.job = job
        self.passes = passes
        self.job_id = job_id
        self.closesig = closesig
        self.source = source

        self.setWindowTitle(name)
        self.setFeatures(QDockWidget.DockWidgetMovable
                         | QDockWidget.DockWidgetFloatable)
        self.setAllowedAreas(Qt.BottomDockWidgetArea)
        self.setFloating(True)

        self.widget = QWidget()
        layout = QVBoxLayout()
        #        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        message_layout = QFormLayout()
        self.lblPass = QLabel('Pass ? of {}'.format(passes))
        message_layout.addRow(self.lblPass)
        self.lblFrame = QLabel('?')
        message_layout.addRow('Frame:', self.lblFrame)
        self.lblFps = QLabel('?')
        message_layout.addRow('Frames per Second:', self.lblFps)
        self.lblSize = QLabel('?')
        message_layout.addRow('File Size:', self.lblSize)
        self.lblTime = QLabel('?')
        message_layout.addRow('Video Time:', self.lblTime)
        self.lblBitrate = QLabel('?')
        message_layout.addRow('Bitrate:', self.lblBitrate)
        layout.addLayout(message_layout)

        self.progressbar = QProgressBar()
        self.progressbar.setRange(0, self.source.length.total_seconds())
        layout.addWidget(self.progressbar)

        self.qualitybar = QualityBar()
        layout.addWidget(self.qualitybar)

        btn_layout = QHBoxLayout()
        btn_More = QPushButton('More')
        btn_More.setCheckable(True)
        btn_layout.addWidget(btn_More)
        btn_layout.addStretch()
        self.btnCancel = QPushButton('Close')
        self.btnCancel.setIcon(QIcon(QPixmap(':/icons/application-exit.png')))
        self.btnCancel.clicked.connect(self.on_cancel_clicked)
        btn_layout.addWidget(self.btnCancel)
        layout.addLayout(btn_layout)

        self.terminal = QPlainTextEdit()
        self.terminal.setReadOnly(True)
        self.terminal.setShown(False)
        #        self.terminal.setMinimumWidth(400)
        btn_More.toggled.connect(self.terminal.setVisible)
        layout.addWidget(self.terminal)

        griplayout = QHBoxLayout()
        griplayout.addWidget(QSizeGrip(self.widget))
        griplayout.addStretch()
        griplayout.addWidget(QSizeGrip(self.widget))
        layout.addLayout(griplayout)

        self.widget.setLayout(layout)
        self.setWidget(self.widget)

        self.transcode_data[dict].connect(self.on_avconv_data)
        self.transcode_data[str].connect(self.on_terminal_data)
        self.closesig.connect(parent.on_jobclose)

    def start(self, dir):
        self.runjob = TranscodeJob(self.job, self.passes, self.source, dir,
                                   self.transcode_data, self.job_complete)
        self.runjob.completesig.connect(self.on_job_complete)
        self.btnCancel.setText('Stop')
        self.runjob.start()

    @pyqtSlot(dict)
    def on_avconv_data(self, match):
        self.lblPass.setText('Pass {pass} of {passes}'.format(**match))
        self.lblFrame.setText('{frame}'.format(**match))
        self.lblFps.setText('{fps}'.format(**match))
        size = round(int(match['size']) / 1024, 2)
        self.lblSize.setText('{} MB'.format(size))
        time = DvdTimeDelta(seconds=float(match['time']))
        self.lblTime.setText('{}'.format(time))
        self.lblBitrate.setText('{bitrate} kbps'.format(**match))
        self.qualitybar.setValue(int(round(float(match['q']) * 10)))
        self.progressbar.setValue(int(round(float(match['time']))))

    @pyqtSlot(str)
    def on_terminal_data(self, text):
        self.terminal.appendPlainText(text)

    @pyqtSlot()
    def on_cancel_clicked(self):
        if self.runjob.is_alive():
            msg = QMessageBox(QMessageBox.Question, 'Cancelling Job',
                              'Do you want to cancel the running job?')
            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msg.setDefaultButton(QMessageBox.No)
            ans = msg.exec_()
            if ans == QMessageBox.Yes:
                self.runjob.cancel()
        else:
            self.close_demand()

    @pyqtSlot()
    def on_job_complete(self):
        self.lblPass.setText('Completed')
        self.btnCancel.setText('Close')

    def close_demand(self):
        self.closesig.emit(self.job_id)
        self.close()

    def cancel(self):
        self.runjob.cancel()
        self.runjob.join()
Exemple #21
0
class MainWindow(pMainWindow):
    def __init__(self, parentWidget=None):
        pMainWindow.__init__(self, parentWidget)
        self.createGui()

    def saveState(self):
        pMainWindow.saveState(self)
        
        self.settings().setValue( "MainWindow/Style",
                                  self.agStyles.currentStyle() )
        
        evm = pEnvironmentVariablesManager()
        evm.setVariables( self.eveVariables.variables() )
        evm.save()
        
        self.settings().setValue("UpdateChecker/Last Updated" ,
                                  self.ucMkS.lastUpdated())
        self.settings().setValue("UpdateChecker/Last Checked" ,
                                  self.ucMkS.lastChecked())

    def restoreState(self):
        pMainWindow.restoreState(self)
        
        self.agStyles.setCurrentStyle(
                        self.settings().value( "MainWindow/Style" ).toString() )
        
        variables = []
        evm = pEnvironmentVariablesManager()
        evm.load()
        variables = evm.variables()
        evm.mergeNewVariables( variables )
        
        self.eveVariables.setVariables( variables, True )
        
        self.ucMkS.setLastUpdated( 
            self.settings().value( "UpdateChecker/Last Updated" ).toDateTime() )
        self.ucMkS.setLastChecked( 
            self.settings().value( "UpdateChecker/Last Checked" ).toDateTime() )

    def createGui(self):
        pNetworkAccessManager.instance().setCacheDirectory(
            qApp.applicationDirPath().append( "/tmp" ) )
        
        self.twPages = QTabWidget( self )
        self.setCentralWidget( self.twPages )
        
        # initialize gui
        self.createMenuBar()
        self.createPlainTextEdit()
        self.createActionsTreeView()
        self.createConsole()
        self.createVersionsTests()
        self.createListEditors()
        self.createEnvironmentVariablesEditor()
        self.createCustomWidgets()
        self.createUpdateChecker()
        
        QTimer.singleShot( 3000, self.ucMkS.silentCheck )
        
        # create fake dock widget for testing
        '''for ( i = 0; i < 10; i++ )        dw = QDockWidget( self )
            dw.setObjectName( QString( "Dock%1" ).arg( i ) )
            dw.toggleViewAction().setObjectName( 
                        QString( "DockViewAction%1" ).arg( i ) )
            self.dockToolBar( Qt.LeftToolBarArea ).addDockWidget( 
                    dw, QString( "Dock %1" ).arg( i ), 
        QIcon( scaledPixmap( 
            ":/fresh/country-flags/ad.png", QSize( 96, 96 ) ) ) )
        }'''
        
        # list dock widgets in the menu
        for dockWidget in self.findChildren(QDockWidget):
            #dockWidget.setAttribute( Qt.WA_DeleteOnClose )
            action = dockWidget.toggleViewAction()
            self.mActionsModel.addAction( "mView/mDockWidgets/%s" % \
                        action.objectName() , action )
            self.mActionsModel.setDefaultShortcut(action, 
                QKeySequence( "Ctrl+%s" % chr( max( 32, qrand() % 127 ) ) ) )

    def createMenuBar(self):
        # set menu bar model
        self.mActionsModel = pActionsModel( self )
        self.menuBar().setModel( self.mActionsModel )
        
        # create menus and sub menus
        self.mActionsModel.addMenu( "mFile", self.tr( "&File" ) )
        self.mActionsModel.addMenu( "mEdit", self.tr( "&Edit" ) )
        self.mActionsModel.addMenu( "mView", self.tr( "&View" ) )
        self.mActionsModel.addMenu( "mView/mStyle", self.tr( "&Style" ) )
        self.mActionsModel.addMenu( "mView/mMode", self.tr( "&Mode" ) )
        self.mActionsModel.addMenu( "mView/mDockToolBarManager", self.tr( "&Dock ToolBar Manager" ) )
        self.mActionsModel.addMenu( "mView/mDockWidgets", self.tr( "Dock &Widgets" ) )
        
        # create actions
        aQuit = self.mActionsModel.addAction( "mFile/aQuit", self.tr( "&Quit" ) )
        
        aClassic = self.mActionsModel.addAction(
                        "mView/mMode/aShowClassic", self.tr( "Classic" ) )
        aClassic.setCheckable( True )
        
        aModern = self.mActionsModel.addAction(
                        "mView/mMode/aShowModern", self.tr( "Modern" ) )
        aModern.setCheckable( True )
        
        # style actions
        self.agStyles = pStylesActionGroup( self )
        self.agStyles.installInMenuBar( self.menuBar(), "mView/mStyle" )
        
        # action group
        agDockToolBarManagerMode = QActionGroup( self )
        agDockToolBarManagerMode.addAction( aClassic )
        agDockToolBarManagerMode.addAction( aModern )
        
        # add dock toolbar manager actions
        for dockToolBar in self.dockToolBarManager().dockToolBars():
            action = dockToolBar.toggleViewAction()
            self.mActionsModel.addAction(
                "mView/mDockToolBarManager/%s" % action.objectName() , action )
            
            action = dockToolBar.toggleExclusiveAction()
            self.mActionsModel.addAction(
                "mView/mDockToolBarManager/%s" % action.objectName(), action )
        
        # connections
        aQuit.triggered.connect(self.close)
        self.agStyles.styleSelected.connect(self.setCurrentStyle)
        self.dockToolBarManager().modeChanged.connect(
                            self.dockToolBarManagerModeChanged)
        aClassic.triggered.connect(self.dockToolBarManagerClassic)
        aModern.triggered.connect(self.dockToolBarManagerModern)

    def createPlainTextEdit(self):
        self.pteLog = QPlainTextEdit( self )
        self.pteLog.setReadOnly( True )
        self.pteLog.setTabStopWidth( 40 )
        self.twPages.addTab( self.pteLog, self.tr( "Log" ) )

    def createActionsTreeView(self):
        self.tvActions = QTreeView( self )
        self.tvActions.setModel( self.menuBar().model() )
        
        self.mActionsModel.addMenu( "mEdit/mActions", self.tr( "&Actions" ) )
        
        aAddAction = self.mActionsModel.addAction( "mEdit/mActions/aAddAction",
                                           self.tr( "&Add action" ) )
        aRemoveAction = self.mActionsModel.addAction( "mEdit/mActions/aRemoveAction",
                                        self.tr( "&Remove selected action" ) )
        aEditTextNode = self.mActionsModel.addAction( "mEdit/mActions/aEditTextNode",
                                        self.tr( "&Edit selected node text" ) )
        aEditShortcuts = self.mActionsModel.addAction( "mEdit/mActions/aEditShortcuts",
                                    self.tr( "Edit the actions &shortcuts" ) )
        
        aAddAction.triggered.connect(self.aAddAction_triggered)
        aRemoveAction.triggered.connect(self.aRemoveAction_triggered)
        aEditTextNode.triggered.connect(self.aEditTextNode_triggered)
        aEditShortcuts.triggered.connect(self.aEditShortcuts_triggered)
        
        self.twPages.addTab( self.tvActions, self.tr( "Actions" ) )

    def createConsole(self):
        cShell = pConsole( "Shell:/> ", self )
        self.commands = ConsoleCommands( self, self )
        cShell.addAvailableCommand( self.commands )
        
        self.dwShell = pDockWidget( self )
        self.dwShell.setObjectName( "Shell" )
        self.dwShell.setWidget( cShell )
        self.dwShell.toggleViewAction().setObjectName( "ShellViewAction" )
        self.dockToolBar( Qt.BottomToolBarArea ).addDockWidget(
               self.dwShell, 
               self.tr( "Shell" ),
               QIcon(pGuiUtils.scaledPixmap( ":/fresh/country-flags/ro.png",
                      QSize( 96, 96 ) ) ) )

    def createEnvironmentVariablesEditor(self):
        self.eveVariables = pEnvironmentVariablesEditor( self )
        
        self.dwEnvironmentVariablesEditor = pDockWidget( self )
        self.dwEnvironmentVariablesEditor.setObjectName(
                                        "EnvironmentVariablesEditor" )
        self.dwEnvironmentVariablesEditor.setWidget( self.eveVariables )
        self.dwEnvironmentVariablesEditor.toggleViewAction().setObjectName(
                                    "EnvironmentVariablesEditorViewAction" )
        self.dockToolBar( Qt.TopToolBarArea ).addDockWidget(
            self.dwEnvironmentVariablesEditor,
            self.tr( "Environment Variables Editor" ),
            QIcon( pGuiUtils.scaledPixmap(":/fresh/country-flags/it.png",
                                              QSize( 96, 96 ) ) ) )

    def createVersionsTests(self):
        v1 = pVersion ( "1.5.4" )
        v2 = pVersion ( "1.5.4a" )
        
        self.pteLog.appendPlainText( 
            self.tr( "Testing versions %s & %s:\n" % 
                    (v1.toString(), v2.toString() ) ))
        
        # test 1
        test1 = ''
        for op in [">", "<", ">=", "<=", "==", "!="]:
            test1 += '%s\t%s\t%s: %s\n' % \
                (v1.toString(),
                op,
                v2.toString(),
                str(bool(eval("v1 %s v2" % op))))
            
        # test 2
        test2 = ''
        for op in [">", "<", ">=", "<=", "==", "!="]:
            test2 += '%s\t%s\t%s: %s\n' % \
                     (v1.toString(),
                     op,
                     v1.toString(),
                     str(bool(eval("v1 %s v1" % op))))
        
        self.pteLog.appendPlainText( self.tr( "Test 1:\n%s\n" % test1 ))
        self.pteLog.appendPlainText( self.tr( "Test 2:\n%s" % test2 ))

    def createListEditors(self):
        # list editor dock
        self.dwListEditor = pDockWidget( self )
        twListEditors = QTabWidget( self.dwListEditor )
        self.dwListEditor.setObjectName( "DockListEditor" )
        self.dwListEditor.setWidget( twListEditors )
        self.dwListEditor.toggleViewAction().setObjectName(
                "DockListEditorViewAction" )
        self.dockToolBar( Qt.RightToolBarArea ).addDockWidget(
              self.dwListEditor,
              self.tr( "List Editor" ),
              QIcon(pGuiUtils.scaledPixmap( ":/fresh/country-flags/fr.png", 
                                                QSize( 96, 96 ))))
        
        twListEditors.addTab( 
              pStringListEditor( '', self ), self.tr( "Edit strings" ) )
        twListEditors.addTab(
              pPathListEditor( '', ".", self ), self.tr( "Edit paths" ) )
        twListEditors.addTab(
              pFileListEditor('', ".", "*.png", self ), self.tr( "Edit files" ))

    def createCustomWidgets(self):
        self.dwWidgets = pDockWidget( self )
        self.dwWidgets.setObjectName( "dwWidgets" )
        self.dwWidgets.toggleViewAction().setObjectName( "dwWidgetsViewAction" )
        self.dockToolBar( Qt.LeftToolBarArea ).addDockWidget(
              self.dwWidgets,
              self.tr( "Custom Widgets" ),
              QIcon( pGuiUtils.scaledPixmap( ":/fresh/country-flags/es.png",
              QSize( 96, 96 ) ) ) )
        
        self.dwWidgetsContents = QWidget( self )
        self.dwWidgetsContentsLayout = QGridLayout( self.dwWidgetsContents )
        self.dwWidgets.setWidget( self.dwWidgetsContents )
        
        pbOpenFile = QPushButton( self.tr( "Get open file names" ), self )
        self.dwWidgetsContentsLayout.addWidget( pbOpenFile, 0, 0 )
        pbOpenFile.clicked.connect(self.openFileDialog)
        
        pbOpenDirectory = QPushButton( self.tr( "Get open directory name" ),
                                       self )
        self.dwWidgetsContentsLayout.addWidget( pbOpenDirectory, 1, 0 )
        pbOpenDirectory.clicked.connect(self.openDirectoryDialog)
        
        pbQueuedMessage = QPushButton( self.tr( "Add queued message" ) )
        self.dwWidgetsContentsLayout.addWidget( pbQueuedMessage, 2, 0 )
        pbQueuedMessage.clicked.connect(self.addQueuedMessage)
        
        stylesButton = pStylesToolButton( self.dwWidgetsContents )
        stylesButton.setSizePolicy( pbQueuedMessage.sizePolicy() )
        stylesButton.setCheckableActions( False )
        self.dwWidgetsContentsLayout.addWidget( stylesButton, 3, 0 )
        stylesButton.styleSelected.connect(self.agStyles.setCurrentStyle)
        
        tcbActions = pTreeComboBox( self )
        tcbActions.setModel( self.mActionsModel )
        self.dwWidgetsContentsLayout.addWidget( tcbActions, 4, 0 )
        
        paypal = pPaypalButton( self )
        paypal.setBusinessId( "5R924WYXJ6BAW" )
        paypal.setItemName( "QWBFS Manager" )
        paypal.setItemId( "QWBFS-DONATION" )
        paypal.setCurrencyCode( "EUR" )
        self.dwWidgetsContentsLayout.addWidget( paypal, 5, 0 )
        
        toolButton1 = pToolButton( self.dwWidgetsContents )
        toolButton1.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        toolButton1.setText( self.tr( "Bottom To Top" ) )
        toolButton1.setIcon( pIconManager.icon( "pt.png") )
        toolButton1.setDirection( QBoxLayout.BottomToTop )
        self.dwWidgetsContentsLayout.addWidget( toolButton1, 0, 1, 6, 1 )
        
        toolButton2 = pToolButton( self.dwWidgetsContents )
        toolButton2.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        toolButton2.setText( self.tr( "Top To Bottom" ) )
        toolButton2.setIcon( pIconManager.icon( "br.png" ) )
        toolButton2.setDirection( QBoxLayout.TopToBottom )
        self.dwWidgetsContentsLayout.addWidget( toolButton2, 0, 2, 6, 1 )
        
        colorButton = pColorButton( self.dwWidgetsContents )
        self.dwWidgetsContentsLayout.addWidget( colorButton, 6, 0 )

    def createUpdateChecker(self):
        self.ucMkS = pUpdateChecker( self )
        self.ucMkS.setDownloadsFeedUrl( 
            QUrl("http:#code.google.com/feeds/p/monkeystudio/downloads/basic" ))
        self.ucMkS.setVersion( "1.6.0.0" )
        self.ucMkS.setVersionString( "1.6.0.0" )
        self.ucMkS.setVersionDiscoveryPattern( ".*mks_([0-9\\.]+).*" )
        
        self.mActionsModel.addMenu( "mHelp", self.tr( "&Help" ) )
        self.mActionsModel.addAction( "mHelp/aUpdateChecker", self.ucMkS.menuAction() )

    def aAddAction_triggered(self):
        index = self.tvActions.selectionModel().selectedIndexes()[0]
        path = ''
        
        if index.isValid():
            action = mActionsModel.action( index );   
            
            if action.menu():
                path = mActionsModel.path(action).split('/')[:-2]
            else:
                path = mActionsModel.path()
        
        if path:
            path += '/'
        
        path = QInputDialog.getText( 
                self,
                '',
                self.tr( "Enter the full path where to add " +
                         "the action (/some/path/to/add/the/actionName):" ),
                QLineEdit.Normal,
                path )
        
        if not "/" in path or path.replace("/", '').trim().isEmpty():
            return
        
        action = QAction( self )
        action.setText(path.split('/')[-1])
        
        if  not self.mActionsModel.addAction( path, action ) :
            del action
            QMessageBox.information(
                                self,
                                '',
                                self.tr( "Can't add action to '%s' % path" ))

    def aRemoveAction_triggered(self):
        index = self.tvActions.selectionModel().selectedIndexes()[0]
        
        if  index.isValid():
            node = self.mActionsModel.indexToNode( index )
            
            if not self.mActionsModel.removeAction( node.path() ):
                QMessageBox.information( self,
                                         '',
                                         self.tr( "Can't remove action '%s'" % 
                                                  node.path() ) )

    def aEditTextNode_triggered(self):
        index = self.tvActions.selectionModel().selectedIndexes()[0]
        
        if index.isValid():
            node = self.mActionsModel.indexToNode( index )
            text = QInputDialog.getText( self,
                                         '',
                                         self.tr( "Enter the node text:" ),
                                         QLineEdit.Normal,
                                         node.text())
            
            if text:
                node.setText( text )

    def aEditShortcuts_triggered(self):
        dlg = pActionsShortcutEditor ( self.mActionsModel, self )
        dlg.exec_()

    def dockToolBarManagerModeChanged(self, mode ):
        if mode == pDockToolBarManager.Classic:
            self.mActionsModel.action( "mView/mMode/aShowClassic" ).trigger()
        elif mode == pDockToolBarManager.Modern:
            self.mActionsModel.action( "mView/mMode/aShowModern" ).trigger()
        else:
            assert(0)

    def dockToolBarManagerClassic(self):
        self.dockToolBarManager().setMode( pDockToolBarManager.Classic )

    def dockToolBarManagerModern(self):
        self.dockToolBarManager().setMode( pDockToolBarManager.Modern )

    def addQueuedMessage(self):
        ok, message = QInputDialog.getText( 
                                    self,
                                    self.tr( "Add a queued message" ),
                                    self.tr( "Enter the message to show:" ),
                                    QLineEdit.Normal,
                                    self.tr( "This is the default message" ))
        
        if  ok and message:
            msg = pQueuedMessage()
            msg.message = message
            msg.buttons[ QDialogButtonBox.Ok ] = ''
            msg.buttons[ QDialogButtonBox.Yes ] = self.tr( "Show QMessageBox" )
            msg.object = self
            msg.slot = "queuedMessageToolBarButtonClicked"
            
            queuedMessageToolBar().appendMessage( msg )

    def queuedMessageToolBarButtonClicked(self, button, message ):
        if button == QDialogButtonBox.Yes:
            QMessageBox.information( self, '', message.message )

    def setCurrentStyle(self, style ):
        QApplication.setStyle( style )

    def openFileDialog(self):
        caption = ''
        dir = ''
        filter = ''
        enabledTextCodec = True
        enabledOpenReadOnly = True
        selectedFilter = ''
        options = 0
        result = pFileDialog.getOpenFileNames(self, caption, dir,
                                              filter, enabledTextCodec,
                                              enabledOpenReadOnly,
                                              selectedFilter, options)
        
        self.pteLog.appendPlainText( '' )
        
        if result.isEmpty():
            self.pteLog.appendPlainText(
                    self.tr( "You canceled the open file dialog" ) )
        else:
            texts = []
            
            texts.append(self.tr( "You accepted the open file dialog" ))
            
            for type in result.keys():
                if type == pFileDialog.TextCodec:
                    texts.append(
                      self.tr( "TextCodec: %s" % result[ type ].toString() ))
                elif type == pFileDialog.OpenReadOnly:
                    texts.append(
                      self.tr( "OpenReadOnly: %s" % result[ type ].toString() ))
                elif type == pFileDialog.Directory:
                    texts.append(
                      self.tr( "Directory: %s" % result[ type ].toString() ))
                elif type == pFileDialog.FileName:
                    texts.append(
                      self.tr( "FileName: %s" % result[ type ].toString() ))
                elif type == pFileDialog.FileNames:
                    texts.append(
                      self.tr( "FileNames: %s" % 
                                ", ".join(result[ type ].toStringList())))
                elif type == pFileDialog.SelectedFilter:
                    texts.append(
                    self.tr( "SelectedFilter: %s" % result[ type ].toString() ))
            
            self.pteLog.appendPlainText( '\n'.join(texts))

    def openDirectoryDialog(self):
        caption = ''
        dir = ''
        filter = ''
        enabledTextCodec = True
        enabledOpenReadOnly = True
        selectedFilter = ''
        options = 0
        result = pFileDialog.getExistingDirectory( 
                                        self, caption, dir, 
                                        enabledTextCodec, 
                                        enabledOpenReadOnly,
                                        options | QFileDialog.ShowDirsOnly )
        
        self.pteLog.appendPlainText( '' )
        
        if not result:
            self.pteLog.appendPlainText(
                        self.tr( "You canceled the open directory dialog" ) )
        else:
            texts = []
            
            texts.append(self.tr( "You accepted the open directory dialog" ))
            
            for type in result.keys():
                if type == pFileDialog.TextCodec:
                    texts.append(
                        self.tr( "TextCodec: %s" % result[ type ].toString() ))
                elif type == pFileDialog.OpenReadOnly:
                    texts.append(
                        self.tr("OpenReadOnly: %s" % result[ type ].toString()))
                elif type == pFileDialog.Directory:
                    texts.append(
                        self.tr( "Directory: %s" % result[ type ].toString() ))
                elif type == pFileDialog.FileName:
                    texts.append(
                        self.tr( "FileName: %s" % result[ type ].toString() ))
                elif type == pFileDialog.FileNames:
                    texts.append(
                        self.tr( "FileNames: %s" % 
                                  ", ".join(result[ type ].toStringList())))
                elif type == pFileDialog.SelectedFilter:
                    texts.append(self.tr( "SelectedFilter: %s" % 
                                 result[ type ].toString() ))
            
            self.pteLog.appendPlainText( '\n'.join(texts))