Example #1
0
 def append(self, text):
     """Append line to the end
     """
     cursor = QTextCursor(self._doc)
     cursor.movePosition(QTextCursor.End)
     cursor.insertBlock()
     cursor.insertText(text)
Example #2
0
 def append(self, text):
     """Append line to the end
     """
     cursor = QTextCursor(self._doc)
     cursor.movePosition(QTextCursor.End)
     cursor.insertBlock()
     cursor.insertText(text)
Example #3
0
 def _format_suggestion(self, index):
     suggestion = index.data(Qt.DisplayRole)
     self._doc.clear()
     cursor = QTextCursor(self._doc)
     cursor.setCharFormat(self._translation_char_format)
     cursor.insertText(escape_translation(suggestion.text) + ':')
     if not suggestion.steno_list:
         cursor.insertText(' ' + NO_SUGGESTIONS_STRING)
         return
     for strokes_list in suggestion.steno_list[:MAX_SUGGESTIONS_COUNT]:
         cursor.insertBlock()
         cursor.setCharFormat(self._strokes_char_format)
         cursor.insertText('   ' + '/'.join(strokes_list))
Example #4
0
    def insert(self, index, text):
        """Insert line to the document
        """
        if index < 0 or index > self._doc.blockCount():
            raise IndexError('Invalid block index', index)

        if index == 0:  # first
            cursor = QTextCursor(self._doc.firstBlock())
            cursor.insertText(text)
            cursor.insertBlock()
        elif index != self._doc.blockCount():  # not the last
            cursor = QTextCursor(self._doc.findBlockByNumber(index).previous())
            cursor.movePosition(QTextCursor.EndOfBlock)
            cursor.insertBlock()
            cursor.insertText(text)
        else:  # last append to the end
            self.append(text)
Example #5
0
    def insert(self, index, text):
        """Insert line to the document
        """
        if index < 0 or index > self._doc.blockCount():
            raise IndexError('Invalid block index', index)

        if index == 0:  # first
            cursor = QTextCursor(self._doc.firstBlock())
            cursor.insertText(text)
            cursor.insertBlock()
        elif index != self._doc.blockCount():  # not the last
            cursor = QTextCursor(self._doc.findBlockByNumber(index).previous())
            cursor.movePosition(QTextCursor.EndOfBlock)
            cursor.insertBlock()
            cursor.insertText(text)
        else:  # last append to the end
            self.append(text)
    def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName,
                  VManager):
        ''' Create PDF QgsTask '''
        QCoreApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        font_normal = QFont("Helvetica", 10, QFont.Normal)
        font_bold = QFont("Helvetica", 12, QFont.Bold)

        printer = QPrinter(QPrinter.HighResolution)
        printer.setOrientation(QPrinter.Portrait)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setFullPage(True)
        printer.setPaperSize(QPrinter.A4)
        printer.setOutputFileName(out)
        printer.setPageMargins(15, 15, 15, 15, QPrinter.Point)
        printer.setColorMode(QPrinter.Color)

        document = QTextDocument()
        document.setDefaultFont(font_normal)

        cursor = QTextCursor(document)
        cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
        cursor.insertHtml("""
            <p style='text-align: center;'>
            <img style='display: block; margin-left: auto; margin-right: auto;' 
            src=\':/imgFMV/images/header_logo.png\' width='200' height='25' />
            </p>
            <p style='text-align: center;'>
            <strong>Video :&nbsp;</strong>%s<strong>
            </p>
            <p style='text-align: center;'>
            <strong>TimeStamp :&nbsp;</strong>%s</p><br><br>
            """ % (fileName, timestamp))

        tableFormat = QTextTableFormat()
        tableFormat.setHeaderRowCount(1)
        tableFormat.setBorderBrush(QBrush(Qt.black))
        tableFormat.setAlignment(Qt.AlignHCenter)
        tableFormat.setCellPadding(2)
        tableFormat.setCellSpacing(2)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignCenter)
        cursor.insertBlock(centerFormat)

        textTable = cursor.insertTable(rows + 1, columns, tableFormat)

        tableHeaderFormat = QTextCharFormat()
        tableHeaderFormat.setFont(font_bold)
        tableHeaderFormat.setBackground(QColor("#67b03a"))
        tableHeaderFormat.setForeground(Qt.white)

        alternate_background = QTextCharFormat()
        alternate_background.setBackground(QColor("#DDE9ED"))

        for column in range(columns):
            cell = textTable.cellAt(0, column)
            cell.setFormat(tableHeaderFormat)
            cellCursor = cell.firstCursorPosition()
            cellCursor.insertText(VManager.horizontalHeaderItem(column).text())

        row = 0
        for key in sorted(data.keys()):
            cell0 = textTable.cellAt(row + 1, 0)
            cell1 = textTable.cellAt(row + 1, 1)
            cell2 = textTable.cellAt(row + 1, 2)
            if (row + 1) % 2 == 0:
                cell0.setFormat(alternate_background)
                cell1.setFormat(alternate_background)
                cell2.setFormat(alternate_background)
            cellCursor0 = cell0.firstCursorPosition()
            cellCursor0.insertText(str(key))
            cellCursor1 = cell1.firstCursorPosition()
            cellCursor1.insertText(str(data[key][0]))
            cellCursor2 = cell2.firstCursorPosition()
            cellCursor2.insertText(str(data[key][1]))
            row += 1

        cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)

        cursor.insertHtml("""
        <br><p style='text-align: center;'><strong>Current Frame</strong></p><br>
        """)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignHCenter)
        cursor.insertBlock(centerFormat)
        cursor.insertImage(frame.scaledToWidth(500))
        QCoreApplication.processEvents()
        document.print_(printer)
        QCoreApplication.processEvents()
Example #7
0
    def printViaQCursor(self):
        dialog = QPrintDialog(self.printer, self)
        if not dialog.exec_():
            return
        logo = QPixmap(":/logo.png")
        headFormat = QTextBlockFormat()
        headFormat.setAlignment(Qt.AlignLeft)
        headFormat.setTextIndent(self.printer.pageRect().width() -
                                 logo.width() - 216)
        bodyFormat = QTextBlockFormat()
        bodyFormat.setAlignment(Qt.AlignJustify)
        lastParaBodyFormat = QTextBlockFormat(bodyFormat)
        lastParaBodyFormat.setPageBreakPolicy(
            QTextFormat.PageBreak_AlwaysAfter)
        rightBodyFormat = QTextBlockFormat()
        rightBodyFormat.setAlignment(Qt.AlignRight)
        headCharFormat = QTextCharFormat()
        headCharFormat.setFont(QFont("Helvetica", 10))
        bodyCharFormat = QTextCharFormat()
        bodyCharFormat.setFont(QFont("Times", 11))
        redBodyCharFormat = QTextCharFormat(bodyCharFormat)
        redBodyCharFormat.setForeground(Qt.red)
        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(2)

        document = QTextDocument()
        cursor = QTextCursor(document)
        mainFrame = cursor.currentFrame()
        page = 1
        for statement in self.statements:
            cursor.insertBlock(headFormat, headCharFormat)
            cursor.insertImage(":/logo.png")
            for text in ("Greasy Hands Ltd.",
                         "New Lombard Street", "London", "WC13 4PX",
                         QDate.currentDate().toString(DATE_FORMAT)):
                cursor.insertBlock(headFormat, headCharFormat)
                cursor.insertText(text)
            for line in statement.address.split(", "):
                cursor.insertBlock(bodyFormat, bodyCharFormat)
                cursor.insertText(line)
            cursor.insertBlock(bodyFormat)
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Dear {0},".format(statement.contact))
            cursor.insertBlock(bodyFormat)
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            balance = statement.balance()
            cursor.insertText(
                "The balance of your account is $ {0:,.2f}.".format(
                    float(balance)))
            if balance < 0:
                cursor.insertBlock(bodyFormat, redBodyCharFormat)
                cursor.insertText("Please remit the amount owing "
                                  "immediately.")
            else:
                cursor.insertBlock(bodyFormat, bodyCharFormat)
                cursor.insertText("We are delighted to have done "
                                  "business with you.")
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Transactions:")
            table = cursor.insertTable(len(statement.transactions), 3,
                                       tableFormat)
            row = 0
            for date, amount in statement.transactions:
                cellCursor = table.cellAt(row, 0).firstCursorPosition()
                cellCursor.setBlockFormat(rightBodyFormat)
                cellCursor.insertText(date.toString(DATE_FORMAT),
                                      bodyCharFormat)
                cellCursor = table.cellAt(row, 1).firstCursorPosition()
                if amount > 0:
                    cellCursor.insertText("Credit", bodyCharFormat)
                else:
                    cellCursor.insertText("Debit", bodyCharFormat)
                cellCursor = table.cellAt(row, 2).firstCursorPosition()
                cellCursor.setBlockFormat(rightBodyFormat)
                format = bodyCharFormat
                if amount < 0:
                    format = redBodyCharFormat
                cellCursor.insertText("$ {0:,.2f}".format(float(amount)),
                                      format)
                row += 1
            cursor.setPosition(mainFrame.lastPosition())
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("We hope to continue doing business "
                              "with you,")
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Yours sincerely")
            cursor.insertBlock(bodyFormat)
            if page == len(self.statements):
                cursor.insertBlock(bodyFormat, bodyCharFormat)
            else:
                cursor.insertBlock(lastParaBodyFormat, bodyCharFormat)
            cursor.insertText("K. Longrey, Manager")
            page += 1
        document.print_(self.printer)
Example #8
0
class TextSectionEditor(QTextDocument):
    def __init__(self,
                 sectionId: str,
                 content="",
                 pos=0,
                 selectionStart=0,
                 selectionEnd=0):
        super().__init__()
        self.dtb = DTB()
        self.sectionId = sectionId
        self.setDefaultStyleSheet(CSS)
        self.setHtml(content)
        self.s_start = selectionStart
        self.s_end = selectionEnd

        self.cur = QTextCursor(self)
        self.cur.setPosition(pos)
        self.result = {
            "text": "",
            "cursorPosition": self.pos,
            "eventAccepted": False
        }
        self.pending = False

    @property
    def len(self):
        return self.characterCount()

    @property
    def s_len(self):
        return abs(self.s_end - self.s_start)

    @property
    def pos(self):
        return self.cur.position()

    def onChange(self):

        self._update_ddb()
        self.setResponse(True)
        return self.result

    def onLoad(self):
        item = self.dtb.getDB("Section", self.sectionId)
        self.setHtml(item["text"])
        self.setResponse(True, cur=self.len)
        return self.result

    def onMenu(self, style={}, **kwargs):
        backup = [self.pos, self.s_start, self.s_end]

        for k, v in style.items():
            # un peut répétition mais uniquement sur des if alors ...
            if k == "fgColor":
                self._set_fg_color(v)
            elif k == "underline":  # pragma: no branch
                self._set_underline(style["underline"])

            self.cur.setPosition(backup[0])
            self.s_start = backup[1]
            self.s_end = backup[2]

        if self.pending:
            # else:
            self._update_ddb()
        else:
            self.setResponse(False)
        return self.result

    def onKey(self, event):
        # on met en premier ceux à qui il faut passer l'event
        if event["key"] == Qt.Key_Return:
            self.do_key_return(event)

        elif event["modifiers"] == Qt.ControlModifier:
            self.do_control_modifier(event)

        else:
            self.setResponse(False)

        if self.pending:
            self._update_ddb()
        return self.result

    def do_control_modifier(self, event):

        if event == KeyW.KEY_1:
            self.do_key_1()

        elif event == KeyW.KEY_2:
            self.do_key_2()

        elif event == KeyW.KEY_3:
            self.do_key_3()

        elif event == KeyW.KEY_4:
            self.do_key_4()

        elif event["key"] == Qt.Key_U:  # pragma: no branch
            self.do_key_u()

    def do_key_1(self):
        self._set_fg_color(BLACK)

    def do_key_2(self):
        self._set_fg_color(BLUE)

    def do_key_3(self):
        self._set_fg_color(GREEN)

    def do_key_4(self):
        self._set_fg_color(RED)

    def do_key_return(self, event):
        block = self.findBlock(self.pos)
        if event["modifiers"] == Qt.ControlModifier:
            self._appendEmptyBlock()
        elif event["modifiers"] == Qt.ShiftModifier:
            self._insertEmptyBlock()
        elif block.blockFormat().headingLevel():
            self._appendEmptyBlock()
        else:
            if self._headerAutoFormat():
                return
            else:
                self.setResponse(False)

    def do_key_u(self):
        self._set_underline("toggle")

    def setResponse(self, accepted, text=None, cur=None):
        self.result["text"] = text or self.toHtml()
        self.result["cursorPosition"] = cur or self.cur.position()
        self.result["eventAccepted"] = accepted

    def _appendEmptyBlock(self,
                          section="p",
                          pre_move=QTextCursor.EndOfBlock,
                          set_response=True):
        self.cur.movePosition(pre_move)
        self.cur.insertBlock(blockFormat[section], blockCharFormat[section])
        self.cur.insertFragment(QTextDocumentFragment.fromPlainText(""))
        self.pending = True
        if set_response:
            self.setResponse(True)

    def _insertEmptyBlock(self,
                          section="p",
                          pre_move=QTextCursor.StartOfBlock,
                          set_response=True):
        old = self.cur.blockFormat().headingLevel()
        self._appendEmptyBlock(pre_move=pre_move, set_response=False)
        self._set_block_style(old)
        self.cur.movePosition(QTextCursor.PreviousBlock)
        self._set_block_style(section)
        self.pending = True
        if set_response:  # pragma: no branch
            self.setResponse(True)

    def _headerAutoFormat(self):

        # on check les expressions régulières suivantes:
        #   #, ##, ###, ####, #####
        line = self.cur.block().text()
        matched = RE_AUTOPARAGRAPH_DEBUT.search(line)
        matched_at_start = False
        if not matched:
            matched = RE_AUTOPARAGRAPH_FIN.search(line)
            if not matched:
                return False
        else:
            matched_at_start = True

        # strip les # et applique les styles par défault
        level = len(matched.groups()[0])
        if matched_at_start:
            text = self.cur.block().text()[level + 1:]
        else:
            text = self.cur.block().text()[:-(level + 1)]

        self.cur.beginEditBlock()
        self.cur.select(QTextCursor.LineUnderCursor)
        self.cur.setCharFormat(blockCharFormat[level])
        self.cur.insertText(text)
        self.cur.setBlockFormat(blockFormat[level])
        self.cur.endEditBlock()

        self._appendEmptyBlock()
        self.pending = True
        self.setResponse(True)
        return True

    @contextmanager
    def _merge_char_format(self):
        self._select_word_or_selection()
        f: QTextCharFormat = QTextCharFormat()
        yield f
        self.cur.mergeCharFormat(f)
        self.pending = True
        self.setResponse(True, cur=max(self.pos, self.s_start, self.s_end))

    def _select_word_or_selection(self):
        if self.s_start < self.pos:
            self.cur.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor,
                                  self.s_len)
        elif self.s_end > self.pos:
            self.cur.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor,
                                  self.s_len)
        else:
            self.cur.select(QTextCursor.WordUnderCursor)

    def _set_block_style(self, level):
        self.cur.setBlockFormat(blockFormat[level])
        self.cur.setBlockCharFormat(blockCharFormat[level])

    def _set_fg_color(self, color):
        with self._merge_char_format() as f:
            f.setForeground(QBrush(QColor(color)))

    def _set_underline(self, value):
        with self._merge_char_format() as f:
            if value == "toggle":
                value = not self.cur.charFormat().fontUnderline()
            f.setFontUnderline(value)

    def _update_ddb(self):
        new_body = TextSectionFormatter(self.toHtml()).build_body()
        self.dtb.setDB("Section", self.sectionId, {"text": new_body})
        return new_body