Beispiel #1
0
 def malujLinie(self):
     format = QTextBlockFormat()
     format.setBackground(Qt.white)
     self.setLineFormat(self.aktualna_linia, format)
     self.aktualna_linia = self.player.licznik
     format = QTextBlockFormat()
     format.setBackground(Qt.cyan)
     self.setLineFormat(self.aktualna_linia, format)
Beispiel #2
0
 def clear_highlight(self) -> None:
     fmt = QTextBlockFormat()
     fmt.setBackground(QColor('white'))
     block = self.editor.document().firstBlock()
     while block.isValid():
         cursor = QTextCursor(block)
         cursor.setBlockFormat(fmt)
         block = block.next()
Beispiel #3
0
 def AddLog3(self, iLevel, sMsg):
     """设置背景色"""
     self.m_LogTextEdit.appendPlainText(sMsg)
     myDoc = self.m_LogTextEdit.document()
     fmt = QTextBlockFormat()
     fmt.setBackground(LEVEL_COLOR[iLevel])
     for iNum in range(self.m_LineID, myDoc.lineCount()):
         oTextBlock = myDoc.findBlockByNumber(iNum)
         oCursor = QTextCursor(oTextBlock)
         oCursor.mergeBlockFormat(fmt)
     self.m_LineID = myDoc.lineCount()
Beispiel #4
0
    def reset(self):
        self.b_pause.setEnabled(False)
        self.b_start.setEnabled(True)
        self.combo_plansze.setEnabled(True)
        # self.konsola.clear()
        self.textBox.setEnabled(True)

        for j in range(0, len(self.textBox.toPlainText().splitlines())):
            format = QTextBlockFormat()
            format.setBackground(Qt.white)
            self.setLineFormat(j, format)

    # DZIALAJACY RESET
        for t in self.threads_list:
            if t.is_alive():
                t.raiseExc(SystemExit)
                time.sleep(0.1)
                pass
        self.threads_list = []
        self.player_thread = None
        self.timer.stop()
        self.timer_action.stop()
        self.map_init(str(self.combo_plansze.currentText()))
    def formatBlock(self, block, state):
        """Apply transformation to given block."""
        blockFormat = QTextBlockFormat()

        if state == State.BLOCKQUOTE_LINE:
            # Number of tabs
            n = block.text().indexOf(QRegExp(r'[^\t]'), 0)
            blockFormat.setIndent(0)
            blockFormat.setTextIndent(-self.tabStopWidth * n)
            blockFormat.setLeftMargin(self.tabStopWidth * n)
            # blockFormat.setRightMargin(self.editor.contentsRect().width()
            # - self.editor.lineNumberAreaWidth()
            # - fm.width("X") * self.editor.LimitLine
            # + self.editor.tabStopWidth())
            blockFormat.setAlignment(Qt.AlignJustify)
            if self.name == "Default":
                blockFormat.setTopMargin(5)
                blockFormat.setBottomMargin(5)
        elif state == State.HEADER_LINE:
            blockFormat.setBackground(QColor("#EEEEEE"))
        elif state in State.LIST:
            data = blockUserData.getUserData(block)
            if str(data.listSymbol()) in "+-":
                blockFormat.setBackground(QColor("#EEFFEE"))
            else:
                blockFormat.setBackground(QColor("#EEEEFA"))
            n = blockUserData.getUserData(block).leadingSpaces() + 1

            f = QFontMetrics(QFont(self.defaultFontFamily,
                                   self._defaultCharFormat.font().pointSize()))
            fm = f.width(" " * n +
                         blockUserData.getUserData(block).listSymbol())
            blockFormat.setTextIndent(-fm)
            blockFormat.setLeftMargin(fm)
            if blockUserData.getUserState(block) == State.LIST_BEGINS and \
                            self.name == "Default":
                blockFormat.setTopMargin(5)
        return blockFormat
Beispiel #6
0
class GenresOptionsPage(OptionsPage):

    NAME = "genres"
    TITLE = N_("Genres")
    PARENT = "metadata"
    SORT_ORDER = 20
    ACTIVE = True
    HELP_URL = '/config/options_genres.html'

    options = [
        BoolOption("setting", "use_genres", False),
        IntOption("setting", "max_genres", 5),
        IntOption("setting", "min_genre_usage", 90),
        TextOption("setting", "genres_filter",
                   "-seen live\n-favorites\n-fixme\n-owned"),
        TextOption("setting", "join_genres", ""),
        BoolOption("setting", "only_my_genres", False),
        BoolOption("setting", "artists_genres", False),
        BoolOption("setting", "folksonomy_tags", False),
    ]

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_GenresOptionsPage()
        self.ui.setupUi(self)

        self.ui.genres_filter.setToolTip(_(TOOLTIP_GENRES_FILTER))
        self.ui.genres_filter.textChanged.connect(
            self.update_test_genres_filter)

        self.ui.test_genres_filter.setToolTip(_(TOOLTIP_TEST_GENRES_FILTER))
        self.ui.test_genres_filter.textChanged.connect(
            self.update_test_genres_filter)

        # FIXME: colors aren't great from accessibility POV
        self.fmt_keep = QTextBlockFormat()
        self.fmt_keep.setBackground(Qt.green)

        self.fmt_skip = QTextBlockFormat()
        self.fmt_skip.setBackground(Qt.red)

        self.fmt_clear = QTextBlockFormat()
        self.fmt_clear.clearBackground()

    def load(self):
        config = get_config()
        self.ui.use_genres.setChecked(config.setting["use_genres"])
        self.ui.max_genres.setValue(config.setting["max_genres"])
        self.ui.min_genre_usage.setValue(config.setting["min_genre_usage"])
        self.ui.join_genres.setEditText(config.setting["join_genres"])
        self.ui.genres_filter.setPlainText(config.setting["genres_filter"])
        self.ui.only_my_genres.setChecked(config.setting["only_my_genres"])
        self.ui.artists_genres.setChecked(config.setting["artists_genres"])
        self.ui.folksonomy_tags.setChecked(config.setting["folksonomy_tags"])

    def save(self):
        config = get_config()
        config.setting["use_genres"] = self.ui.use_genres.isChecked()
        config.setting["max_genres"] = self.ui.max_genres.value()
        config.setting["min_genre_usage"] = self.ui.min_genre_usage.value()
        config.setting["join_genres"] = self.ui.join_genres.currentText()
        config.setting["genres_filter"] = self.ui.genres_filter.toPlainText()
        config.setting["only_my_genres"] = self.ui.only_my_genres.isChecked()
        config.setting["artists_genres"] = self.ui.artists_genres.isChecked()
        config.setting["folksonomy_tags"] = self.ui.folksonomy_tags.isChecked()

    def update_test_genres_filter(self):
        test_text = self.ui.test_genres_filter.toPlainText()

        filters = self.ui.genres_filter.toPlainText()
        tagfilter = TagGenreFilter(filters)

        # FIXME: very simple error reporting, improve
        self.ui.label_test_genres_filter_error.setText("\n".join([
            _("Error line %d: %s") % (lineno + 1, error)
            for lineno, error in tagfilter.errors.items()
        ]))

        def set_line_fmt(lineno, textformat):
            obj = self.ui.test_genres_filter
            if lineno < 0:
                # use current cursor position
                cursor = obj.textCursor()
            else:
                cursor = QTextCursor(obj.document().findBlockByNumber(lineno))
            obj.blockSignals(True)
            cursor.setBlockFormat(textformat)
            obj.blockSignals(False)

        set_line_fmt(-1, self.fmt_clear)
        for lineno, line in enumerate(test_text.splitlines()):
            line = line.strip()
            fmt = self.fmt_clear
            if line:
                if tagfilter.skip(line):
                    fmt = self.fmt_skip
                else:
                    fmt = self.fmt_keep
            set_line_fmt(lineno, fmt)
    def loadFormats(self):
        self.formats = {}

        stylesCSS = pkg_resources.resource_string(data.__name__, 'styles.css')
        print("styles.css file: {}".format(stylesCSS))
        styleSheet = cssutils.parseString(stylesCSS)

        blockFormats = ['title[level="1"]', 
                        'title[level="2"]', 
                        'title[level="3"]', 
                        'para',
                        'tip',
                        'warning',
                        'blockquote',
                        'programlisting[language="java"]',
                        'programlisting[language="cpp"]',
                        'programlisting[language="xml"]',
                        'programlisting[language="sql"]',
                        'programlisting[language="python"]',
                        'programlisting[language="bash"]',
                        'screen']

        for cssKey in blockFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            # get the selector as a tuple of class and one attribute selector
            # (Can be extended later, but currently sufficient)
            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()

            blockFmt = QTextBlockFormat()
            blockFmt.setProperty(QTextFormat.UserProperty, selector)

            value = self.getIntValue(cssRule, 'margin-top')
            if value:
                blockFmt.setTopMargin(value)
            value = self.getIntValue(cssRule, 'margin-right')
            if value:
                blockFmt.setRightMargin(value)
            value = self.getIntValue(cssRule, 'margin-bottom')
            if value:
                blockFmt.setBottomMargin(value)
            value = self.getIntValue(cssRule, 'margin-left')
            if value:
                blockFmt.setLeftMargin(value)
            value = self.getColorValue(cssRule, 'background-color')
            if value:
                blockFmt.setBackground(value)

            charFmt = QTextCharFormat()
            self.setCharFormatAttributes(cssRule, charFmt)

            fmt = Format(blockFmt, charFmt)
            value = self.getStringValue(cssRule, 'white-space')
            if value and value == 'pre':
                fmt.isPre = True
            self.formats[selector] = fmt

### List formats

        listFormats = ['itemizedlist[level="1"]',
                       'itemizedlist[level="2"]',
                       'itemizedlist[level="3"]', 
                       'itemizedlist[level="4"]',
                       'orderedlist[level="1"]',
                       'orderedlist[level="2"]' ,
                       'orderedlist[level="3"]',
                       'orderedlist[level="4"]'] 
        for cssKey in listFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            indent = 0
            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()
            if selector[1] == 'level':
                indent = int(selector[2])

            listFmt = QTextListFormat()
            listFmt.setProperty(QTextFormat.UserProperty, selector)
            listFmt.setIndent(indent)

            value = self.getStringValue(cssRule, 'list-style-type')
            if value:
                if value == 'disc':
                    listFmt.setStyle(QTextListFormat.ListDisc)
                elif value == 'circle':
                    listFmt.setStyle(QTextListFormat.ListCircle)
                elif value == 'square':
                    listFmt.setStyle(QTextListFormat.ListSquare)
                elif value == 'decimal':
                    listFmt.setStyle(QTextListFormat.ListDecimal)

            self.formats[selector] = Format(None, None, listFmt)

### Inline formats

        # Base format (?????)
        pcharFmt = QTextCharFormat()
        pcharFmt.setFontPointSize(10)
        pcharFmt.setFontFamily("Sans")

        inlineFormats = ['emphasis[role="highlight"]', 
                         'emphasis',
                         'code',
                         'link',
                         'olink']

        for cssKey in inlineFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()

            charFmt = QTextCharFormat(pcharFmt)
            charFmt.setProperty(QTextFormat.UserProperty, selector)

            # TODO: better approach?
            if cssKey in ['link', 'olink']:
                charFmt.setAnchor(True)
            self.setCharFormatAttributes(cssRule, charFmt)

            self.formats[selector] = Format(None, charFmt)

### special formats
        charFmt = QTextCharFormat()
        cssRule = self.simpleLookup(styleSheet, 'searchMarker')
        self.setCharFormatAttributes(cssRule, charFmt)
        self.formats[('searchMarker', None, None)] = Format(None, charFmt)
class ProgressWindow(QWidget):
    def __init__(self, filedialog):
        super().__init__()
        self.filedialog = filedialog
        self.parent = self.filedialog.parent
        self.args = filedialog.args
        self.imageList = None
        self.batchInfos = {}

        self.fmt = QTextBlockFormat()
        self.fmt.setBackground(Qt.red)

        layout = QVBoxLayout()

        self.labelImagesProcessed = QLabel("Images Processed:")
        layout.addWidget(self.labelImagesProcessed)

        self.imagesProcessed = QListWidget()

        self.labels = [os.path.splitext(os.path.basename(img))[0] for img in self.args.images]
        self.imagesProcessed.itemDoubleClicked.connect(self.images_processed_double_left_click)
        self.imagesProcessed.itemClicked.connect(images_processed_single_left_click)
        layout.addWidget(self.imagesProcessed)

        self.labelTextInfos = QLabel("Processed image infos:")
        layout.addWidget(self.labelTextInfos)

        self.textInfos = QTextEdit()
        self.textInfos.setReadOnly(True)
        layout.addWidget(self.textInfos)

        self.progress_bar = QProgressBar(self)
        self.progress_bar.setGeometry(30, 40, self.width(), 25)
        self.progress_bar.setMaximum(5 + len(self.args.images))
        self.progress_bar.setValue(0)
        self.progress_bar_increase = 0
        layout.addWidget(self.progress_bar)

        horizontal_box = QHBoxLayout()
        self.back_btn = QPushButton('Back', self)
        self.back_btn.clicked.connect(self.back_process)

        self.start_btn = QPushButton('Start', self)
        self.start_btn.clicked.connect(self.start_process)

        self.stop_btn = QPushButton('Stop', self)
        self.stop_btn.clicked.connect(self.stop_process)

        self.stop_btn.setEnabled(False)
        self.start_btn.setEnabled(True)

        horizontal_box.addWidget(self.back_btn, alignment=Qt.AlignLeft)
        horizontal_box.addStretch(2)
        horizontal_box.addWidget(self.stop_btn)
        horizontal_box.addWidget(self.start_btn)

        layout.addLayout(horizontal_box)
        self.setLayout(layout)

        # define signals
        self.obj = WorkerImageDetection(self)
        self.detection_thread = QThread()

        self.obj.moveToThread(self.detection_thread)
        self.detection_thread.started.connect(self.obj.run)

        # Handle closing events
        self.obj.finished.connect(self.finished_process)
        self.obj.finished.connect(self.detection_thread.quit)
        self.obj.finished.connect(self.obj.deleteLater)
        self.obj.finished.connect(self.detection_thread.deleteLater)

        # Handle processing signals from detector
        self.obj.error.connect(self.handle_error)
        self.obj.info.connect(self.handle_info)
        self.obj.no_detections.connect(self.handle_no_detections)

        self.obj.images_ready.connect(self.handle_images_ready)
        self.obj.batch_info.connect(self.handle_batch_info)

    def start_process(self):
        self.stop_btn.setEnabled(True)
        self.start_btn.setEnabled(False)
        self.detection_thread.start()

    def stop_process(self):
        self.stop_btn.setEnabled(False)
        self.start_btn.setEnabled(True)
        self.progress_bar.setValue(0)
        self.detection_thread.terminate()

    def finished_process(self):
        self.stop_btn.setEnabled(False)
        self.start_btn.setEnabled(True)
        self.progress_bar.setValue(0)
        QMessageBox.information(self, "Done!", "Done detecting images!")

    def handle_error(self, msg):
        messagebox = QMessageBox()
        messagebox.critical(self, "Error", msg)
        messagebox.setFixedSize(500, 200)
        self.filedialog.parent.change_widget(self.filedialog)

    def handle_info(self, msg):
        if not self.textInfos:
            self.textInfos.append(msg)
        else:
            self.textInfos.append("\n" + msg)
        if self.progress_bar_increase == 1:
            self.progress_bar.setValue(1 + self.progress_bar.value())
        self.progress_bar_increase = 1 - self.progress_bar_increase

    def handle_batch_info(self, msg, image_id):
        self.batchInfos[image_id] = msg
        self.imagesProcessed.addItem(self.labels[image_id])

    def handle_no_detections(self, msg):
        message = QMessageBox()
        message.warning(self, "Warning", msg)
        message.setFixedSize(500, 200)

    def handle_images_ready(self, image_list):
        self.imageList = image_list
        for image in image_list:
            image.set_batch_info(self.batchInfos[image.image_ind])

    def images_processed_double_left_click(self):
        current_id = self.imagesProcessed.currentRow()
        if self.imageList:
            img = self.imageList[current_id]
            self.parent.show_image_viewer(img, self.tr(f"{self.labels[current_id].capitalize()} Detection View"))
        else:
            QMessageBox.information(self, f"{self.labels[current_id]} detection info", self.batchInfos[current_id])

    def back_process(self):
        self.parent.back_to_parent()
        self.deleteLater()
Beispiel #9
0
 def highlight_error(self, line: int) -> None:
     block = self.editor.document().findBlockByLineNumber(line - 1)
     cursor = QTextCursor(block)
     fmt = QTextBlockFormat()
     fmt.setBackground(QColor(255, 220, 190))
     cursor.setBlockFormat(fmt)