コード例 #1
0
ファイル: RaceModel.py プロジェクト: gaffcodes/QBetty
 def flags(self, index):
     if not index.isValid():
         return Qt.ItemIsEnabled
     if self.isColumn("round", index) or self.isColumn("adjRating", index):
         return Qt.ItemFlags(QAbstractTableModel.flags(self, index))
     return Qt.ItemFlags(
         QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)
コード例 #2
0
ファイル: moviedata.py プロジェクト: hooloong/gitpython
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(
                         encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(fname).fileName())
コード例 #3
0
ファイル: e2tomo_eval.py プロジェクト: landang14/eman2
 def __init__(self, parent=None):
     super(TomoListWidget, self).__init__(parent)
     self.parent = parent
     self.itemflags = Qt.ItemFlags(Qt.ItemIsSelectable) | Qt.ItemFlags(
         Qt.ItemIsEnabled)
     self.itemlst = []
     self.lblen = 10
コード例 #4
0
	def __init__(self,target):
		QtGui.QWidget.__init__(self)

		self.target = weakref.ref(target) # this should be the EMImageMXWidget
		self.busy = False
		self.initialized=False

		# cached values for speed later
		self.itemflags=	Qt.ItemFlags(Qt.ItemIsEditable)|Qt.ItemFlags(Qt.ItemIsSelectable)|Qt.ItemFlags(Qt.ItemIsEnabled)|Qt.ItemFlags(Qt.ItemIsUserCheckable)

		# now build the interface
		hbl = QtGui.QHBoxLayout(self)
		self.setlist=QtGui.QListWidget()
		self.setlist.setSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Expanding)
		hbl.addWidget(self.setlist)

		vbl = QtGui.QVBoxLayout()

		self.new_set_button = QtGui.QPushButton("New")
		vbl.addWidget(self.new_set_button)
		self.rename_set_button = QtGui.QPushButton("Rename")
		vbl.addWidget(self.rename_set_button)
		self.save_set_button = QtGui.QPushButton("Save")
		vbl.addWidget(self.save_set_button)
		self.delete_set_button = QtGui.QPushButton("Delete")
		vbl.addWidget(self.delete_set_button)

		hbl.addLayout(vbl)

		self.save_set_button.clicked[bool].connect(self.save_set)
		self.new_set_button.clicked[bool].connect(self.new_set)
		self.rename_set_button.clicked[bool].connect(self.rename_set)
		self.delete_set_button.clicked[bool].connect(self.delete_set)
		self.setlist.itemChanged[QtGui.QListWidgetItem].connect(self.set_list_item_changed)
		self.setlist.currentRowChanged[int].connect(self.set_list_row_changed)
コード例 #5
0
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(fname).fileName())
コード例 #6
0
def getTooltipValue( value ):
    """ Takes a potentially multilined string and converts it to
        the form suitable for tooltips """

    value = str( value )
    if Qt.mightBeRichText( value ):
        tooltipValue = str( Qt.escape( value ) )
    else:
        tooltipValue = value

    lines = tooltipValue.splitlines()
    lineCount = len( lines )
    if lineCount > 1:
        value = ""
        index = 0
        for line in lines:
            if index >= 5:  # First 5 lines only
                break
            if index > 0:
                value += "\n"
            if len( line ) > 128:
                value += line[ : 128 ] + "<...>"
            else:
                value += line
            index += 1
        if lineCount > 5:
            value += "\n<...>"
    elif lineCount == 1:
        if len( lines[ 0 ] ) > 128:
            value = lines[ 0 ][ : 128 ] + "<...>"
        else:
            value = lines[ 0 ]

    return value
コード例 #7
0
ファイル: webpage.py プロジェクト: ver007/quiet-mist-212
    def sendEvent(self, type_, arg1, arg2):
        type_ = type_.lower()

        if type_ in ('mousedown', 'mouseup', 'mousemove'):
            eventType = QMouseEvent.Type(QEvent.None)
            button = Qt.MouseButton(Qt.LeftButton)
            buttons = Qt.MouseButtons(Qt.LeftButton)

            if type_ == 'mousedown':
                eventType = QEvent.MouseButtonPress
            elif type_ == 'mouseup':
                eventType = QEvent.MouseButtonRelease
            elif type_ == 'mousemove':
                eventType = QEvent.MouseMove
                button = buttons = Qt.NoButton

            assert eventType != QEvent.None

            event = QMouseEvent(eventType, QPoint(arg1, arg2), button, buttons, Qt.NoModifier)
            QApplication.postEvent(self.m_webPage, event)
            QApplication.processEvents()

            return

        if type_ == 'click':
            self.sendEvent('mousedown', arg1, arg2)
            self.sendEvent('mouseup', arg1, arg2)
コード例 #8
0
ファイル: chat.py プロジェクト: dhrosa/empyre_old
 def updateHistory(self):
     lines = []
     for line in self.lines:
         text = Qt.escape(line.text)
         target = Qt.escape(line.target)
         if line.type == Line.Chat or line.type == Line.Whisper:
             (r, g, b) = [int(c * 0.75) for c in line.playerColor]
             sender = Qt.escape(line.sender)
             dateTime = QDateTime.fromTime_t(int(line.timestamp))
             time = dateTime.toString("hh:mm:ss AP")
             if line.type == Line.Whisper:
                 lines.append("<p><strong style=\"color: rgb(%d, %d, %d)\">[%s] %s >> %s</strong>: %s</p>" % (r, g, b, time, sender, target, text))
             else:
                 lines.append("<p><strong style=\"color: rgb(%d, %d, %d)\">[%s] %s</strong>: %s</p>" % (r, g, b, time, sender, text))
         else:
             if line.type == Line.Info:
                 (r, g, b) = (0, 0, 170)
                 text = line.text
             elif line.type == Line.PlayerJoined:
                 (r, g, b) = (0, 170, 0)
                 text = "%s has joined." % (target)
             elif line.type == Line.PlayerRejoined:
                 (r, g, b) = (0, 170, 0)
                 text = "%s has rejoined." % (target)
             elif line.type == Line.PlayerLeft:
                 (r, g, b) = (170, 0, 0)
                 text = "%s has left." % (target)
             lines.append("<p style=\"color: rgb(%d, %d, %d)\">** %s **</p>" % (r, g, b, text))
     self.history.setHtml(
         "<html><body>%s</body></html>" % ("".join(lines))
     )
     self.history.verticalScrollBar().setValue(self.history.verticalScrollBar().maximum())
コード例 #9
0
 def flags( self, index ):
     if not index.isValid():
         return Qt.ItemIsEnabled
     if index.column() == CANTIDAD:
         return Qt.ItemFlags( QAbstractTableModel.flags( self, index )
                          | Qt.ItemIsEditable )
     else:
         return Qt.ItemFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled)
コード例 #10
0
 def sortByName(self):
     self.treeWidget.setSortingEnabled(True)
     if self.sortToggle:
         self.treeWidget.sortByColumn(0, Qt.SortOrder(Qt.AscendingOrder))
     else:
         self.treeWidget.sortByColumn(0, Qt.SortOrder(Qt.DescendingOrder))
     self.treeWidget.setSortingEnabled(False)
     self.sortToggle = not self.sortToggle
コード例 #11
0
 def flags(self, index):
     if not index.isValid():
         return Qt.ItemIsEnabled
     column = index.column()
     if column in (MOD1, MOD2, MOD3, KEY):
         return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|
                             Qt.ItemIsEditable)
     else:
         return Qt.ItemFlags(QAbstractTableModel.flags(self, index))
コード例 #12
0
def run_in_thread(fn, args):
    worker = Worker(*args)
    worker.process = fn
    thread = QThread()
    worker.moveToThread(thread)
    app = QApplication.instance()
    app.connect(thread, Qt.SIGNAL('started()'), worker.start)
    app.connect(worker, Qt.SIGNAL('finished()'), thread.quit)
    app.connect(worker, Qt.SIGNAL('finished()'), thread.deleteLater)
    return worker, thread
コード例 #13
0
    def flags(self, index):

        if not index.isValid():
            return Qt.NoItemFlags

        item = self.colours[index.row()]
        thread_type = self.headers[index.column()]

        if item.hasThread(thread_type):
            return Qt.ItemIsEnabled | Qt.ItemIsSelectable
        else:
            return Qt.ItemFlags(Qt.ItemFlag(0))  # Qt.NoItemFlags
コード例 #14
0
ファイル: abstract_tables.py プロジェクト: whaozl/ibeis
 def flags(self, index):
     """ Returns the item flags for the given index. """
     if index.column() == 0:
         # The First Column is just a label and unchangable
         return Qt.ItemIsEnabled | Qt.ItemIsSelectable
     if not index.isValid():
         return Qt.ItemFlag(0)
     item_col, item_rowid = self.index2_itemdata(index)
     if item_rowid:
         if item_col in self.col_editable:
             return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
     return Qt.ItemFlag(0)
コード例 #15
0
ファイル: factura.py プロジェクト: luismejiadev/pyqt_billing
    def printDocument1(self):
        html = u""

        date = QDate.currentDate().toString(self.DATE_FORMAT)

        address = Qt.escape("Bario francisco mesa").replace(",", "<br>")
        contact = Qt.escape("Luis Mejia")
        balance = 5000
        html += ("<p align=right><img src=':/logo.png'></p>"
                 "<p> align = right>Greasy hands ltd."
                 "<br>New Lombard Street"
                 "<br>London<br>WC13 4PX<br>%s</p>"
                 "<p>%s</p><p>Dear %s, </p>"
                 "<p>The balance of your account is %s.") % (
                     date, address, contact, QString("$ %L1").arg(
                         float(balance), 0, "f", 2))

        if balance < 0:
            html += (
                "<p><font color =red><b> Please remit the amount owing immediately.</b></font>"
            )
        else:
            html += "We are delighted to have done business with you."

        html += (
            "</p><p>&nbsp;</p><p>"
            "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>"
        )
        transactions = [(QDate.currentDate(), 500), (QDate.currentDate(), 500),
                        (QDate.currentDate(), -500),
                        (QDate.currentDate(), 500)]
        for date, amount in transactions:
            color, status = "black", "Credit"
            if amount < 0:
                color, status = "red", "Debid"

            html += (
                "<tr>"
                "<td align= right>%s</td>"
                "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>"
                % (date.toString(self.DATE_FORMAT), status, color,
                   QString("$ %L1").arg(float(abs(amount)), 0, "f", 2)))

        html += ("</table></p><p style='page-break-after=always;'>"
                 "We hope to continue doing business with you</p>")

        pdialog = QPrintDialog()
        if pdialog.exec_() == QDialog.Accepted:
            printer = pdialog.printer()
            document = QTextDocument()
            document.setHtml(html)
            document.print_(printer)
コード例 #16
0
 def playOnPicture(self, pic):
     if not self.PIC_CHK_D():
         return None
     if pic and pic.picture():
         self.end()
         cpyPic = Qt.QPicture()
         cpyPic.setData(self.d.pic_.data(), self.d.pic_.size())
         pa = Qt.QPainter(pic.picture())
         cpyPic.play(pa)
         pa.end()
         self.begin()
         self.d.pte_.drawPicture(0, 0, cpyPic)
         return pic
     return False
コード例 #17
0
ファイル: factura.py プロジェクト: joseanm/pyqt_billing
    def printDocument1(self):
        html = u""

        date = QDate.currentDate().toString(self.DATE_FORMAT)
        
        address = Qt.escape("Bario francisco mesa").replace(",","<br>")
        contact = Qt.escape("Luis Mejia")
        balance = 5000
        html += ("<p align=right><img src=':/logo.png'></p>"
                 "<p> align = right>Greasy hands ltd."
                 "<br>New Lombard Street"
                 "<br>London<br>WC13 4PX<br>%s</p>"
                 "<p>%s</p><p>Dear %s, </p>"
                 "<p>The balance of your account is %s.")% (
                   date, address, contact, QString("$ %L1").arg(float(balance),0,"f",2))
                 
        if balance <0 :
            html += ("<p><font color =red><b> Please remit the amount owing immediately.</b></font>")
        else:
            html += "We are delighted to have done business with you."
        
        html += ("</p><p>&nbsp;</p><p>"
                "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>")
        transactions = [
                        (QDate.currentDate(),500),
                        (QDate.currentDate(),500),
                        (QDate.currentDate(),-500),
                        (QDate.currentDate(),500)
                        ]
        for date, amount in transactions:
            color, status = "black", "Credit"
            if amount <0:
                color, status = "red", "Debid"
            
            html += ("<tr>"
                        "<td align= right>%s</td>"
                        "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % (
                        date.toString(self.DATE_FORMAT), status,color, QString("$ %L1").arg(float(abs(amount)), 0, "f",2)))
            
        html += ("</table></p><p style='page-break-after=always;'>"
                 "We hope to continue doing business with you</p>")
                 
        
        pdialog = QPrintDialog() 
        if pdialog.exec_() == QDialog.Accepted:
            printer = pdialog.printer()
            document = QTextDocument()
            document.setHtml(html)
            document.print_(printer)
コード例 #18
0
    def click_through_model(self, model_ui, files_to_check):
        """Click through a standard modelui interface.

            model_ui - an instance of natcap.invest.iui.modelui.ModelUI
            files_to_check - a list of strings.  Each string must be a URI
                relative to the workspace.  All files at these URIs are required
                to exist.  An AssertionError will be thrown if a file does not
                exist.

        Returns nothing."""

        workspace_element = locate_workspace_element(model_ui)

        workspace_element.setValue(self.workspace)
        QTest.qWait(100)  # Wait for the test workspace to validate

        # Assert that the test workspace didn't get a validation error.
        self.assertEqual(workspace_element.has_error(), False)

        # Assert that there are no default data validation errors.
        validation_errors = model_ui.errors_exist()
        self.assertEqual(
            validation_errors, [], 'Validation errors '
            'exist for %s inputs. Errors: %s' %
            (len(validation_errors), validation_errors))

        # Click the 'Run' button and see what happens now.
        QTest.mouseClick(model_ui.runButton, Qt.MouseButton(1))

        # Now that the run button has been pressed, we need to check the state
        # of the operation dialog to see if it has finished completing.  This
        # check is done at half-secong intervals.
        while not model_ui.operationDialog.backButton.isEnabled():
            QTest.qWait(500)

        # Once the test has finished, click the back button on the dialog to
        # return toe the UI.
        QTest.mouseClick(model_ui.operationDialog.backButton,
                         Qt.MouseButton(1))

        missing_files = []
        for filepath in files_to_check:
            full_filepath = os.path.join(self.workspace, filepath)
            if not os.path.exists(full_filepath):
                missing_files.append(filepath)

        self.assertEqual(
            missing_files, [], 'Some expected files were not '
            'found: %s' % missing_files)
コード例 #19
0
 def playOnPixmap(self, pix):
     if not self.PIC_CHK_D():
         return None
     if not pix:
         return False
     self.end()
     cpyPic = Qt.QPicture()
     cpyPic.setData(self.d.pic_.data(), self.d.pic_.size())
     pa = Qt.QPainter(pix)
     pa.setClipRect(0, 0, pix.width(), pix.height())
     cpyPic.play(pa)
     pa.end()
     self.begin()
     self.d.pte_.drawPicture(0, 0, cpyPic)
     return pix
コード例 #20
0
            def cb_read(result):
                self.log_file.release()
                self.log_file = None

                self.label_download.setVisible(False)
                self.progress_download.setVisible(False)

                if result.error != None:
                    self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True)
                    return

                try:
                    self.content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    self.log(u'Error: Log file is not UTF-8 encoded', bold=True)
                    return

                self.button_save.setEnabled(True)

                if self.continuous:
                    content = self.content.lstrip()
                else:
                    content = self.content

                self.edit_content.setPlainText('')

                font = QFont('monospace')
                font.setStyleHint(QFont.TypeWriter)

                self.edit_content.setFont(font)
                self.edit_content.setPlainText(content)
コード例 #21
0
ファイル: previewdialog.py プロジェクト: wibrt/orange3
    def __init__(self, parent=None, flags=Qt.WindowFlags(0),
                 model=None, **kwargs):
        QDialog.__init__(self, parent, flags, **kwargs)

        self.__setupUi()
        if model is not None:
            self.setModel(model)
コード例 #22
0
 def flags(self, index):
     """
     return the item flags
     """
     if not index.isValid():
         return Qt.ItemIsEnabled
     return Qt.ItemFlags(QAbstractTableModel.flags(self, index))
コード例 #23
0
ファイル: test_owsieve.py プロジェクト: zaffnet/orange3
 def _select_data(self):
     area = self.widget.areas[0]
     self.widget.select_area(
         area,
         QMouseEvent(QEvent.MouseButtonPress, QPoint(), Qt.LeftButton,
                     Qt.LeftButton, Qt.KeyboardModifiers()))
     return [0, 4, 6, 7, 11, 17, 19, 21, 22, 24, 26, 39, 40, 43, 44, 46]
コード例 #24
0
            def cb_read(result):
                self.log_file.release()
                self.log_file = None

                self.label_download.setVisible(False)
                self.progress_download.setVisible(False)

                if result.error != None:
                    self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True)
                    return

                try:
                    self.content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    self.log(u'Error: Log file is not UTF-8 encoded', bold=True)
                    return

                self.button_save.setEnabled(True)

                if self.continuous:
                    content = self.content.lstrip()
                else:
                    content = self.content

                self.edit_content.setPlainText('')

                font = QFont('monospace')
                font.setStyleHint(QFont.TypeWriter)

                self.edit_content.setFont(font)
                self.edit_content.setPlainText(content)
コード例 #25
0
    def initTable(self):
        # stop the update timer
        self.timerDataRequest.stop()

        # init servo memory data table
        self.tableServoData.clear()
        self.tableServoData.setColumnCount(1)
        self.tableServoData.setHorizontalHeaderItem(
            0, QTableWidgetItem('Parameter'))
        self.tableServoData.setRowCount(
            len(self.serialProtocol.memoryInfo['fieldNames']))
        rowNumber = 0
        for fieldName in self.serialProtocol.memoryInfo['fieldNames']:
            fieldInfo = self.serialProtocol.memoryInfo[fieldName]
            nameItem = QTableWidgetItem(fieldInfo['name'])
            if fieldInfo['writable']:
                nameItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            else:
                nameItem.setFlags(Qt.ItemFlag())
            self.tableServoData.setItem(rowNumber, 0, nameItem)
            self.tableServoData.resizeRowToContents(rowNumber)
            self.tableServoData.setRowHeight(
                rowNumber,
                self.tableServoData.rowHeight(rowNumber) - 7)
            rowNumber += 1
        self.tableServoData.resizeColumnToContents(0)

        # restart the update timer
        self.timerDataRequest.start(20)
コード例 #26
0
 def log(self, message, bold=False, pre=False):
     if bold:
         self.edit_content.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
     elif pre:
         self.edit_content.appendHtml(u'<pre>{0}</pre>'.format(message))
     else:
         self.edit_content.appendPlainText(message)
コード例 #27
0
ファイル: splashscreen.py プロジェクト: 675801717/orange3
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
コード例 #28
0
ファイル: stickynotes_plus.py プロジェクト: AG4GitHub/leo
    def toMarkdown(self):
        references = ''
        i = 1
        # doc = QString() # the full document
        doc = g.u('')
        block = self.document().begin(
        )  # block is like a para; text fragment is sequence of same char format
        while block.isValid():
            #print "block=",block.text()
            if block.blockFormat().nonBreakableLines():
                doc += '    ' + block.text() + '\n'
            #elif block.textList():
            #textList = block.textList()
            #print block.textList().count()
            #print g.u(block.textList().itemText(block))
            #print block.textList().itemNumber(block)
            #print block.textList().item(block.textList().itemNumber(block)).text()
            #doc += textList.itemText(block) + ' ' + textList.item(textList.itemNumber(block)).text() + '\n\n'
            else:
                if block.textList():
                    doc += '  ' + block.textList().itemText(block) + ' '
                # para = QString()
                para = g.u('')
                iterator = block.begin()
                while iterator != block.end():
                    fragment = iterator.fragment()
                    if fragment.isValid():
                        char_format = fragment.charFormat()
                        text = g.u(Qt.escape(fragment.text())
                                   )  # turns chars like < into entities &lt;
                        font_size = char_format.font().pointSize()
                        # a fragment can only be an anchor, italics or bold
                        if char_format.isAnchor():
                            ref = text if text.startswith(
                                'http://') else 'http://{0}'.format(text)
                            # too lazy right now to check if URL has already been referenced but should
                            references += "  [{0}]: {1}\n".format(i, ref)
                            text = "[{0}][{1}]".format(text, i)
                            i += 1
                        elif font_size > 10:
                            if font_size > 15:
                                text = '#{0}'.format(text)
                            elif font_size > 12:
                                text = '##{0}'.format(text)
                            else:
                                text = '###{0}'.format(text)
                        elif char_format.fontFixedPitch(
                        ):  #or format.fontFamily=='courier':
                            text = QString("`%1`").arg(text)
                        elif char_format.fontItalic():
                            text = QString("*%1*").arg(text)
                        elif char_format.fontWeight(
                        ) > QFont.Normal:  #font-weight:600; same as for an H1; H1 font-size:xx-large; H1 20; H2 15 H3 12
                            text = QString("**%1**").arg(text)

                        para += text
                    iterator += 1
                doc += para + '\n\n'
            block = block.next()
        return doc + references
コード例 #29
0
 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)
コード例 #30
0
    def updateUI(self):
        theme = self.m_themeComboBox.itemData(
            self.m_themeComboBox.currentIndex())

        if self.m_charts[0].chart().theme() != theme:
            for chartView in self.m_charts:
                chartView.chart().setTheme(theme)

            pal = self.window().palette()

            if theme == QChart.ChartThemeLight:
                pal.setColor(QPalette.Window, QColor(0xf0f0f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeDark:
                pal.setColor(QPalette.Window, QColor(0x121218))
                pal.setColor(QPalette.WindowText, QColor(0xd6d6d6))
            elif theme == QChart.ChartThemeBlueCerulean:
                pal.setColor(QPalette.Window, QColor(0x40434a))
                pal.setColor(QPalette.WindowText, QColor(0xd6d6d6))
            elif theme == QChart.ChartThemeBrownSand:
                pal.setColor(QPalette.Window, QColor(0x9e8965))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeBlueNcs:
                pal.setColor(QPalette.Window, QColor(0x018bba))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeHighContrast:
                pal.setColor(QPalette.Window, QColor(0xffab03))
                pal.setColor(QPalette.WindowText, QColor(0x181818))
            elif theme == QChart.ChartThemeBlueIcy:
                pal.setColor(QPalette.Window, QColor(0xcee7f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            else:
                pal.setColor(QPalette.Window, QColor(0xf0f0f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))

            self.window().setPalette(pal)

        checked = self.m_antialiasCheckBox.isChecked()
        for chartView in self.m_charts:
            chartView.setRenderHint(QPainter.Antialiasing, checked)

        options = QChart.AnimationOptions(
            self.m_animatedComboBox.itemData(
                self.m_animatedComboBox.currentIndex()))

        if self.m_charts[0].chart().animationOptions() != options:
            for chartView in self.m_charts:
                chartView.chart().setAnimationOptions(options)

        alignment = self.m_legendComboBox.itemData(
            self.m_legendComboBox.currentIndex())

        for chartView in self.m_charts:
            legend = chartView.chart().legend()

            if alignment == 0:
                legend.hide()
            else:
                legend.setAlignment(Qt.Alignment(alignment))
                legend.show()
コード例 #31
0
ファイル: splashscreen.py プロジェクト: yisuax11/orange2
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
コード例 #32
0
    def flags(self, index):
        """
        Overriding method flags

        @param index: 
        @type index:

        @return:
        @rtype:
        """
        if not index.isValid():
            return Qt.ItemIsEnabled
        if index.column() == COL_ID:
            return Qt.ItemFlags(QAbstractTableModel.flags(self, index))
        else:
            return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable| Qt.ItemIsDragEnabled)
コード例 #33
0
    def createWidgets(self):
        """
        Create all widgets
        """
        self.setWindowIcon(QIcon(':/plugin.png'))

        self.mainTab = QTabWidget()

        self.aboutPage = AboutPage(parent=self)
        self.debugPage = DebugPage(parent=self)

        self.mainTab.addTab(self.aboutPage, "About")
        self.mainTab.addTab(self.debugPage, "Debug")

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.mainTab)
        self.setLayout(mainLayout)

        self.setWindowTitle("%s - %s - %s" %
                            (Settings.instance().readValue(key='Common/name'),
                             self.pluginName, self.pluginVersion))

        flags = Qt.WindowFlags()
        if not self.debugMode: flags |= Qt.WindowStaysOnTopHint
        self.setWindowFlags(flags)
コード例 #34
0
ファイル: WelcomeTab.py プロジェクト: khosrow/luma-devel
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setupUi(self)
     self.retranslate(all=False)
     self.settings = QSettings()
     show = self.settings.value('showWelcome', 2).toInt()[0]
     self.checkBox.setCheckState(Qt.CheckState(show))
コード例 #35
0
 def flags(self, index):
     res = super(UnivTableModel, self).flags(index)
     c = self.column(index.column())
     if c.isEditable():
         return Qt.ItemFlags(res | QtCore.Qt.ItemIsEditable)
     else:
         return res
コード例 #36
0
    def createDialog(self):
        """
        Create qt dialog
        """
        self.setWindowTitle("%s" % self.name)
        layout = QVBoxLayout()

        self.loadingLabel = QLabel("Loading...")
        self.imageLabel = QLabel()

        layout2 = QHBoxLayout()
        layout2.addWidget(self.imageLabel)
        layout2.addWidget(self.loadingLabel)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(0)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        layout.addLayout(layout2)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)

        flags = Qt.WindowFlags()
        flags |= Qt.MSWindowsFixedSizeDialogHint
        self.setWindowFlags(flags)
コード例 #37
0
    def toMarkdown(self):
        references = ''
        i = 1
        # doc = QString() # the full document
        doc = g.u('')
        block = self.document().begin() # block is like a para; text fragment is sequence of same char format
        while block.isValid():
            #print "block=",block.text()
            if block.blockFormat().nonBreakableLines():
                doc += '    '+block.text()+'\n'
            #elif block.textList():
                #textList = block.textList()
                #print block.textList().count()
                #print g.u(block.textList().itemText(block))
                #print block.textList().itemNumber(block)
                #print block.textList().item(block.textList().itemNumber(block)).text()
                #doc += textList.itemText(block) + ' ' + textList.item(textList.itemNumber(block)).text() + '\n\n'
            else:
                if block.textList():
                    doc += '  '+block.textList().itemText(block) + ' '
                # para = QString()
                para = g.u('')
                iterator = block.begin()
                while iterator != block.end():
                    fragment = iterator.fragment()
                    if fragment.isValid():
                        char_format = fragment.charFormat()
                        # pylint: disable=no-member
                        # EKR: I'm not sure whether this warning is valid.
                        # I'm going to kill it because this is an experimental plugin.
                        text = g.u(Qt.escape(fragment.text()))
                            # turns chars like < into entities &lt;
                        font_size = char_format.font().pointSize()
                        # a fragment can only be an anchor, italics or bold
                        if char_format.isAnchor():
                            ref = text if text.startswith('http://') else 'http://{0}'.format(text)
                            # too lazy right now to check if URL has already been referenced but should
                            references += "  [{0}]: {1}\n".format(i,ref)
                            text = "[{0}][{1}]".format(text,i)
                            i+=1
                        elif font_size > 10:
                            if font_size > 15:
                                text = '#{0}'.format(text)
                            elif font_size > 12:
                                text = '##{0}'.format(text)
                            else:
                                text = '###{0}'.format(text)
                        elif char_format.fontFixedPitch(): #or format.fontFamily=='courier':
                            text = QString("`%1`").arg(text)
                        elif char_format.fontItalic():
                            text = QString("*%1*").arg(text)
                        elif char_format.fontWeight() > QFont.Normal: #font-weight:600; same as for an H1; H1 font-size:xx-large; H1 20; H2 15 H3 12
                            text = QString("**%1**").arg(text)

                        para += text
                    iterator += 1
                doc += para+'\n\n'
            block = block.next()
        return doc+references
コード例 #38
0
    def log(self, message, bold=False, pre=False):
        if bold:
            self.edit_log.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
        elif pre:
            self.edit_log.appendHtml(u'<pre>{0}</pre>'.format(message))
        else:
            self.edit_log.appendPlainText(message)

        self.edit_log.verticalScrollBar().setValue(self.edit_log.verticalScrollBar().maximum())
コード例 #39
0
ファイル: IM.py プロジェクト: AchillesA/cspace
 def _chatMessage( self, msg, fromUser ) :
     msg = unicode( msg, 'utf8', 'replace' )
     msg = unicode( Qt.escape(msg) )
     msg = msg.replace( '\r\n', '<br/>' )
     msg = msg.replace( '\n', '<br/>' )
     msg = msg.replace( '\t', '    ' )
     msg = msg.replace( '  ', ' &nbsp;' )
     color = (fromUser == self.peerName) and '#FF821C' or 'black'
     self.ui.chatLogView.append( u'<font face="Verdana" size=-1 color="%s"><b>%s: </b></font>%s' % (color,fromUser,msg) )
     self.flash()
コード例 #40
0
    def download_error(self, message, *args):
        string_args = []

        for arg in args:
            string_args.append(Qt.escape(unicode(arg)))

        if len(string_args) > 0:
            message = unicode(message).format(*tuple(string_args))

        self.log(message, bold=True)
コード例 #41
0
    def report_error(self, message, *args):
        string_args = []

        for arg in args:
            string_args.append(Qt.escape(unicode(arg)))

        if len(string_args) > 0:
            message = unicode(message).format(*tuple(string_args))

        self.widget.progress.close()
        QMessageBox.critical(get_main_window(), 'Import Error', message)
コード例 #42
0
    def upload_warning(self, message, *args):
        self.warnings += 1

        string_args = []

        for arg in args:
            string_args.append(Qt.escape(unicode(arg)))

        if len(string_args) > 0:
            message = unicode(message).format(*tuple(string_args))

        self.log(message, bold=True)
コード例 #43
0
def write_description_content(handle, data): 
    """ This function generates the xml content of the description 
    file.
    """
    
    stream = QTextStream(handle)
    stream.setCodec("UTF-8")
    stream << ("<?xml version='1.0' encoding='UTF-8'?>\n"
               "<sconcho>\n"
               "  <knittingSymbol>\n"
               "    <svgName>%s</svgName>\n"
               "    <category>%s</category>\n"
               "    <symbolName>%s</symbolName>\n"
               "    <symbolDescription>%s</symbolDescription>\n"
               "    <symbolWidth>%d</symbolWidth>\n"
               "  </knittingSymbol>\n"
               "</sconcho>\n"
               % (Qt.escape(data["svgName"]), 
                  Qt.escape(data["category"]), 
                  Qt.escape(data["name"]), 
                  Qt.escape(data["description"]), 
                  data["width"]))
コード例 #44
0
ファイル: html.py プロジェクト: maximerobin/Ufwi
def escapeHTML(text, nl2br=True):
    r"""
    Escape HTML to be used in a widget displaying HMTL code.
    Example:

    >>> escapeHTML('<a>text</a>')
    u'&lt;a&gt;text&lt;/a&gt;'
    >>> print escapeHTML('one\ntwo')
    one<br />two
    """
    text = Qt.escape(text)
    text = unicode(text)
    if nl2br:
        text = text.replace("\n", "<br />")
    return text
コード例 #45
0
    def upload_error(self, message, *args):
        string_args = []

        for arg in args:
            string_args.append(Qt.escape(unicode(arg)))

        if len(string_args) > 0:
            message = unicode(message).format(*tuple(string_args))

        self.log(message, bold=True)

        if not self.edit_mode and self.program_defined:
            try:
                self.program.purge() # FIXME: async_call
            except (Error, REDError):
                pass # FIXME: report this error?
コード例 #46
0
        def cb_walk(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' + Qt.escape(message))
                self.label_error.setVisible(True)
                self.refresh_files_done()
                return

            self.label_error.setVisible(False)

            def expand_async(data):
                try:
                    walk = json.loads(zlib.decompress(buffer(data)).decode('utf-8'))
                except:
                    walk = None

                if walk == None or not isinstance(walk, dict):
                    available_files       = []
                    available_directories = []
                    walk                  = None
                else:
                    available_files, available_directories = expand_walk_to_lists(walk)

                return walk, available_files, available_directories

            def cb_expand_success(result):
                walk, available_files, available_directories = result

                self.available_files       = available_files
                self.available_directories = available_directories

                if walk != None:
                    expand_walk_to_model(walk, self.tree_files_model, self.folder_icon, self.file_icon)
                else:
                    self.label_error.setText('<b>Error:</b> Received invalid data')
                    self.label_error.setVisible(True)

                self.tree_files.header().setSortIndicator(0, Qt.AscendingOrder)
                self.refresh_files_done()

            def cb_expand_error():
                self.label_error.setText('<b>Error:</b> Internal async error')
                self.label_error.setVisible(True)
                self.refresh_files_done()

            async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
コード例 #47
0
            def cb_read(result):
                done()

                if result.error != None:
                    if result.error.error_code != REDError.E_OPERATION_ABORTED:
                        log.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True)

                    return

                try:
                    content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    log.log(u'Error: Log file is not UTF-8 encoded', bold=True)
                    return

                log.set_content(content)
コード例 #48
0
 def toSimpleHtml(self):
     html = QString()
     black = QColor(Qt.black)
     block = self.document().begin()
     while block.isValid():
         iterator = block.begin()
         while iterator != block.end():
             fragment = iterator.fragment()
             if fragment.isValid():
                 format = fragment.charFormat()
                 family = format.fontFamily()
                 color = format.foreground().color()
                 text = Qt.escape(fragment.text())
                 if (format.verticalAlignment() ==
                     QTextCharFormat.AlignSubScript):
                     text = QString("<sub>%1</sub>").arg(text)
                 elif (format.verticalAlignment() ==
                       QTextCharFormat.AlignSuperScript):
                     text = QString("<sup>%1</sup>").arg(text)
                 if format.fontUnderline():
                     text = QString("<u>%1</u>").arg(text)
                 if format.fontItalic():
                     text = QString("<i>%1</i>").arg(text)
                 if format.fontWeight() > QFont.Normal:
                     text = QString("<b>%1</b>").arg(text)
                 if format.fontStrikeOut():
                     text = QString("<s>%1</s>").arg(text)
                 if color != black or not family.isEmpty():
                     attribs = ""
                     if color != black:
                         attribs += ' color="{0}"'.format(color.name())
                     if not family.isEmpty():
                         attribs += ' face="{0}"'.format(family)
                     text = (QString("<font%1>%2</font>")
                             .arg(attribs).arg(text))
                 html += text
             iterator += 1
         block = block.next()
     return html
コード例 #49
0
ファイル: owaxis.py プロジェクト: agiz/orange3
    def update(self, zoom_only = False):
        self.update_ticks()
        line_color = self.plot.color(OWPalette.Axis)
        text_color = self.plot.color(OWPalette.Text)
        if not self.graph_line or not self.scene():
            return
        self.line_item.setLine(self.graph_line)
        self.line_item.setPen(line_color)
        if self.title:
            self.title_item.setHtml('<b>' + self.title + '</b>')
            self.title_item.setDefaultTextColor(text_color)
        if self.title_location == AxisMiddle:
            title_p = 0.5
        elif self.title_location == AxisEnd:
            title_p = 0.95
        else:
            title_p = 0.05
        title_pos = self.graph_line.pointAt(title_p)
        v = self.graph_line.normalVector().unitVector()

        dense_text = False
        if hasattr(self, 'title_margin'):
            offset = self.title_margin
        elif self._ticks:
            if self.should_be_expanded():
                offset = 55
                dense_text = True
            else:
                offset = 35
        else:
            offset = 10

        if self.title_above:
            title_pos = title_pos + (v.p2() - v.p1())*(offset + QFontMetrics(self.title_item.font()).height())
        else:
            title_pos = title_pos - (v.p2() - v.p1())*offset
        ## TODO: Move it according to self.label_pos
        self.title_item.setVisible(self.show_title)
        self.title_item.setRotation(-self.graph_line.angle())
        c = self.title_item.mapToParent(self.title_item.boundingRect().center())
        tl = self.title_item.mapToParent(self.title_item.boundingRect().topLeft())
        self.title_item.setPos(title_pos - c + tl)

        ## Arrows
        if not zoom_only:
            if self.start_arrow_item:
                self.scene().removeItem(self.start_arrow_item)
                self.start_arrow_item = None
            if self.end_arrow_item:
                self.scene().removeItem(self.end_arrow_item)
                self.end_arrow_item = None

        if self.arrows & AxisStart:
            if not zoom_only or not self.start_arrow_item:
                self.start_arrow_item = QGraphicsPathItem(self.arrow_path, self)
            self.start_arrow_item.setPos(self.graph_line.p1())
            self.start_arrow_item.setRotation(-self.graph_line.angle() + 180)
            self.start_arrow_item.setBrush(line_color)
            self.start_arrow_item.setPen(line_color)
        if self.arrows & AxisEnd:
            if not zoom_only or not self.end_arrow_item:
                self.end_arrow_item = QGraphicsPathItem(self.arrow_path, self)
            self.end_arrow_item.setPos(self.graph_line.p2())
            self.end_arrow_item.setRotation(-self.graph_line.angle())
            self.end_arrow_item.setBrush(line_color)
            self.end_arrow_item.setPen(line_color)

        ## Labels

        n = len(self._ticks)
        resize_plot_item_list(self.label_items, n, QGraphicsTextItem, self)
        resize_plot_item_list(self.label_bg_items, n, QGraphicsRectItem, self)
        resize_plot_item_list(self.tick_items, n, QGraphicsLineItem, self)

        test_rect = QRectF(self.graph_line.p1(),  self.graph_line.p2()).normalized()
        test_rect.adjust(-1, -1, 1, 1)

        n_v = self.graph_line.normalVector().unitVector()
        if self.title_above:
            n_p = n_v.p2() - n_v.p1()
        else:
            n_p = n_v.p1() - n_v.p2()
        l_v = self.graph_line.unitVector()
        l_p = l_v.p2() - l_v.p1()
        for i in range(n):
            pos, text, size, step = self._ticks[i]
            hs = 0.5 * step
            tick_pos = self.map_to_graph( pos )
            if not test_rect.contains(tick_pos):
                self.tick_items[i].setVisible(False)
                self.label_items[i].setVisible(False)
                continue
            item = self.label_items[i]
            item.setVisible(True)
            if not zoom_only:
                if self.id in XAxes or getattr(self, 'is_horizontal', False):
                    item.setHtml( '<center>' + Qt.escape(text.strip()) + '</center>')
                else:
                    item.setHtml(Qt.escape(text.strip()))

            item.setTextWidth(-1)
            text_angle = 0
            if dense_text:
                w = min(item.boundingRect().width(), self.max_text_width)
                item.setTextWidth(w)
                if self.title_above:
                    label_pos = tick_pos + n_p * (w + self.text_margin) + l_p * item.boundingRect().height()/2
                else:
                    label_pos = tick_pos + n_p * self.text_margin + l_p * item.boundingRect().height()/2
                text_angle = -90 if self.title_above else 90
            else:
                w = min(item.boundingRect().width(), QLineF(self.map_to_graph(pos - hs), self.map_to_graph(pos + hs) ).length())
                label_pos = tick_pos + n_p * self.text_margin - l_p * w/2
                item.setTextWidth(w)

            if not self.always_horizontal_text:
                if self.title_above:
                    item.setRotation(-self.graph_line.angle() - text_angle)
                else:
                    item.setRotation(self.graph_line.angle() - text_angle)

            item.setPos(label_pos)
            item.setDefaultTextColor(text_color)

            self.label_bg_items[i].setRect(item.boundingRect())
            self.label_bg_items[i].setPen(QPen(Qt.NoPen))
            self.label_bg_items[i].setBrush(self.plot.color(OWPalette.Canvas))

            item = self.tick_items[i]
            item.setVisible(True)
            tick_line = QLineF(v)
            tick_line.translate(-tick_line.p1())
            tick_line.setLength(size)
            if self.title_above:
                tick_line.setAngle(tick_line.angle() + 180)
            item.setLine( tick_line )
            item.setPen(line_color)
            item.setPos(self.map_to_graph(pos))
コード例 #50
0
        def cb_program_logs_list(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' + Qt.escape(message))
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            try:
                # FIXME: do decompress in an async_call
                program_logs_list = json.loads(zlib.decompress(buffer(result.stdout)).decode('utf-8'))
            except:
                program_logs_list = None

            if program_logs_list == None or not isinstance(program_logs_list, dict):
                self.label_error.setText('<b>Error:</b> Received invalid data')
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            self.label_error.setVisible(False)

            def create_file_size_item(size):
                item = QStandardItem(get_file_display_size(size))
                item.setData(size, USER_ROLE_SIZE)

                return item

            def update_file_size_item(item, additional_size):
                current_size = item.data(USER_ROLE_SIZE)
                new_size     = current_size + additional_size

                item.setText(get_file_display_size(new_size))
                item.setData(new_size, USER_ROLE_SIZE)

            continuous_row = None
            date_rows      = {}
            time_rows      = {}

            for file_name, file_size in program_logs_list.iteritems():
                QApplication.processEvents()

                file_name_parts = file_name.split('_')

                if file_name_parts[0] == "continuous":
                    if len(file_name_parts) != 2:
                        continue

                    if continuous_row == None:
                        continuous_item = QStandardItem("Continuous")
                        continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE)

                        continuous_row = [continuous_item, create_file_size_item(0)]

                        self.tree_logs_model.appendRow(continuous_row)

                    log_item = QStandardItem(file_name_parts[1])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE)

                    continuous_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(continuous_row[1], file_size)
                else:
                    if len(file_name_parts) != 3:
                        continue

                    try:
                        timestamp = int(file_name_parts[1].split('+')[0]) / 1000000
                    except ValueError:
                        continue

                    date      = QDateTime.fromTime_t(timestamp).toString('yyyy-MM-dd')
                    time      = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss')
                    date_time = date + 'T' + time

                    if date in date_rows:
                        date_row = date_rows[date]
                    else:
                        date_item = QStandardItem(date)
                        date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE)

                        date_row        = [date_item, create_file_size_item(0)]
                        date_rows[date] = date_row

                        self.tree_logs_model.appendRow(date_row)

                    if date_time in time_rows:
                        time_row = time_rows[date_time]
                    else:
                        time_item = QStandardItem(time)
                        time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE)

                        time_row             = [time_item, create_file_size_item(0)]
                        time_rows[date_time] = time_row

                        date_row[0].appendRow(time_row)

                    log_item = QStandardItem(file_name_parts[2])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE)

                    time_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(time_row[1], file_size)
                    update_file_size_item(date_row[1], file_size)

            self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder)
            self.refresh_logs_done()
コード例 #51
0
    def start_conflict_resolution(self):
        self.log(u'...target file {0} already exists'.format(self.upload.target))

        if self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_REPLACE:
            self.log(u'...replacing {0}'.format(self.upload.target))
            self.continue_upload_file(True)
        elif self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_SKIP:
            self.log('...skipped')
            self.upload_next_file()
        else:
            self.progress_file.setVisible(False)

            try:
                target_file = REDFile(self.wizard().session).open(self.target_path, REDFile.FLAG_READ_ONLY, 0, 1000, 1000) # FIXME: async_call

                self.label_existing_stats.setText('{0}, last modified on {1}'
                                                  .format(get_file_display_size(target_file.length),
                                                          timestamp_to_date_at_time(int(target_file.modification_time))))

                target_file.release()
            except (Error, REDError) as e:
                self.label_existing_stats.setText(u'<b>Error</b>: Could not open target file: {0}', Qt.escape(unicode(e)))

            self.label_new_stats.setText('{0}, last modified on {1}'
                                         .format(self.chunked_uploader.source_display_size,
                                                 timestamp_to_date_at_time(int(self.chunked_uploader.source_stat.st_mtime))))

            self.label_replace_help.setText(self.replace_help_template.replace('<FILE>', Qt.escape(self.upload.target)))
            self.check_rename_new_file.setChecked(self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_RENAME)
            self.edit_new_name.setText('') # force a new-name check
            self.edit_new_name.setText(posixpath.split(self.upload.target)[1])

            self.conflict_resolution_in_progress = True
            self.update_ui_state()
コード例 #52
0
    def initializePage(self):
        self.set_formatted_sub_title(u'The complete configuration of the {language} program [{name}].')

        language              = self.get_field('language')
        language_display_name = Constants.language_display_names[language]
        language_api_name     = Constants.language_api_names[language]

        # general information
        html  = u'<b>General Information</b><br/>'
        html += u'Name: {0}<br/>'.format(Qt.escape(self.get_field('name')))
        html += u'Identifier: {0}<br/>'.format(Qt.escape(self.get_field('identifier')))
        html += u'Language: {0}<br/>'.format(Qt.escape(language_display_name))
        html += u'Description: {0}<br/>'.format(Qt.escape(self.get_field('description')))
        html += u'<br/>'

        # files
        html += u'<b>Files</b>'

        items = self.wizard().page(Constants.PAGE_FILES).get_items()

        if len(items) == 0:
            html += u' (none)'

        html += u'<br/>'

        for item in items:
            html += u'{0}<br/>'.format(Qt.escape(item))

        html += u'<br/>'

        # language specific configuration
        html += u'<b>{0} Configuration</b><br/>'.format(Qt.escape(language_display_name))
        html += self.wizard().page(Constants.get_language_page(language_api_name)).get_html_summary()
        html += u'<br/>'

        if self.wizard().hasVisitedPage(Constants.PAGE_ARGUMENTS):
            # arguments
            html += u'<b>Arguments</b>'

            arguments = self.wizard().page(Constants.PAGE_ARGUMENTS).get_arguments()

            if len(arguments) == 0:
                html += u' (none)'

            html += u'<br/>'

            for argument in arguments:
                html += u'{0}<br/>'.format(Qt.escape(argument))

            html += u'<br/>'

            # environment
            html += u'<b>Environment</b>'

            environment = self.wizard().page(Constants.PAGE_ARGUMENTS).get_environment()

            if len(environment) == 0:
                html += u' (empty)'

            html += u'<br/>'

            for variable in environment:
                html += u'{0}<br/>'.format(Qt.escape(variable))

            html += u'<br/>'

        # stdio redirection
        if self.wizard().hasVisitedPage(Constants.PAGE_STDIO):
            html += u'<b>Stdio Redirection</b><br/>'

            stdin_redirection  = self.get_field('stdin_redirection')
            stdout_redirection = self.get_field('stdout_redirection')
            stderr_redirection = self.get_field('stderr_redirection')

            if stdin_redirection == Constants.STDIN_REDIRECTION_FILE:
                html += u'Standard Input: {0}<br/>'.format(self.get_field('stdin_file'))
            else:
                html += u'Standard Input: {0}<br/>'.format(Constants.get_stdin_redirection_display_name(stdin_redirection))

            if stdout_redirection == Constants.STDOUT_REDIRECTION_FILE:
                html += u'Standard Output: {0}<br/>'.format(self.get_field('stdout_file'))
            else:
                html += u'Standard Output: {0}<br/>'.format(Constants.get_stdout_redirection_display_name(stdout_redirection))

            if stderr_redirection == Constants.STDERR_REDIRECTION_FILE:
                html += u'Standard Error: {0}<br/>'.format(self.get_field('stderr_file'))
            else:
                html += u'Standard Error: {0}<br/>'.format(Constants.get_stderr_redirection_display_name(stderr_redirection))

            html += u'<br/>'

        # schedule
        if self.wizard().hasVisitedPage(Constants.PAGE_SCHEDULE):
            html += u'<b>Schedule</b><br/>'

            start_mode = self.get_field('start_mode')

            if start_mode == Constants.START_MODE_ONCE:
                html += u'Mode: Once After Upload<br/>'
            else:
                html += u'Mode: {0}<br/>'.format(Constants.get_start_mode_display_name(start_mode))

            if start_mode != Constants.START_MODE_NEVER and start_mode != Constants.START_MODE_ONCE:
                if self.get_field('continue_after_error'):
                    html += u'Continue After Error: Enabled<br/>'
                else:
                    html += u'Continue After Error: Disabled<br/>'

            if start_mode == Constants.START_MODE_INTERVAL:
                html += u'Interval: {0} seconds<br/>'.format(self.get_field('start_interval'))
            elif start_mode == Constants.START_MODE_CRON:
                html += u'Fields: {0}<br/>'.format(self.get_field('start_fields'))

        self.text_summary.setHtml(html)
        self.update_ui_state()
コード例 #53
0
    def start_conflict_resolution(self):
        self.log(u'...target file {0} already exists'.format(self.target_path))

        if self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_REPLACE:
            self.log(u'...replacing {0}'.format(self.download.target))
            self.continue_download_file(True)
        elif self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_SKIP:
            self.log('...skipped')
            self.download_next_file()
        else:
            self.progress_file.setVisible(False)

            try:
                target_stat = os.stat(self.target_path)

                self.label_existing_stats.setText('{0}, last modified on {1}'
                                                  .format(get_file_display_size(target_stat.st_size),
                                                          timestamp_to_date_at_time(int(target_stat.st_mtime))))
            except Exception as e:
                self.label_existing_stats.setText(u'<b>Error</b>: Could not get informarion for target file: {0}', Qt.escape(unicode(e)))

            self.label_new_stats.setText('{0}, last modified on {1}'
                                         .format(self.chunked_downloader.source_display_size,
                                                 timestamp_to_date_at_time(int(self.chunked_downloader.source_file.modification_time))))

            self.label_replace_help.setText(self.replace_help_template.replace('<FILE>', Qt.escape(self.download.target)))
            self.check_rename_new_file.setChecked(self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_RENAME)
            self.edit_new_name.setText('') # force a new-name check
            self.edit_new_name.setText(os.path.split(self.download.target)[1])

            self.conflict_resolution_in_progress = True
            self.update_ui_state()
コード例 #54
0
 def log_error(self, message):
     self.edit_errors.show()
     self.edit_errors.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))