Example #1
0
    def highlightHorizontalLine(self, text, cursor, bf, strt):
        found = False
        for mo in re.finditer(self.MARKDOWN_KEYS_REGEX['HR'],text):
            prevBlock = self.currentBlock().previous()
            prevCursor = QTextCursor(prevBlock)
            prev = prevBlock.text()
            prevAscii = str(prev.replace(u'\u2029','\n'))
            if prevAscii.strip():
                #print "Its a header"
                prevCursor.select(QTextCursor.LineUnderCursor)
                #prevCursor.setCharFormat(self.MARKDOWN_KWS_FORMAT['Header'])
                formatRange = QTextLayout.FormatRange()
                formatRange.format = self.MARKDOWN_KWS_FORMAT['Header']
                formatRange.length = prevCursor.block().length()
                formatRange.start = 0
                prevCursor.block().layout().setAdditionalFormats([formatRange])
            self.setFormat(mo.start()+strt, mo.end() - mo.start(), self.MARKDOWN_KWS_FORMAT['HR'])

        for mo in re.finditer(self.MARKDOWN_KEYS_REGEX['eHR'],text):
            prevBlock = self.currentBlock().previous()
            prevCursor = QTextCursor(prevBlock)
            prev = prevBlock.text()
            prevAscii = str(prev.replace(u'\u2029','\n'))
            if prevAscii.strip():
                #print "Its a header"
                prevCursor.select(QTextCursor.LineUnderCursor)
                #prevCursor.setCharFormat(self.MARKDOWN_KWS_FORMAT['Header'])
                formatRange = QTextLayout.FormatRange()
                formatRange.format = self.MARKDOWN_KWS_FORMAT['Header']
                formatRange.length = prevCursor.block().length()
                formatRange.start = 0
                prevCursor.block().layout().setAdditionalFormats([formatRange])
            self.setFormat(mo.start()+strt, mo.end() - mo.start(), self.MARKDOWN_KWS_FORMAT['HR'])
        return found
Example #2
0
    def write(self, data):
        """
            This uses insertPlainText (maybe in a later version HTML, so that we can change
            the colour of the output) and scrolls down to the bottom of the field. The problem
            with append() is that it puts the inserted text in its own paragraph, which is not
            good if we do not want the linefeed.
        :param data: a unicode string
        :return: nothing
        """
        # move cursor to end (in case user clicked somewhere else in the window)
        cursor = QTextCursor(self.document())
        cursor.movePosition(QTextCursor.End)
        self.setTextCursor(cursor)

        while True:  # find all carriage returns
            i = data.find('\r')
            if i >= 0:  # means we have to deal with a carriage return
                self.insertPlainText(QString(data[0:i]))
                cursor.select(QTextCursor.LineUnderCursor)
                cursor.removeSelectedText()
                data = data[i + 1:]
            else:
                break

        # insert remaining text
        self.insertPlainText(data)
        sb = self.verticalScrollBar()
        sb.setValue(sb.maximum())
Example #3
0
    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)
Example #4
0
    def highlight_ascii(self) -> None:
        """Bidirectional highlighting from ascii"""

        # Create and get cursors for getting and setting selections.
        highlight_cursor = QTextCursor(self.main_text_area.document())
        cursor = self.ascii_text_area.textCursor()

        # Clear any current selections and reset text color.
        highlight_cursor.select(QTextCursor.Document)
        highlight_cursor.setCharFormat(QTextCharFormat())
        highlight_cursor.clearSelection()

        # Information about where selections and rows start.
        selected_text = cursor.selectedText()  # The actual text selected.
        selection_start = cursor.selectionStart()

        ascii_text = self.ascii_text_area.toPlainText().replace('\n', '')
        main_start = self.__get_valuable_positions_length(ascii_text[:selection_start])
        main_start = self.__positive_compensation(main_start)

        total_bytes = self.__get_valuable_positions_length(selected_text)  # get all valuable positions
        # \n and word length compensation
        total_bytes = self.__positive_compensation(total_bytes)
        selection_end = main_start + total_bytes

        # Select text and highlight it.
        highlight_cursor.setPosition(main_start, QTextCursor.MoveAnchor)
        highlight_cursor.setPosition(selection_end, QTextCursor.KeepAnchor)

        highlight = QTextCharFormat()
        highlight.setBackground(Qt.red)
        highlight_cursor.setCharFormat(highlight)
        highlight_cursor.clearSelection()
Example #5
0
    def load(self, url=None, encoding=None, keepUndo=False):
        """Load the specified or current url (if None was specified).

        Currently only local files are supported. An IOError is raised
        when trying to load a nonlocal URL.

        If loading succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).

        If keepUndo is True, the loading can be undone (with Ctrl-Z).

        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        text = self.load_data(u, encoding or self._encoding)
        if keepUndo:
            c = QTextCursor(self)
            c.select(QTextCursor.Document)
            c.insertText(text)
        else:
            self.setPlainText(text)
        self.setModified(False)
        if not url.isEmpty():
            self.setUrl(url)
Example #6
0
    def fixUpLine(self, line: int, newText: str, data: int):
        """ The receiver of the 'fixupText' signal should invoke this method
        to replace the line with the cleaned text and the model's
        matching row """

        block = self.document().findBlockByLineNumber(line)
        if block.isValid():
            if block.userData() is None:
                block.setUserData(self._UserData(data))
            else:
                block.userData().row = data

            text = newText.strip()
            if not text:
                block.setUserState(self._State.Blank)
            elif data < 0:
                block.setUserState(self._State.Error)
            else:
                block.setUserState(self._State.Fixup)

            cursor = QTextCursor(block)
            cursor.beginEditBlock()
            cursor.movePosition(QTextCursor.StartOfLine)
            cursor.select(QTextCursor.LineUnderCursor)
            cursor.removeSelectedText()
            cursor.insertText(text)
            cursor.endEditBlock()
Example #7
0
    def load(self, url=None, encoding=None, keepUndo=False):
        """Load the specified or current url (if None was specified).

        Currently only local files are supported. An IOError is raised
        when trying to load a nonlocal URL.

        If loading succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).

        If keepUndo is True, the loading can be undone (with Ctrl-Z).

        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        text = self.load_data(u, encoding or self._encoding)
        if keepUndo:
            c = QTextCursor(self)
            c.select(QTextCursor.Document)
            c.insertText(text)
        else:
            self.setPlainText(text)
        self.setModified(False)
        if not url.isEmpty():
            self.setUrl(url)
Example #8
0
    def add_debug_message(self, message):
        self.text_debug.append(message)

        while self.text_debug.document().blockCount() > 1000:
            cursor = QTextCursor(self.text_debug.document().begin())
            cursor.select(QTextCursor.BlockUnderCursor)
            cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
            cursor.removeSelectedText()

        if self.checkbox_debug_auto_scroll.isChecked():
            self.text_debug.verticalScrollBar().setValue(self.text_debug.verticalScrollBar().maximum())
Example #9
0
    def add_debug_message(self, message):
        self.text_debug.append(message)

        while self.text_debug.document().blockCount() > 1000:
            cursor = QTextCursor(self.text_debug.document().begin())
            cursor.select(QTextCursor.BlockUnderCursor)
            cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
            cursor.removeSelectedText()

        if self.checkbox_debug_auto_scroll.isChecked():
            self.text_debug.verticalScrollBar().setValue(self.text_debug.verticalScrollBar().maximum())
    def update_minimap_doc(self, position, charsRemoved, charsAdded):

        def select_blocks(first_block,  last_block):
            first_block_pos = first_block.position()
            doc_cursor.setPosition(first_block_pos)
            last_block_pos = last_block.position()
            doc_cursor.setPosition(last_block_pos,  QTextCursor.KeepAnchor)
            doc_cursor.movePosition(
                QTextCursor.EndOfBlock,  QTextCursor.KeepAnchor)
            print("selected text :",  doc_cursor.selectedText())
            return doc_cursor.selectedText()

        doc_cursor = QTextCursor(self._doc)
        minimap_cursor = QTextCursor(self._minimap_doc)

        # IF one same block is modified
        if self._minimap_doc.blockCount() == self._doc.blockCount():
            doc_cursor.setPosition(position)
            doc_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.setPosition(position)
            minimap_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.insertFragment(doc_cursor.selection())
        # TODO: if the doc is modified on more than one block but resulting in
        # the same count of blocks (right now only the first block would be
        # updated)
        else:
            # ELSE
            doc_cursor.select(QTextCursor.Document)
            minimap_cursor.select(QTextCursor.Document)
            minimap_cursor.insertFragment(doc_cursor.selection())
Example #11
0
    def update_minimap_doc(self, position, charsRemoved, charsAdded):
        def select_blocks(first_block, last_block):
            first_block_pos = first_block.position()
            doc_cursor.setPosition(first_block_pos)
            last_block_pos = last_block.position()
            doc_cursor.setPosition(last_block_pos, QTextCursor.KeepAnchor)
            doc_cursor.movePosition(QTextCursor.EndOfBlock,
                                    QTextCursor.KeepAnchor)
            print("selected text :", doc_cursor.selectedText())
            return doc_cursor.selectedText()

        doc_cursor = QTextCursor(self._doc)
        minimap_cursor = QTextCursor(self._minimap_doc)

        # IF one same block is modified
        if self._minimap_doc.blockCount() == self._doc.blockCount():
            doc_cursor.setPosition(position)
            doc_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.setPosition(position)
            minimap_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.insertFragment(doc_cursor.selection())
        # TODO: if the doc is modified on more than one block but resulting in
        # the same count of blocks (right now only the first block would be
        # updated)
        else:
            # ELSE
            doc_cursor.select(QTextCursor.Document)
            minimap_cursor.select(QTextCursor.Document)
            minimap_cursor.insertFragment(doc_cursor.selection())
    def highlightMain(self):
        # Create and get cursors for getting and setting selections.
        highlightCursor = QTextCursor(self.asciiTextArea.document())
        # asciitextArea의 처음을 가르치는 커서를 구성
        cursor = self.mainTextArea.textCursor()
        # 커서의 위치의 사본을 따서 복사 함
        # Clear any current selections and reset text color.
        highlightCursor.select(QTextCursor.Document)
        highlightCursor.setCharFormat(QTextCharFormat())
        highlightCursor.clearSelection()

        # Information about where selections and rows start.
        selectedText = cursor.selectedText()  # The actual text selected.
        selectionStart = cursor.selectionStart()
        selectionEnd = cursor.selectionEnd()

        mainText = self.mainTextArea.toPlainText().replace('\n', 'A')
        #mainText = self.mainTextArea.toPlainText()

        totalBytes = 0

        for char in mainText[selectionStart:selectionEnd]:
            if char is not ' ':
                totalBytes += len(char)

        asciiStart = 0

        for char in mainText[:selectionStart]:
            if char is not ' ':
                asciiStart += len(char)

        totalBytes = round(totalBytes / self.byteWidth)
        asciiStart = round(asciiStart / self.byteWidth)
        asciiEnd = asciiStart + totalBytes

        asciiText = self.asciiTextArea.toPlainText()

        # Select text and highlight it.
        highlightCursor.setPosition(asciiStart, QTextCursor.MoveAnchor)
        highlightCursor.setPosition(asciiEnd, QTextCursor.KeepAnchor)

        highlight = QTextCharFormat()
        highlight.setBackground(Qt.darkCyan)
        highlightCursor.setCharFormat(highlight)
        highlightCursor.clearSelection()
Example #13
0
 def start_complete_process(self, event: QtGui.QKeyEvent,
                            tc: QtGui.QTextCursor):
     if (event.text().isalnum() and
             not self.document().characterAt(tc.position() + 1).isalnum()):
         tc.movePosition(QtGui.QTextCursor.Left,
                         QtGui.QTextCursor.MoveAnchor, 1)
         tc.select(QtGui.QTextCursor.WordUnderCursor)
         if len(tc.selectedText()) <= 1:
             return
         self.completer.setCompletionPrefix(tc.selectedText())
         popup = self.completer.popup()
         popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
         cr = self.cursorRect()
         cr.setWidth(
             self.completer.popup().sizeHintForColumn(0) +
             self.completer.popup().verticalScrollBar().sizeHint().width())
         self.completer.complete(cr)
     else:
         self.completer.popup().hide()
Example #14
0
    def set_bytes(self, bs):
        self.pretty_mode = False
        self.data = bs
        chunks = HextEditor._split_by_printables(bs)
        self.clear()
        cursor = QTextCursor(self.textedit.document())
        cursor.beginEditBlock()

        cursor.select(QTextCursor.Document)
        cursor.setCharFormat(QTextCharFormat())
        cursor.clearSelection()

        for chunk in chunks:
            if chr(chunk[0]) in qtprintable:
                cursor.insertText(chunk.decode())
            else:
                for b in chunk:
                    self._insert_byte(cursor, b)
        cursor.endEditBlock()
Example #15
0
 def __update_text_status_messages(self, severity, msg):  # yet another PyQt5 thread workaround
     prepend = ''
     append = '<br>'
     if severity < 6:
         prepend = '<span style="color:'
         append = '</span><br>'
     if severity == 5:
         prepend = f'{prepend} #53a0ed;">'
     elif severity == 4:
         prepend = f'{prepend} yellow;">'
     elif severity == 3 or severity == 0:
         prepend = f'{prepend} red;">'
     elif 1 <= severity <= 2:
         prepend = f'{prepend} orange;">'
     cursor = QTextCursor(self._window.text_status.document())
     cursor.setPosition(0)
     self._window.text_status.setTextCursor(cursor)
     self._window.text_status.insertHtml(f'{prepend}{msg}{append}\n')
     if self._window.text_status.toPlainText().count('\n') >= _MAX_STATUSTEXT_MESSAGES:
         cursor.movePosition(QTextCursor.End)
         cursor.select(QTextCursor.LineUnderCursor)
         cursor.removeSelectedText()
         cursor.deletePreviousChar()
Example #16
0
    def _handle_location_click(self, item):
        if item.text()[0] == '/':
            file, line = item.text().split(':')
            try:
                with open(file) as f:
                    content = f.read()

                self.text.setText(content)
                block = self.text.document().findBlockByNumber(int(line) - 1)
                cur = QTextCursor(block)
                cur.select(QTextCursor.LineUnderCursor)

                extra = QTextEdit.ExtraSelection()
                extra.format.setProperty(QTextFormat.FullWidthSelection, True)
                extra.format.setBackground(QColor(Qt.yellow).lighter(160))
                extra.cursor = cur
                self.text.setExtraSelections([extra])

                self.text.setTextCursor(cur)
                self.text.moveCursor(QTextCursor.EndOfLine)
            except IOError as e:
                QMessageBox().critical(
                    self, "Could not open file",
                    "Could not open file %s: %s" % (file, e.strerror))
Example #17
0
File: ARUP.py Project: cdhigh/ARUP
    def highlightCodeLine(self, execInfo):
        if not execInfo:
            return

        lineNo = 0
        mat = re.search(r'File "<user code>", line (\d+)', execInfo)
        if mat:
            lineNo = mat.group(1)
            if lineNo.isdigit():
                lineNo = int(lineNo)
            else:
                return
        else:
            return

        doc = self.txtCode.document()
        block = doc.findBlockByLineNumber(lineNo - 1)
        blockPos = block.position()
        cursor = QTextCursor(block)
        cursor.setPosition(blockPos, QTextCursor.MoveAnchor)
        cursor.select(QTextCursor.LineUnderCursor)
        self.txtCode.setTextCursor(cursor)

        self.txtCode.setFocus()
Example #18
0
    def post_import(self, settings, doc):
        """Adaptations of the source after running musicxml2ly

        Present settings:
        Reformat source
        Remove superfluous durations
        Remove duration scaling
        Engrave directly
        """
        cursor = QTextCursor(doc)
        if settings[0]:
            import reformat
            reformat.reformat(cursor)
        if settings[1]:
            cursor.select(QTextCursor.Document)
            from rhythm import rhythm
            rhythm.rhythm_implicit_per_line(cursor)
        if settings[2]:
            cursor.select(QTextCursor.Document)
            from rhythm import rhythm
            rhythm.rhythm_remove_fraction_scaling(cursor)
        if settings[3]:
            import engrave
            engrave.engraver(self.mainwindow()).engrave('preview', doc, False)
Example #19
0
    def post_import(self, settings, doc):
        """Adaptations of the source after running musicxml2ly

        Present settings:
        Reformat source
        Remove superfluous durations
        Remove duration scaling
        Engrave directly
        """
        cursor = QTextCursor(doc)
        if settings[0]:
            import reformat
            reformat.reformat(cursor)
        if settings[1]:
            cursor.select(QTextCursor.Document)
            from rhythm import rhythm
            rhythm.rhythm_implicit_per_line(cursor)
        if settings[2]:
            cursor.select(QTextCursor.Document)
            from rhythm import rhythm
            rhythm.rhythm_remove_fraction_scaling(cursor)
        if settings[3]:
            import engrave
            engrave.engraver(self.mainwindow()).engrave('preview', doc, False)
Example #20
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
Example #21
0
    def SaveAsPDF(self):
        """ Save Table as pdf """
        fileName, _ = QFileDialog.getSaveFileName(self, "Save File", "",
                                                  "PDF Files (*.pdf)")
        if fileName == "":
            return

        try:
            videoName = self.player.fileName
            timestamp = self.player.player.position()
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            rows = self.VManager.rowCount()
            columns = self.VManager.columnCount()

            printer = QPrinter(QPrinter.HighResolution)
            innerRect = printer.pageRect()
            sizeF = QSizeF(innerRect.size().width(), innerRect.size().height())
            header = QTextDocument()
            header.setPageSize(sizeF)
            cursor_header = QTextCursor(header)
            format1 = QTextCharFormat()
            format1.setFontPointSize(16)
            cursor_header.insertHtml(
                "<p style='text-align: left;'><strong>Video</strong>: %s <strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TimeStamp</strong>: %s </p>"
                % (videoName, timestamp))
            cursor_header.insertHtml("<br><br><br> ")

            cursor_header.select(QTextCursor.Document)
            fragment_header = cursor_header.selection()

            document = QTextDocument()
            cursor = QTextCursor(document)
            tableFormat = QTextTableFormat()
            tableFormat.setHeaderRowCount(1)
            tableFormat.setBorderBrush(QBrush(Qt.black))
            tableFormat.setAlignment(Qt.AlignHCenter)
            tableFormat.setCellPadding(5)
            tableFormat.setCellSpacing(5)

            cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
            cursor.insertFragment(fragment_header)

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

            tableHeaderFormat = QTextCharFormat()
            tableHeaderFormat.setBackground(QColor("#DADADA"))

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

            for row in range(rows):
                for column in range(columns):
                    item = self.VManager.item(row, column)
                    if item is not None:
                        cell = textTable.cellAt(row + 1, column)
                        cellCursor = cell.firstCursorPosition()
                        cellCursor.insertText(
                            self.VManager.item(row, column).text())

            cursor.movePosition(QTextCursor.End)
            printer.setOrientation(QPrinter.Portrait)

            printer.setPageMargins(30, 100, 10, 40, QPrinter.DevicePixel)
            printer.setFullPage(True)
            printer.setPageSize(QPrinter.A4)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fileName)

            document.print_(printer)
            QApplication.restoreOverrideCursor()
            qgsu.showUserAndLogMessage(
                QCoreApplication.translate("QgsFmvMetadata",
                                           "Succesfully creating PDF"))
        except Exception as e:
            QApplication.restoreOverrideCursor()
            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "QgsFmvMetadata", "Failed creating PDF"),
                                       level=QGis.Warning)
            return
        return
Example #22
0
 def get_find_range(self):
     tc = QTextCursor(self.range_sel.cursor)  # copy of range cursor
     if not tc.hasSelection():
         tc.select(QTextCursor.Document)
     return tc
Example #23
0
 def get_find_range(self):
     tc = QTextCursor(self.range_sel.cursor) # copy of range cursor
     if not tc.hasSelection() :
         tc.select(QTextCursor.Document)
     return tc
Example #24
0
class ParsingInput(QWidget):
    edit_complete = pyqtSignal(Task)

    def __init__(self):
        super().__init__(flags=Qt.WindowTitleHint | Qt.WindowCloseButtonHint
                         | Qt.WindowMinimizeButtonHint
                         | Qt.WindowMaximizeButtonHint)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setMinimumSize(28, 28)
        self.setCursor(Qt.IBeamCursor)
        self.text = []
        self.character_offsets = [5]
        self.parsed_blocks = []
        self.qt_text = QTextDocument("")
        self.cursor = QTextCursor(self.qt_text)
        self.cursor.setPosition(0)
        self.cursor_visible = True
        self.cursor_timer = QTimer()
        self.cursor_timer.timeout.connect(self.blink_cursor)
        self.set_cursor_visible()

    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        qp.setRenderHint(QPainter.Antialiasing)
        qp.setRenderHint(QPainter.HighQualityAntialiasing)
        self.draw(qp)
        qp.end()

    def draw(self, qp):
        size = self.size()
        w = size.width()
        h = size.height()
        font = QFont('Sans-Serif', 12, QFont.Normal)
        qp.setFont(font)
        qp.setPen(QColor(128, 128, 128))
        qp.setBrush(QColor(255, 255, 255))
        qp.drawRoundedRect(0, 0, w, h, 5, 5)
        qp.setPen(QColor(0, 0, 0))
        font_metrics = qp.fontMetrics()
        c_start_position = 5
        cursor_pixel_position = c_start_position
        self.character_offsets = [cursor_pixel_position]
        for i, c in enumerate(self.text):
            start_of_parsed_block = False
            end_of_parsed_block = False
            inside_parsed_block = False
            for start, end in self.parsed_blocks:
                if start == i:
                    block_width = 4
                    for char in self.text[start:end]:
                        block_width += font_metrics.width(char["char"])
                    qp.setPen(QColor(0, 0, 0))
                    qp.setBrush(QColor(0, 0, 0))
                    qp.drawRoundedRect(c_start_position + 2, 4, block_width,
                                       20, 2, 2)
                    start_of_parsed_block = True
                if end == i:
                    end_of_parsed_block = True
                if start <= i < end:
                    inside_parsed_block = True
            if end_of_parsed_block:
                c_start_position += 4
            if start_of_parsed_block:
                c_start_position += 4
            c_width = font_metrics.width(c["char"])
            if self.cursor.hasSelection() and self.cursor.selectionStart(
            ) <= i < self.cursor.selectionEnd():
                if start_of_parsed_block or end_of_parsed_block:
                    sel_rect_start = c_start_position - 2
                    sel_rect_width = font_metrics.width(c["char"]) + 4
                else:
                    sel_rect_start = c_start_position
                    sel_rect_width = font_metrics.width(c["char"])
                if i != self.cursor.selectionStart():
                    sel_rect_start += 2
                if i + 1 != self.cursor.selectionEnd():
                    sel_rect_width += 2
                else:
                    sel_rect_width -= 2
                if not inside_parsed_block:
                    selection_color = QColor(100, 100, 255)
                else:
                    selection_color = QColor(60, 60, 168)
                qp.setBrush(selection_color)
                qp.setPen(selection_color)
                qp.drawRect(sel_rect_start, 6, sel_rect_width, 16)
            qp.setPen(
                QColor(inside_parsed_block * 255, inside_parsed_block * 255,
                       inside_parsed_block * 255))
            qp.setBrush(
                QColor(255 - inside_parsed_block * 255,
                       255 - inside_parsed_block * 255,
                       255 - inside_parsed_block * 255))
            qp.drawText(c_start_position, 20, c["char"])
            c_start_position += c_width
            if i == self.cursor.position() - 1:
                cursor_pixel_position = c_start_position
            self.character_offsets.append(c_start_position)
        if self.hasFocus() and self.cursor_visible:
            qp.setPen(QColor(0, 0, 0))
            for start, end in self.parsed_blocks:
                if start < self.cursor.position() <= end:
                    qp.setPen(QColor(255, 255, 255))
            qp.drawLine(cursor_pixel_position, 4, cursor_pixel_position,
                        28 - 4)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Left:
            if event.modifiers() & Qt.CTRL:
                new_pos = max(
                    0,
                    self.get_text_str().rfind(
                        " ", 0, max(0,
                                    self.cursor.position() - 1)))
            else:
                new_pos = self.cursor.position() - 1
            if event.modifiers() & Qt.SHIFT:
                if self.cursor.hasSelection():
                    self.cursor.setPosition(max(0, new_pos),
                                            mode=QTextCursor.KeepAnchor)
                else:
                    self.cursor.setPosition(self.cursor.position(),
                                            mode=QTextCursor.MoveAnchor)
                    self.cursor.setPosition(max(0, new_pos),
                                            mode=QTextCursor.KeepAnchor)
            else:
                self.cursor.setPosition(max(0, new_pos))
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_Right:
            if event.modifiers() & Qt.CTRL:
                next_space = self.get_text_str().find(
                    " ",
                    self.cursor.position() + 1, len(self.text))
                if next_space < 0:
                    new_pos = len(self.text)
                else:
                    new_pos = next_space
            else:
                new_pos = self.cursor.position() + 1
            if event.modifiers() & Qt.SHIFT:
                if self.cursor.hasSelection():
                    self.cursor.setPosition(max(0, new_pos),
                                            mode=QTextCursor.KeepAnchor)
                else:
                    self.cursor.setPosition(self.cursor.position(),
                                            mode=QTextCursor.MoveAnchor)
                    self.cursor.setPosition(max(0, new_pos),
                                            mode=QTextCursor.KeepAnchor)
            else:
                self.cursor.setPosition(min(len(self.text), new_pos))
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_Home:
            if event.modifiers() & Qt.SHIFT:
                if self.cursor.hasSelection():
                    self.cursor.setPosition(0, mode=QTextCursor.KeepAnchor)
                else:
                    self.cursor.setPosition(self.cursor.position(),
                                            mode=QTextCursor.MoveAnchor)
                    self.cursor.setPosition(0, mode=QTextCursor.KeepAnchor)
            else:
                self.cursor.setPosition(0)
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_End:
            if event.modifiers() & Qt.SHIFT:
                if self.cursor.hasSelection():
                    self.cursor.setPosition(len(self.text),
                                            mode=QTextCursor.KeepAnchor)
                else:
                    self.cursor.setPosition(self.cursor.position(),
                                            mode=QTextCursor.MoveAnchor)
                    self.cursor.setPosition(len(self.text),
                                            mode=QTextCursor.KeepAnchor)
            else:
                self.cursor.setPosition(len(self.text))
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_Escape:
            self.cursor.clearSelection()
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_Backspace:
            something_changed = False
            if self.cursor.hasSelection():
                self.delete_selected_text()
                something_changed = True
            else:
                if self.cursor.position() > 0:
                    self.text.pop(self.cursor.position() - 1)
                    self.cursor.setPosition(self.cursor.position() - 1)
                    something_changed = True
            if something_changed:
                self.parse_text()
                self.set_cursor_visible()
                self.update()
        elif key == Qt.Key_Delete:
            something_changed = False
            if self.cursor.hasSelection():
                self.delete_selected_text()
                something_changed = True
            else:
                if self.cursor.position() < len(self.text):
                    self.text.pop(self.cursor.position())
                    something_changed = True
            if something_changed:
                self.parse_text()
                self.set_cursor_visible()
                self.update()
        elif key == Qt.Key_C and event.modifiers() & Qt.CTRL:
            selected_text = self.get_selected_text()
            print("Selected Text: {}".format(selected_text))
            if len(selected_text) > 0:
                QApplication.clipboard().setText(selected_text)
        elif key == Qt.Key_V and event.modifiers() & Qt.CTRL:
            self.delete_selected_text()
            clipboard_text = QApplication.clipboard().text()
            self.text = self.text[:self.cursor.position()] + \
                [{"char": c, "parse": True} for c in clipboard_text] + \
                self.text[self.cursor.position():]
            self.parse_text()
            self.cursor.setPosition(self.cursor.position() +
                                    len(clipboard_text))
            self.set_cursor_visible()
            self.update()
        elif key == Qt.Key_Enter or key == Qt.Key_Return:
            self.edit_complete.emit(self.get_task())
            self.text = []
            self.cursor.setPosition(0)
            self.parse_text()
            self.set_cursor_visible()
            self.update()
        else:
            if len(event.text()) > 0:
                typed_text = ""
                for c in event.text():
                    if c in ALL_CHARACTERS:
                        typed_text += c
                if len(typed_text):
                    self.delete_selected_text()
                    self.text = self.text[:self.cursor.position()] + \
                        [{"char": c, "parse": True} for c in typed_text] + \
                        self.text[self.cursor.position():]
                    self.parse_text()
                    self.cursor.setPosition(self.cursor.position() +
                                            len(typed_text))
                    self.set_cursor_visible()
                    self.update()

    def get_selected_text(self):
        if self.cursor.hasSelection():
            return "".join([
                c["char"] for c in self.text[self.cursor.selectionStart():self.
                                             cursor.selectionEnd()]
            ])
        else:
            return ""

    def delete_selected_text(self):
        if self.cursor.hasSelection():
            start_pos = self.cursor.selectionStart()
            self.text = self.text[:start_pos] + self.text[self.cursor.
                                                          selectionEnd():]
            self.cursor.clearSelection()
            self.cursor.setPosition(start_pos)

    def get_min_dist_pos(self, click_x):
        min_dist_pos = 0
        min_dist = abs(self.character_offsets[0] - click_x)
        for i, offset in enumerate(self.character_offsets[1:]):
            d = abs(offset - click_x)
            if d < min_dist:
                min_dist = d
                min_dist_pos = i + 1
        return min_dist_pos

    def mousePressEvent(self, event):
        self.cursor.select(QTextCursor.BlockUnderCursor)
        self.cursor.setPosition(self.get_min_dist_pos(event.pos().x()),
                                mode=QTextCursor.MoveAnchor)
        self.update()

    def mouseMoveEvent(self, event):
        self.cursor.setPosition(self.get_min_dist_pos(event.pos().x()),
                                mode=QTextCursor.KeepAnchor)
        self.update()

    def mouseReleaseEvent(self, event):
        self.cursor.setPosition(self.get_min_dist_pos(event.pos().x()),
                                mode=QTextCursor.KeepAnchor)
        if self.cursor.selectionStart() == self.cursor.selectionEnd():
            self.cursor.clearSelection()
        self.update()

    def blink_cursor(self):
        self.cursor_visible = not self.cursor_visible
        self.update()

    def set_cursor_visible(self):
        self.cursor_visible = True
        self.cursor_timer.stop()
        self.cursor_timer.start(500)

    def get_text_str(self):
        return "".join([c["char"] for c in self.text])

    @staticmethod
    def generate_date(day, hour=None, minute=None):
        fuzziness = timedelta(days=1)
        date = datetime.now()
        if day in ["Morgen", "Tomorrow"]:
            date = datetime.now() + timedelta(days=1)
        try:
            if hour is not None and 0 <= int(hour) <= 24:
                if minute is not None and 0 <= int(minute) < 60:
                    date = datetime(year=date.year,
                                    month=date.month,
                                    day=date.day,
                                    hour=int(hour),
                                    minute=int(minute))
                else:
                    date = datetime(year=date.year,
                                    month=date.month,
                                    day=date.day,
                                    hour=int(hour),
                                    minute=0)
                fuzziness = 0
        except ValueError:
            print("Unexpected Values for hour ({}) and minute ({}). Ignoring.".
                  format(hour, minute))
        return date, fuzziness

    def parse_text(self):
        regexes = [
            (re.compile(r"(Morgen|Tomorrow) (?:at |um )?(\d\d?):(\d\d?)"),
             self.generate_date),
            (re.compile(r"(Morgen|Tomorrow)"), self.generate_date)
        ]
        text = self.get_text_str()
        saved_cursor_pos = self.cursor.position()
        self.qt_text.setPlainText(text)
        self.cursor.setPosition(saved_cursor_pos)
        self.parsed_blocks = []
        for regex, generator in regexes:
            matches = regex.finditer(text)
            for match in matches:
                if match.end() > 0 and self.text[match.end() - 1]["parse"]:
                    print(match.groups())
                    print(generator(*match.groups()))
                    text = text[:match.start()] + " " * (
                        match.end() - match.start()) + text[match.end():]
                    self.parsed_blocks.append((match.start(), match.end()))

    def get_task(self):
        new_task = Task()
        new_task.text = self.get_text_str()
        return new_task