Beispiel #1
0
    def getFontFromCmnd(self, fontinfo):
        '''
        Returns a QFont based on the information in the dictionary
        fontinfo.

        Recognized keys in the font dictionary are:
            "family": font family name (string)
            "size": text size in points (1/72 inches)
            "italic": italicize? (False/True)
            "bold": make bold? (False/True)
            "underline": underline?  (False/True)
        '''
        try:
            myfont = QFont(fontinfo["family"])
        except KeyError:
            myfont = self.__viewer.font()
        try:
            myfont.setPointSizeF(fontinfo["size"])
        except KeyError:
            pass
        try:
            myfont.setItalic(fontinfo["italic"])
        except KeyError:
            pass
        try:
            myfont.setBold(fontinfo["bold"])
        except KeyError:
            pass
        try:
            myfont.setUnderline(fontinfo["underline"])
        except KeyError:
            pass
        return myfont
Beispiel #2
0
    def set_gui(self, qfont: QFont):
        self.setText(qfont.family() + " " +
                     _format_font_size(qfont.pointSizeF()))

        preview_font = QFont(qfont)
        preview_font.setPointSizeF(self.font().pointSizeF())
        self.setFont(preview_font)
Beispiel #3
0
def pixmap(cursor, num_lines=6, scale=0.8):
    """Return a QPixmap displaying the selected lines of the document.
    
    If the cursor has no selection, num_lines are drawn.
    
    By default the text is drawn 0.8 * the normal font size. You can change
    that by supplying the scale parameter.
    
    """
    block = cursor.document().findBlock(cursor.selectionStart())
    c2 = QTextCursor(block)
    if cursor.hasSelection():
        c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor)
        c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
    else:
        c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor,
                        num_lines)

    data = textformats.formatData('editor')
    doc = QTextDocument()
    font = QFont(data.font)
    font.setPointSizeF(font.pointSizeF() * scale)
    doc.setDefaultFont(font)
    doc.setPlainText(c2.selection().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlighter.highlight(doc, state=tokeniter.state(block))
    size = doc.size().toSize() + QSize(8, -4)
    pix = QPixmap(size)
    pix.fill(data.baseColors['background'])
    doc.drawContents(QPainter(pix))
    return pix
Beispiel #4
0
 def labelLines(self, img: Optional[QPixmap], toSrc: bool):
     if not img or not self.lines:
         return None
     painter = QPainter()
     painter.begin(img)
     painter.setRenderHint(QPainter.Antialiasing, True)
     pen = QPen()
     pen.setCapStyle(Qt.RoundCap)
     font = QFont('Consolas')
     if toSrc:
         pen.setWidthF(config.lineWidth * self.ratioToSrc)
         font.setPointSizeF(config.fontSize * self.ratioToSrc)
     else:
         pen.setWidthF(config.lineWidth)
         font.setPointSizeF(config.fontSize)
     painter.setFont(font)
     for (indexA, indexB), color in self.lines.items():
         isHighlight = indexA in self.highlightPoints and indexB in self.highlightPoints \
             and (self.mode == LabelMode.AngleMode or self.mode == LabelMode.VerticalMode)
         pen.setColor(QColor.lighter(color) if isHighlight else color)
         painter.setPen(pen)
         A = self.points[indexA][0]
         B = self.points[indexB][0]
         srcA = self.getSrcPoint(A)
         srcB = self.getSrcPoint(B)
         labelPoint: QPointF
         if toSrc:
             painter.drawLine(srcA, srcB)
             labelPoint = static.getMidpoint(srcA, srcB)
         else:
             painter.drawLine(A, B)
             labelPoint = static.getMidpoint(A, B)
         painter.drawText(static.getDistanceShift(A, B, labelPoint), str(round(static.getDistance(srcA, srcB), 2)))
     painter.end()
def pixmap(cursor, num_lines=6, scale=0.8):
    """Return a QPixmap displaying the selected lines of the document.

    If the cursor has no selection, num_lines are drawn.

    By default the text is drawn 0.8 * the normal font size. You can change
    that by supplying the scale parameter.

    """
    block = cursor.document().findBlock(cursor.selectionStart())
    c2 = QTextCursor(block)
    if cursor.hasSelection():
        c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor)
        c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
    else:
        c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines)

    data = textformats.formatData('editor')
    doc = QTextDocument()
    font = QFont(data.font)
    font.setPointSizeF(font.pointSizeF() * scale)
    doc.setDefaultFont(font)
    doc.setPlainText(c2.selection().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlighter.highlight(doc, state=tokeniter.state(block))
    size = doc.size().toSize() + QSize(8, -4)
    pix = QPixmap(size)
    pix.fill(data.baseColors['background'])
    doc.drawContents(QPainter(pix))
    return pix
Beispiel #6
0
    def transform(self, value):
        if not value:
            return None
        style_map = {"normal": QFont.StyleNormal, "italic": QFont.StyleItalic, "oblique": QFont.StyleOblique}
        weight_map = {"normal": QFont.Normal, "bold": QFont.Bold}
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        style = match.group("style")
        weight = match.group("weight")
        namedweight = match.group("namedweight")
        size = match.group("size")
        family = match.group("family")
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith("pt"):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith("px"):
                font.setPixelSize(int(size[:-2]))
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', "").replace("'", "")
        font.setFamily(family)
        return font
Beispiel #7
0
 def add_line_item(self, userItem: UserItem):
     # 新建项目,在这里加载key
     # 添加的时候禁用排序,否则后面会混乱
     self.ui.table.setSortingEnabled(False)
     self.itemList[userItem.id] = userItem.load_key(self.adminPassword)
     index = self.ui.table.rowCount()
     self.ui.table.setRowCount(index + 1)
     # 内容缓存
     contents = [
         userItem.id, userItem.name, userItem.account, '******',
         userItem.email_or_phone, userItem.note
     ]
     # 显示内容,以及设置中间对齐
     for i in range(0, 5 + 1):
         self.ui.table.setItem(index, i, QTableWidgetItem(contents[i]))
         self.ui.table.item(index, i).setTextAlignment(Qt.AlignHCenter
                                                       | Qt.AlignVCenter)
     font = QFont()
     font.setFamily('consolas')
     font.setPointSizeF(9.8)
     headerItem = QTableWidgetItem(str(index + 1))
     headerItem.setFont(font)
     self.ui.table.setVerticalHeaderItem(index, headerItem)
     self.ui.table.verticalHeaderItem(index).setTextAlignment(
         Qt.AlignHCenter | Qt.AlignVCenter)
     self.ui.table.setSortingEnabled(True)
Beispiel #8
0
class GhostDelta(QGraphicsTextItem):
    # Similar to textitem
    def __init__(self, delta, fontsize=10):
        super(GhostDelta, self).__init__()
        self.delta = int(delta)
        self.setDefaultTextColor(Qt.blue)
        self.setPlainText(" {} ".format(self.delta))
        self.font = QFont("Helvetica")
        # Slightly larger font than regular textitem.
        self.font.setPointSizeF(1.25 * fontsize)
        self.setFont(self.font)
        # Is not editable.
        self.setTextInteractionFlags(Qt.NoTextInteraction)
        self.setFlag(QGraphicsItem.ItemIsMovable)

    def changeDelta(self, dlt):
        self.delta = dlt
        self.setPlainText(" {} ".format(self.delta))

    def paint(self, painter, option, widget):
        # paint the background
        painter.setPen(QPen(Qt.blue, 1))
        painter.drawRoundedRect(option.rect, 10, 10)
        # paint the normal TextItem with the default 'paint' method
        super(GhostDelta, self).paint(painter, option, widget)
Beispiel #9
0
class GhostText(QGraphicsTextItem):
    # Textitem is a qgraphicstextitem, has to handle
    # textinput and double-click to start editing etc.
    # Shift-return ends the editor
    def __init__(self, txt, fontsize=10):
        super(GhostText, self).__init__()
        self.setDefaultTextColor(Qt.blue)
        self.setPlainText(txt)
        self.font = QFont("Helvetica")
        self.font.setPointSizeF(fontsize)
        self.setFont(self.font)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        # Set it as editably with the text-editor
        self.setTextInteractionFlags(Qt.NoTextInteraction)

    def changeText(self, txt):
        self.setPlainText(txt)
        if self.scene() is not None and txt[:4].upper() == "TEX:":
            texIt = (
                "\\color{blue}\n" + txt[4:].strip()
            )  # make color blue for ghost rendering
            fragfilename = self.scene().latexAFragment(texIt)
            if fragfilename:
                self.setPlainText("")
                tc = self.textCursor()
                qi = QImage(fragfilename)
                tc.insertImage(qi)
Beispiel #10
0
    def __init__(self, parent=None, *args, **kwargs):

        QLineEdit.__init__(self, *args)
        self.ventana = parent
        font = QFont()
        if 'tamanio' in kwargs:
            font.setPointSizeF(kwargs['tamanio'])
        else:
            font.setPointSizeF(12)
        self.setFont(font)

        if 'tooltip' in kwargs:
            self.setToolTip(kwargs['tooltip'])
        if 'placeholderText' in kwargs:
            self.setPlaceholderText(kwargs['placeholderText'])

        if 'alineacion' in kwargs:
            if kwargs['alineacion'].upper() == 'DERECHA':
                self.setAlignment(QtCore.Qt.AlignRight)
            elif kwargs['alineacion'].upper() == 'IZQUIERDA':
                self.setAlignment(QtCore.Qt.AlignLeft)

        if 'enabled' in kwargs:
            self.setEnabled(kwargs['enabled'])

        if 'inputmask' in kwargs:
            self.setInputMask(kwargs['inputmask'])
Beispiel #11
0
 def labelPoints(self, img: Optional[QPixmap], toSrc: bool):
     if not img or not self.points:
         return None
     painter = QPainter()
     painter.begin(img)
     painter.setRenderHint(QPainter.Antialiasing, True)
     pen = QPen()
     pen.setCapStyle(Qt.RoundCap)
     font = QFont('Consolas')
     if toSrc:
         pen.setWidthF(config.pointWidth * self.ratioToSrc)
         font.setPointSizeF(config.fontSize * self.ratioToSrc)
     else:
         pen.setWidthF(config.pointWidth)
         font.setPointSizeF(config.fontSize)
     painter.setFont(font)
     for index, (point, color) in self.points.items():
         labelPoint: QPointF
         if toSrc:
             pen.setColor(color)
             labelPoint = self.getSrcPoint(point)
         else:
             pen.setColor(
                 color if index != self.highlightMoveIndex and index not in self.highlightPoints
                 else QColor.lighter(color)
             )
             labelPoint = point
         painter.setPen(pen)
         painter.drawPoint(labelPoint)
         painter.drawText(static.getIndexShift(labelPoint), str(index))
     painter.end()
    def paintMap(self):
        painter = QPainter(self)
        painter.setPen(QPen(Qt.black, 2, Qt.SolidLine))

        dimension = self.windowHeight / 3

        rectangleWidth = dimension * 2 / self.mapa.width
        rectangleHeight = dimension * 2 / self.mapa.height

        for i in range(self.mapa.width):
            for j in range(self.mapa.height):
                node = self.mapa.nodeArray[i][j]

                painter.setBrush(Qt.white)

                if node.isBeginning | node.isDestination:
                    painter.setBrush(Qt.darkYellow)
                elif node.isPath:
                    painter.setBrush(Qt.yellow)
                elif (node.cordX == self.drawTypeFirstX) & (
                        node.cordY == self.drawTypeFirstY):
                    painter.setBrush(Qt.gray)
                elif not node.isTraversable:
                    painter.setBrush(Qt.black)
                elif not self.mapa.isPathFound:
                    if node.isOpen:
                        painter.setBrush(Qt.magenta)
                    elif node.isClosed:
                        painter.setBrush(Qt.red)

                painter.drawRect(i * rectangleWidth,
                                 j * rectangleHeight + dimension,
                                 rectangleWidth, rectangleHeight)

                if node.isBeginning | node.isDestination:
                    painter.setBrush(Qt.black)
                    painter.drawLine(i * rectangleWidth,
                                     j * rectangleHeight + dimension,
                                     (i + 1) * rectangleWidth,
                                     (j + 1) * rectangleHeight + dimension)
                    painter.drawLine(i * rectangleWidth,
                                     (j + 1) * rectangleHeight + dimension,
                                     (i + 1) * rectangleWidth,
                                     j * rectangleHeight + dimension)

                if node.isBeginning:
                    font = QFont()
                    font.setPointSizeF(rectangleWidth / 2)
                    painter.setFont(font)
                    painter.drawText(i * rectangleWidth,
                                     (j + 1) * rectangleHeight + dimension,
                                     'A')
                if node.isDestination:
                    font = QFont()
                    font.setPointSizeF(rectangleWidth / 2)
                    painter.setFont(font)
                    painter.drawText(i * rectangleWidth,
                                     (j + 1) * rectangleHeight + dimension,
                                     'B')
Beispiel #13
0
    def __init__(self, *args, **kwargs):
        QTextEdit.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']

        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
Beispiel #14
0
 def __init__(self, parent=None, *args, **kwargs):
     #QCheckBox.__init__(parent)
     QCheckBox.__init__(self, *args)
     font = QFont()
     font.setPointSizeF(12)
     self.setFont(font)
     if 'texto' in kwargs:
         self.setText(kwargs['texto'])
Beispiel #15
0
 def __init__(self, parent=None, *args, **kwargs):
     EntradaTexto.__init__(self, parent, *args, **kwargs)
     font = QFont()
     font.setPointSizeF(12)
     self.setFont(font)
     if self.largo != 0:
         self.setMaxLength(self.largo)
     self.setMaximumWidth(50)
Beispiel #16
0
    def paintTab(self, painter: QPainter, index: int):
        if not self.isValidIndex(index):
            return
        painter.save()

        tab = self._tabs[index]
        rect = self._tabRect(index)
        selected = index == self._currentIndex
        enabled = self._enabled and tab.enabled

        if selected:
            painter.fillRect(rect, FancyToolButtonSelectedColor)

        tabText = tab.text
        tabTextRect = QRect(rect)
        drawIcon = rect.height() > 36
        tabIconRect = QRect(rect)

        tabTextRect.translate(0, -2 if drawIcon else 1)
        boldFont = QFont(painter.font())
        boldFont.setPointSizeF(SIDEBAR_FONT_SIZE)
        boldFont.setBold(True)
        painter.setFont(boldFont)
        #painter.setPen(QColor(255, 255, 255, 160) if selected else QColor(0, 0, 0, 110))
        textFlags = Qt.AlignCenter | (Qt.AlignBottom if drawIcon else
                                      Qt.AlignVCenter) | Qt.TextWordWrap

        fader = tab.fader
        if fader > 0 and not selected and enabled:
            painter.save()
            painter.setOpacity(fader)
            painter.fillRect(rect, FancyToolButtonHoverColor)
            painter.restore()

        if not enabled:
            painter.setOpacity(0.7)

        if drawIcon:
            textHeight = (painter.fontMetrics().boundingRect(
                QRect(0, 0, self.width(), self.height()), Qt.TextWordWrap,
                tabText).height())
            tabIconRect.adjust(0, 4, 0, -textHeight - 4)
            iconMode = (QIcon.Active if selected else
                        QIcon.Normal) if enabled else QIcon.Disabled
            iconRect = QRect(0, 0, MODEBAR_ICON_SIZE, MODEBAR_ICON_SIZE)
            iconRect.moveCenter(tabIconRect.center())
            iconRect = iconRect.intersected(tabIconRect)
            drawIconWithShadow(tab.icon, iconRect, painter, iconMode)

        if enabled:
            penColor = FancyTabWidgetEnabledSelectedTextColor if selected else FancyTabWidgetEnabledUnselectedTextColor
        else:
            penColor = FancyTabWidgetDisabledSelectedTextColor if selected else FancyTabWidgetDisabledUnselectedTextColor
        painter.setPen(penColor)
        painter.translate(0, -1)
        painter.drawText(tabTextRect, textFlags, tabText)

        painter.restore()
Beispiel #17
0
    def __init__(self, *args, **kwargs):

        QTableWidget.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']
        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
        self.setSortingEnabled(True)
Beispiel #18
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        style_map = {
            'normal': QFont.StyleNormal,
            'italic': QFont.StyleItalic,
            'oblique': QFont.StyleOblique,
        }
        weight_map = {
            'normal': QFont.Normal,
            'bold': QFont.Bold,
        }
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        if not match:  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")

        style = match.group('style')
        weight = match.group('weight')
        namedweight = match.group('namedweight')
        size = match.group('size')
        family = match.group('family')
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith('pt'):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith('px'):
                font.setPixelSize(int(size[:-2]))
            else:
                # This should never happen as the regex only lets pt/px
                # through.
                raise ValueError("Unexpected size unit in {!r}!".format(
                    size))  # pragma: no cover

        if family == 'monospace':
            family = self.monospace_fonts
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', '').replace("'", '')
        font.setFamily(family)

        return font
Beispiel #19
0
def fitTextToWidth(text: str, font: QFont, width: int) -> QFont:
    text_width = QFontMetrics(font).horizontalAdvance(text)
    step = font.pointSize() / 20
    new_font = QFont(font)

    while text_width > width:
        new_font.setPointSizeF(max(0, new_font.pointSize() - step))
        text_width = QFontMetrics(new_font).horizontalAdvance(text)

    return new_font
Beispiel #20
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        style_map = {
            'normal': QFont.StyleNormal,
            'italic': QFont.StyleItalic,
            'oblique': QFont.StyleOblique,
        }
        weight_map = {
            'normal': QFont.Normal,
            'bold': QFont.Bold,
        }
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        if not match:  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")

        style = match.group('style')
        weight = match.group('weight')
        namedweight = match.group('namedweight')
        size = match.group('size')
        family = match.group('family')
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith('pt'):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith('px'):
                font.setPixelSize(int(size[:-2]))
            else:
                # This should never happen as the regex only lets pt/px
                # through.
                raise ValueError("Unexpected size unit in {!r}!".format(
                    size))  # pragma: no cover
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', '').replace("'", '')
        if family == 'monospace':
            family = self.monospace_fonts
        font.setFamily(family)
        return font
Beispiel #21
0
def get_optimal_font(family_font: str, w, h, text: str) -> QFont:
    font = QFont(family_font)
    font.setStyleHint(QFont.Courier, QFont.PreferAntialias)
    metrics = QFontMetrics(font)

    # SOURCE: https://github.com/gil9red/SimplePyScripts/blob/add91e36e1ee59b3956b9fafdcffc9f4ff10ed3d/qt__pyqt__pyside__pyqode/pyqt__QPainter__draw_table.py#L98
    factor = w / metrics.boundingRect(0, 0, w, h, Qt.AlignCenter, text).width()
    if factor < 1 or factor > 1.25:
        font.setPointSizeF(font.pointSizeF() * factor)

    return font
Beispiel #22
0
 def __init__(self, *args, **kwargs):
     super().__init__()
     font = QFont()
     font.setPointSizeF(10)
     self.setFont(font)
     if 'orden' in kwargs:
         self.cOrden = kwargs['orden']
     if 'checkeable' in kwargs:
         self.CargaDatos(checkeable=kwargs['checkeable'])
     else:
         self.CargaDatos()
Beispiel #23
0
 def loadSettings(self):
     s = QSettings()
     s.beginGroup("log")
     font = QFont(s.value("fontfamily", "monospace", str))
     font.setPointSizeF(s.value("fontsize", 9.0, float))
     with qutil.signalsBlocked(self.fontChooser, self.fontSize):
         self.fontChooser.setCurrentFont(font)
         self.fontSize.setValue(font.pointSizeF())
     self.showlog.setChecked(s.value("show_on_start", True, bool))
     self.rawview.setChecked(s.value("rawview", True, bool))
     self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool))
Beispiel #24
0
    def __init__(self, str, x, y, size, w, fontname):
        super().__init__()
        font = QFont(fontname)

        fontMetrics = QFontMetrics(font)
        scale = float(fontMetrics.width(str)) / w
        font.setPointSizeF(font.pointSizeF() / scale)

        self.setFont(font)
        self.setPos(x - w / 2, y - fontMetrics.height())
        self.setPlainText(str)
Beispiel #25
0
 def loadSettings(self):
     s = QSettings()
     s.beginGroup("log")
     font = QFont(s.value("fontfamily", "monospace", str))
     font.setPointSizeF(s.value("fontsize", 9.0, float))
     with qutil.signalsBlocked(self.fontChooser, self.fontSize):
         self.fontChooser.setCurrentFont(font)
         self.fontSize.setValue(font.pointSizeF())
     self.showlog.setChecked(s.value("show_on_start", True, bool))
     self.rawview.setChecked(s.value("rawview", True, bool))
     self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool))
Beispiel #26
0
    def __init__(self, *args, **kwargs):
        QTextEdit.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']

        if 'placeholdertext' in kwargs:
            self.setPlaceholderText(kwargs['placeholdertext'])

        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
Beispiel #27
0
    def draw(self, pnt, t_start, t_end, **kwargs):
        p = QPointF(*eval_at(self._pos, t_end))

        pen = QPen(QColor(*self._to_qt_color(self.border_color)))
        pen.setWidth(self.border_width)
        pnt.setPen(pen)

        f = QFont()
        f.setPointSizeF(eval_at(self._size, t_end))
        pnt.setFont(f)

        pnt.drawText(p, eval_at(self._text, t_end))
Beispiel #28
0
    def __init__(self, parent=None, *args, **kwargs):
        QComboBox.__init__(self, parent)
        font = QFont()
        if 'tamanio' in kwargs:
            font.setPointSizeF(kwargs['tamanio'])
        else:
            font.setPointSizeF(12)

        if 'enabled' in kwargs:
            self.setEnabled(kwargs['enabled'])

        self.setFont(font)
	def parseFont(self, info):
		font = QFont(self.font())
		for s in info.split(' '):
			s = s.strip().lower()
			if (s.endswith("pt")):
				font.setPointSizeF(float(s[:-2]))

			elif s == "bold" or s == "b": font.setBold(True)
			elif s == "italic" or s == "i": font.setItalic(True)
			elif s == "underline" or s == "u": font.setUnderline(True)
			elif s == "strike": font.setStrikeOut(True)
		print(font.toString())
		return font
Beispiel #30
0
    def logformats(self):
        """Returns a dictionary with QTextCharFormats for the different types of messages.

        Besides the STDOUT, STDERR, NEUTRAL, FAILURE and SUCCESS formats there is also
        a "link" format, that looks basically the same as the output formats, but blueish
        and underlined, to make parts of the output (e.g. filenames) look clickable.

        """
        textColor = QApplication.palette().color(QPalette.WindowText)
        successColor = qutil.addcolor(textColor, 0, 128, 0) # more green
        failureColor = qutil.addcolor(textColor, 128, 0, 0) # more red
        linkColor    = qutil.addcolor(textColor, 0, 0, 128) # more blue
        stdoutColor  = qutil.addcolor(textColor, 64, 64, 0) # more purple

        s = QSettings()
        s.beginGroup("log")
        outputFont = QFont(s.value("fontfamily", "monospace", str))
        outputFont.setPointSizeF(s.value("fontsize", 9.0, float))

        output = QTextCharFormat()
        output.setFont(outputFont)
        # enable zooming the log font size
        output.setProperty(QTextFormat.FontSizeAdjustment, 0)

        stdout = QTextCharFormat(output)
        stdout.setForeground(stdoutColor)

        stderr = QTextCharFormat(output)
        link   = QTextCharFormat(output)
        link.setForeground(linkColor)
        link.setFontUnderline(True)

        status = QTextCharFormat()
        status.setFontWeight(QFont.Bold)

        neutral = QTextCharFormat(status)

        success = QTextCharFormat(status)
        success.setForeground(successColor)

        failure = QTextCharFormat(status)
        failure.setForeground(failureColor)

        return {
            job.STDOUT: stdout,
            job.STDERR: stderr,
            job.NEUTRAL: neutral,
            job.SUCCESS: success,
            job.FAILURE: failure,
            'link': link,
        }
Beispiel #31
0
    def logformats(self):
        """Returns a dictionary with QTextCharFormats for the different types of messages.

        Besides the STDOUT, STDERR, NEUTRAL, FAILURE and SUCCESS formats there is also
        a "link" format, that looks basically the same as the output formats, but blueish
        and underlined, to make parts of the output (e.g. filenames) look clickable.

        """
        textColor = QApplication.palette().color(QPalette.WindowText)
        successColor = qutil.addcolor(textColor, 0, 128, 0)  # more green
        failureColor = qutil.addcolor(textColor, 128, 0, 0)  # more red
        linkColor = qutil.addcolor(textColor, 0, 0, 128)  # more blue
        stdoutColor = qutil.addcolor(textColor, 64, 64, 0)  # more purple

        s = QSettings()
        s.beginGroup("log")
        outputFont = QFont(s.value("fontfamily", "monospace", str))
        outputFont.setPointSizeF(s.value("fontsize", 9.0, float))

        output = QTextCharFormat()
        output.setFont(outputFont)
        # enable zooming the log font size
        output.setProperty(QTextFormat.FontSizeAdjustment, 0)

        stdout = QTextCharFormat(output)
        stdout.setForeground(stdoutColor)

        stderr = QTextCharFormat(output)
        link = QTextCharFormat(output)
        link.setForeground(linkColor)
        link.setFontUnderline(True)

        status = QTextCharFormat()
        status.setFontWeight(QFont.Bold)

        neutral = QTextCharFormat(status)

        success = QTextCharFormat(status)
        success.setForeground(successColor)

        failure = QTextCharFormat(status)
        failure.setForeground(failureColor)

        return {
            job.STDOUT: stdout,
            job.STDERR: stderr,
            job.NEUTRAL: neutral,
            job.SUCCESS: success,
            job.FAILURE: failure,
            'link': link,
        }
Beispiel #32
0
    def __init__(self, *args, **kwargs):
        QTextEdit.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']
        if 'placeholderText' in kwargs:
            self.setPlaceholderText(kwargs['placeholderText'])
        if 'alto' in kwargs:
            self.setMaximumHeight(kwargs['alto'])
        if 'enabled' in kwargs:
            self.setEnabled(kwargs['enabled'])

        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
Beispiel #33
0
    def __init__(self, *args, **kwargs):

        QTableWidget.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']
        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
        if 'habilitarorden' in kwargs:
            self.setSortingEnabled(kwargs['habilitarorden'])
        else:
            self.setSortingEnabled(True)
        # self.itemClicked.connect(self.handleItemClicked)
        self.setEditTriggers(QAbstractItemView.AllEditTriggers)#para que se pueda editar el contenido con solo un click
Beispiel #34
0
 def set_font_to_text_edit(self, text_edit, size, family, bold, italic,
                           strikeout, color):
     """
     Функция set_font_and_color() получает настройки шрифта и цвет текста из базы и применяет их к компоненту QTextEdit
     """
     font = QFont()
     font.setPointSizeF(size)
     font.setFamily(family)
     font.setBold(int(bold))
     font.setItalic(int(italic))
     font.setStrikeOut(int(strikeout))
     text_edit.setFont(font)
     text_edit.setStyleSheet("QTextEdit {background-color:  #00356a}")
     text_edit.setTextColor(QColor(color))
Beispiel #35
0
    def __init__(self, *args, **kwargs):

        QTableWidget.__init__(self, *args)
        if 'tamanio' in kwargs:
            self.tamanio = kwargs['tamanio']
        font = QFont()
        font.setPointSizeF(self.tamanio)
        self.setFont(font)
        if 'habilitarorden' in kwargs:
            self.setSortingEnabled(kwargs['habilitarorden'])
        else:
            self.setSortingEnabled(True)
        if 'enabled' in kwargs:
            self.setEnabled(kwargs['enabled'])
Beispiel #36
0
def importTheme(filename, widget, schemeWidget):
    """Loads the colors theme from a file"""
    try:
        d = ET.parse(filename)
        root = d.getroot()
        if root.tag != 'frescobaldi-theme':
            raise ValueError(_("No theme found."))
    except Exception as e:
        QMessageBox.critical(widget, app.caption(_("Error")),
        _("Can't read from source:\n\n{url}\n\n{error}").format(
            url=filename, error=e))
        return

    schemeWidget.scheme.blockSignals(True)
    key = schemeWidget.addScheme(root.get('name'))
    schemeWidget.scheme.blockSignals(False)
    tfd = textformats.TextFormatData(key)

    fontElt = root.find('font')

    defaultfont = "Lucida Console" if os.name == "nt" else "monospace"
    if fontElt.get('fontFamily') in QFontDatabase().families():
        fontFamily = fontElt.get('fontFamily')
    else:
        fontFamily = defaultfont
    font = QFont(fontFamily)
    font.setPointSizeF(float(fontElt.get('fontSize')))
    tfd.font = font

    for elt in root.find('baseColors'):
        tfd.baseColors[elt.tag] = QColor(elt.get('color'))

    for elt in root.find('defaultStyles'):
        tfd.defaultStyles[elt.tag] = eltToStyle(elt)

    for style in root.find('allStyles'):
        if not style in tfd.allStyles:
            tfd.allStyles[style] = {}
        for elt in style:
            tfd.allStyles[style.tag][elt.tag] = eltToStyle(elt)

    widget.addSchemeData(key, tfd)
    schemeWidget.disableDefault(False)
    schemeWidget.currentChanged.emit()
    schemeWidget.changed.emit()
Beispiel #37
0
    def wheelEvent(self, event):
        """
        We catch wheelEvent if key modifier is CTRL to change font size.
        Note: this should be in a class specific for main textEditView (#TODO).
        """
        if event.modifiers() & Qt.ControlModifier:
            # Get the wheel angle.
            d = event.angleDelta().y() / 120

            # Update settings
            f = QFont()
            f.fromString(settings.textEditor["font"])
            f.setPointSizeF(f.pointSizeF() + d)
            settings.textEditor["font"] = f.toString()

            # Update font to all textEditView. Drastically.
            for w in F.mainWindow().findChildren(textEditView, QRegExp(".*")):
                w.loadFontSettings()

            # We tell the world that we accepted this event
            event.accept()
            return

        QTextEdit.wheelEvent(self, event)
Beispiel #38
0
class TextFormatData(object):
    """Encapsulates all settings in the Fonts & Colors page for a scheme."""
    def __init__(self, scheme):
        """Loads the data from scheme."""
        self.font = None
        self.baseColors = {}
        self.defaultStyles = {}
        self.allStyles = {}
        self._inherits = {}
        self.load(scheme)
        
    def load(self, scheme):
        """Load the settings for the scheme. Called on init."""
        s = QSettings()
        s.beginGroup("fontscolors/" + scheme)
        
        # load font
        defaultfont = "Lucida Console" if os.name == "nt" else "monospace"
        self.font = QFont(s.value("fontfamily", defaultfont, str))
        self.font.setPointSizeF(s.value("fontsize", 10.0, float))
        
        # load base colors
        s.beginGroup("basecolors")
        for name in baseColors:
            if s.contains(name):
                self.baseColors[name] = QColor(s.value(name, "", str))
            else:
                self.baseColors[name] = baseColorDefaults[name]()
        s.endGroup()
        
        # get the list of supported styles from ly.colorize
        all_styles = ly.colorize.default_mapping()
        default_styles = set()
        for group, styles in all_styles:
            d = self._inherits[group] = {}
            for style in styles:
                if style.base:
                    default_styles.add(style.base)
                    d[style.name] = style.base
        
        default_scheme = ly.colorize.default_scheme
        
        # load default styles
        s.beginGroup("defaultstyles")
        for name in default_styles:
            self.defaultStyles[name] = f = QTextCharFormat()
            css = default_scheme[None].get(name)
            if css:
                css2fmt(css, f)
            s.beginGroup(name)
            self.loadTextFormat(f, s)
            s.endGroup()
        s.endGroup()
        
        # load specific styles
        s.beginGroup("allstyles")
        for group, styles in all_styles:
            self.allStyles[group]= {}
            s.beginGroup(group)
            for style in styles:
                self.allStyles[group][style.name] = f = QTextCharFormat()
                css = default_scheme[group].get(style.name)
                if css:
                    css2fmt(css, f)
                s.beginGroup(style.name)
                self.loadTextFormat(f, s)
                s.endGroup()
            s.endGroup()
        s.endGroup()
        
    def save(self, scheme):
        """Save the settings to the scheme."""
        s = QSettings()
        s.beginGroup("fontscolors/" + scheme)
        
        # save font
        s.setValue("fontfamily", self.font.family())
        s.setValue("fontsize", self.font.pointSizeF())
        
        # save base colors
        for name in baseColors:
            s.setValue("basecolors/"+name, self.baseColors[name].name())
        
        # save default styles
        s.beginGroup("defaultstyles")
        for name in defaultStyles:
            s.beginGroup(name)
            self.saveTextFormat(self.defaultStyles[name], s)
            s.endGroup()
        s.endGroup()
        
        # save all specific styles
        s.beginGroup("allstyles")
        for group, styles in ly.colorize.default_mapping():
            s.beginGroup(group)
            for style in styles:
                s.beginGroup(style.name)
                self.saveTextFormat(self.allStyles[group][style.name], s)
                s.endGroup()
            s.endGroup()
        s.endGroup()

    def textFormat(self, group, name):
        """Return a QTextCharFormat() for the specified group and name."""
        inherit = self._inherits[group].get(name)
        f = QTextCharFormat(self.defaultStyles[inherit]) if inherit else QTextCharFormat()
        f.merge(self.allStyles[group][name])
        return f
    
    def css_scheme(self):
        """Return a dictionary of css dictionaries representing this scheme.
        
        This can be fed to the ly.colorize.format_stylesheet() function.
        
        """
        scheme = {}
        # base/default styles
        d = scheme[None] = {}
        for name, fmt in self.defaultStyles.items():
            d[name] = fmt2css(fmt)
        # mode/group styles
        for mode, styles in self.allStyles.items():
            d = scheme[mode] = {}
            for name, fmt in styles.items():
                d[name] = fmt2css(fmt)
        return scheme
    
    def palette(self):
        """Return a basic palette with text, background, selection and selection background filled in."""
        p = QApplication.palette()
        p.setColor(QPalette.Text, self.baseColors['text'])
        p.setColor(QPalette.Base, self.baseColors['background'])
        p.setColor(QPalette.HighlightedText, self.baseColors['selectiontext'])
        p.setColor(QPalette.Highlight, self.baseColors['selectionbackground'])
        return p
        
    def saveTextFormat(self, fmt, settings):
        """(Internal) Store one QTextCharFormat in the QSettings instance."""
        if fmt.hasProperty(QTextFormat.FontWeight):
            settings.setValue('bold', fmt.fontWeight() >= 70)
        else:
            settings.remove('bold')
        if fmt.hasProperty(QTextFormat.FontItalic):
            settings.setValue('italic', fmt.fontItalic())
        else:
            settings.remove('italic')
        if fmt.hasProperty(QTextFormat.TextUnderlineStyle):
            settings.setValue('underline', fmt.fontUnderline())
        else:
            settings.remove('underline')
        if fmt.hasProperty(QTextFormat.ForegroundBrush):
            settings.setValue('textColor', fmt.foreground().color().name())
        else:
            settings.remove('textColor')
        if fmt.hasProperty(QTextFormat.BackgroundBrush):
            settings.setValue('backgroundColor', fmt.background().color().name())
        else:
            settings.remove('backgroundColor')
        if fmt.hasProperty(QTextFormat.TextUnderlineColor):
            settings.setValue('underlineColor', fmt.underlineColor().name())
        else:
            settings.remove('underlineColor')
        
    def loadTextFormat(self, fmt, settings):
        """(Internal) Merge values from the QSettings instance into the QTextCharFormat."""
        if settings.contains('bold'):
            fmt.setFontWeight(QFont.Bold if settings.value('bold', False, bool) else QFont.Normal)
        if settings.contains('italic'):
            fmt.setFontItalic(settings.value('italic', False, bool))
        if settings.contains('underline'):
            fmt.setFontUnderline(settings.value('underline', False, bool))
        if settings.contains('textColor'):
            fmt.setForeground(QColor(settings.value('textColor', '' , str)))
        if settings.contains('backgroundColor'):
            fmt.setBackground(QColor(settings.value('backgroundColor', '' , str)))
        if settings.contains('underlineColor'):
            fmt.setUnderlineColor(QColor(settings.value('underlineColor', '' , str)))
Beispiel #39
0
    def __init__(self, *args, mode=None):
        QApplication.__init__(self, *args)

        # Log some basic system info
        try:
            v = openshot.GetVersion()
            log.info("openshot-qt version: %s" % info.VERSION)
            log.info("libopenshot version: %s" % v.ToString())
            log.info("platform: %s" % platform.platform())
            log.info("processor: %s" % platform.processor())
            log.info("machine: %s" % platform.machine())
            log.info("python version: %s" % platform.python_version())
            log.info("qt5 version: %s" % QT_VERSION_STR)
            log.info("pyqt5 version: %s" % PYQT_VERSION_STR)
        except:
            pass

        # Setup application
        self.setApplicationName('openshot')
        self.setApplicationVersion(info.SETUP['version'])

        # Init settings
        self.settings = settings.SettingStore()
        self.settings.load()

        # Init and attach exception handler
        from classes import exceptions
        sys.excepthook = exceptions.ExceptionHandler

        # Init translation system
        language.init_language()

        # Detect minimum libopenshot version
        _ = self._tr
        libopenshot_version = openshot.GetVersion().ToString()
        if mode != "unittest" and libopenshot_version < info.MINIMUM_LIBOPENSHOT_VERSION:
            QMessageBox.warning(None, _("Wrong Version of libopenshot Detected"),
                                      _("<b>Version %(minimum_version)s is required</b>, but %(current_version)s was detected. Please update libopenshot or download our latest installer.") %
                                {"minimum_version": info.MINIMUM_LIBOPENSHOT_VERSION, "current_version": libopenshot_version})
            # Stop launching and exit
            sys.exit()

        # Tests of project data loading/saving
        self.project = project_data.ProjectDataStore()

        # Init Update Manager
        self.updates = updates.UpdateManager()

        # It is important that the project is the first listener if the key gets update
        self.updates.add_listener(self.project)

        # Load ui theme if not set by OS
        ui_util.load_theme()

        # Start libopenshot logging thread
        self.logger_libopenshot = logger_libopenshot.LoggerLibOpenShot()
        self.logger_libopenshot.start()

        # Track which dockable window received a context menu
        self.context_menu_object = None

        # Set Font for any theme
        if self.settings.get("theme") != "No Theme":
            # Load embedded font
            try:
                log.info("Setting font to %s" % os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
                font_id = QFontDatabase.addApplicationFont(os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
                font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
                font = QFont(font_family)
                font.setPointSizeF(10.5)
                QApplication.setFont(font)
            except Exception as ex:
                log.error("Error setting Ubuntu-R.ttf QFont: %s" % str(ex))

        # Set Experimental Dark Theme
        if self.settings.get("theme") == "Humanity: Dark":
            # Only set if dark theme selected
            log.info("Setting custom dark theme")
            self.setStyle(QStyleFactory.create("Fusion"))

            darkPalette = self.palette()
            darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.WindowText, Qt.white)
            darkPalette.setColor(QPalette.Base, QColor(25, 25, 25))
            darkPalette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ToolTipBase, Qt.white)
            darkPalette.setColor(QPalette.ToolTipText, Qt.white)
            darkPalette.setColor(QPalette.Text, Qt.white)
            darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ButtonText, Qt.white)
            darkPalette.setColor(QPalette.BrightText, Qt.red)
            darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            darkPalette.setColor(QPalette.HighlightedText, Qt.black)
            darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(104, 104, 104))
            self.setPalette(darkPalette)
            self.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 0px solid white; }")

        # Create main window
        from windows.main_window import MainWindow
        self.window = MainWindow(mode)

        # Reset undo/redo history
        self.updates.reset()
        self.window.updateStatusChanged(False, False)

        log.info('Process command-line arguments: %s' % args)
        if len(args[0]) == 2:
            path = args[0][1]
            if ".osp" in path:
                # Auto load project passed as argument
                self.window.OpenProjectSignal.emit(path)
            else:
                # Auto import media file
                self.window.filesTreeView.add_file(path)
        else:
            # Recover backup file (this can't happen until after the Main Window has completely loaded)
            self.window.RecoverBackup.emit()
Beispiel #40
0
 def setTextSize(self, size):
     font = QFont()
     font.setPointSizeF(size)
     self.text.setFont(font)
Beispiel #41
0
    def __init__(self, *args):
        QApplication.__init__(self, *args)

        # Setup appication
        self.setApplicationName('openshot')
        self.setApplicationVersion(info.SETUP['version'])

        # Init settings
        self.settings = settings.SettingStore()
        try:
            self.settings.load()
        except Exception as ex:
            log.error("Couldn't load user settings. Exiting.\n{}".format(ex))
            exit()

        # Init translation system
        language.init_language()

        # Tests of project data loading/saving
        self.project = project_data.ProjectDataStore()

        # Init Update Manager
        self.updates = updates.UpdateManager()

        # It is important that the project is the first listener if the key gets update
        self.updates.add_listener(self.project)

        # Load ui theme if not set by OS
        ui_util.load_theme()

        # Track which dockable window received a context menu
        self.context_menu_object = None

        # Set Font for any theme
        if self.settings.get("theme") != "No Theme":
            # Load embedded font
            log.info("Setting font to %s" % os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
            font_id = QFontDatabase.addApplicationFont(os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
            font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
            font = QFont(font_family)
            font.setPointSizeF(10.5)
            QApplication.setFont(font)

        # Set Experimental Dark Theme
        if self.settings.get("theme") == "Humanity: Dark":
            # Only set if dark theme selected
            log.info("Setting custom dark theme")
            self.setStyle(QStyleFactory.create("Fusion"))

            darkPalette = self.palette()
            darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.WindowText, Qt.white)
            darkPalette.setColor(QPalette.Base, QColor(25, 25, 25))
            darkPalette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ToolTipBase, Qt.white)
            darkPalette.setColor(QPalette.ToolTipText, Qt.white)
            darkPalette.setColor(QPalette.Text, Qt.white)
            darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ButtonText, Qt.white)
            darkPalette.setColor(QPalette.BrightText, Qt.red)
            darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            darkPalette.setColor(QPalette.HighlightedText, Qt.black)
            self.setPalette(darkPalette)
            self.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 0px solid white; }")

        # Create main window
        from windows.main_window import MainWindow
        self.window = MainWindow()
        self.window.show()

        # Load new/blank project (which sets default profile)
        self.project.load("")

        log.info('Process command-line arguments: %s' % args)
        if len(args[0]) == 2:
            path = args[0][1]
            if ".osp" in path:
                # Auto load project passed as argument
                self.window.open_project(path)
            else:
                # Auto import media file
                self.window.filesTreeView.add_file(path)
Beispiel #42
0
    def __init__(self, *args, mode=None):
        QApplication.__init__(self, *args)

        # Log some basic system info
        try:
            v = openshot.GetVersion()
            log.info("openshot-qt version: %s" % info.VERSION)
            log.info("libopenshot version: %s" % v.ToString())
            log.info("platform: %s" % platform.platform())
            log.info("processor: %s" % platform.processor())
            log.info("machine: %s" % platform.machine())
            log.info("python version: %s" % platform.python_version())
            log.info("qt5 version: %s" % QT_VERSION_STR)
            log.info("pyqt5 version: %s" % PYQT_VERSION_STR)
        except:
            pass

        # Setup appication
        self.setApplicationName('openshot')
        self.setApplicationVersion(info.SETUP['version'])

        # Init settings
        self.settings = settings.SettingStore()
        try:
            self.settings.load()
        except Exception as ex:
            log.error("Couldn't load user settings. Exiting.\n{}".format(ex))
            exit()

        # Init translation system
        language.init_language()

        # Tests of project data loading/saving
        self.project = project_data.ProjectDataStore()

        # Init Update Manager
        self.updates = updates.UpdateManager()

        # It is important that the project is the first listener if the key gets update
        self.updates.add_listener(self.project)

        # Load ui theme if not set by OS
        ui_util.load_theme()

        # Start libopenshot logging thread
        self.logger_libopenshot = logger_libopenshot.LoggerLibOpenShot()
        self.logger_libopenshot.start()

        # Track which dockable window received a context menu
        self.context_menu_object = None

        # Set unique install id (if blank)
        if not self.settings.get("unique_install_id"):
            self.settings.set("unique_install_id", str(uuid4()))

            # Track 1st launch metric
            import classes.metrics
            classes.metrics.track_metric_screen("initial-launch-screen")

        # Set Font for any theme
        if self.settings.get("theme") != "No Theme":
            # Load embedded font
            try:
                log.info("Setting font to %s" % os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
                font_id = QFontDatabase.addApplicationFont(os.path.join(info.IMAGES_PATH, "fonts", "Ubuntu-R.ttf"))
                font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
                font = QFont(font_family)
                font.setPointSizeF(10.5)
                QApplication.setFont(font)
            except Exception as ex:
                log.error("Error setting Ubuntu-R.ttf QFont: %s" % str(ex))

        # Set Experimental Dark Theme
        if self.settings.get("theme") == "Humanity: Dark":
            # Only set if dark theme selected
            log.info("Setting custom dark theme")
            self.setStyle(QStyleFactory.create("Fusion"))

            darkPalette = self.palette()
            darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.WindowText, Qt.white)
            darkPalette.setColor(QPalette.Base, QColor(25, 25, 25))
            darkPalette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ToolTipBase, Qt.white)
            darkPalette.setColor(QPalette.ToolTipText, Qt.white)
            darkPalette.setColor(QPalette.Text, Qt.white)
            darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
            darkPalette.setColor(QPalette.ButtonText, Qt.white)
            darkPalette.setColor(QPalette.BrightText, Qt.red)
            darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            darkPalette.setColor(QPalette.HighlightedText, Qt.black)
            darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(104, 104, 104))
            self.setPalette(darkPalette)
            self.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 0px solid white; }")

        # Create main window
        from windows.main_window import MainWindow
        self.window = MainWindow(mode)

        log.info('Process command-line arguments: %s' % args)
        if len(args[0]) == 2:
            path = args[0][1]
            if ".osp" in path:
                # Auto load project passed as argument
                self.window.open_project(path)
            else:
                # Auto import media file
                self.window.filesTreeView.add_file(path)

        # Reset undo/redo history
        self.updates.reset()
        self.window.updateStatusChanged(False, False)
Beispiel #43
0
class CharMap(QWidget):
    """A widget displaying a table of characters."""
    characterSelected = pyqtSignal(str)
    characterClicked = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super(CharMap, self).__init__(parent)
        self._showToolTips = True
        self._showWhatsThis = True
        self._selected = -1
        self._column_count = 32
        self._square = 24
        self._range = (0, 0)
        self._font = QFont()
        
    def setRange(self, first, last):
        self._range = (first, last)
        self._selected = -1
        self.adjustSize()
        self.update()
    
    def range(self):
        return self._range
    
    def square(self):
        """Returns the width of one item (determined by font size)."""
        return self._square
    
    def select(self, charcode):
        """Selects the specified character (int or str)."""
        if not isinstance(charcode, int):
            charcode = ord(charcode)
        if not self._range[0] <= charcode <= self._range[1]:
            charcode = -1
        if self._selected != charcode:
            self._selected = charcode
            self.characterSelected.emit(chr(charcode))
            self.update()
    
    def character(self):
        """Returns the currently selected character, if any."""
        if self._selected != -1:
            return chr(self._selected)
    
    def setDisplayFont(self, font):
        self._font.setFamily(font.family())
        self.update()
    
    def displayFont(self):
        return QFont(self._font)
    
    def setDisplayFontSize(self, size):
        self._font.setPointSize(size)
        self._square = max(24, QFontMetrics(self._font).xHeight() * 3)
        self.adjustSize()
        self.update()
    
    def displayFontSize(self):
        return self._font.pointSize()
    
    def setDisplayFontSizeF(self, size):
        self._font.setPointSizeF(size)
        self._square = max(24, QFontMetrics(self._font).xHeight() * 3)
        self.adjustSize()
        self.update()
    
    def displayFontSizeF(self):
        return self._font.pointSizeF()
    
    def setColumnCount(self, count):
        """Sets how many columns should be used."""
        count = max(1, count)
        self._column_count = count
        self.adjustSize()
        self.update()
    
    def columnCount(self):
        return self._column_count
        
    def sizeHint(self):
        return self.sizeForColumnCount(self._column_count)

    def paintEvent(self, ev):
        rect = ev.rect()
        s = self._square
        rows = range(rect.top() // s, rect.bottom() // s + 1)
        cols = range(rect.left() // s, rect.right() // s + 1)
        
        painter = QPainter(self)
        painter.setPen(QPen(self.palette().color(QPalette.Window)))
        painter.setFont(self._font)
        metrics = QFontMetrics(self._font)
        
        # draw characters on white tiles
        tile = self.palette().color(QPalette.Base)
        selected_tile = self.palette().color(QPalette.Highlight)
        selected_tile.setAlpha(96)
        selected_box = self.palette().color(QPalette.Highlight)
        
        text_pen = QPen(self.palette().text().color())
        disabled_pen = QPen(self.palette().color(QPalette.Disabled, QPalette.Text))
        selection_pen = QPen(selected_box)
        for row in rows:
            for col in cols:
                char = row * self._column_count + col + self._range[0]
                if char > self._range[1]:
                    break
                printable = self.isprint(char)
                painter.setClipRect(col * s, row * s, s, s)
                if char == self._selected:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, selected_tile)
                    painter.setPen(selection_pen)
                    painter.drawRect(col * s, row * s, s - 1, s - 1)
                elif printable:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, tile)
                painter.setPen(text_pen if printable else disabled_pen)
                t = chr(char)
                x = col * s + s // 2 - metrics.width(t) // 2
                y = row * s + 4 + metrics.ascent()
                painter.drawText(x, y, t)
            else:
                continue
            break
    
    def sizeForColumnCount(self, count):
        """Returns the size the widget would have in a certain column count.
        
        This can be used in e.g. a resizable scroll area.
        
        """
        first, last = self._range
        rows = ((last - first) // count) + 1
        return QSize(count, rows) * self._square

    def columnCountForWidth(self, width):
        """Returns the number of columns that would fit into the given width."""
        return width // self._square

    def mousePressEvent(self, ev):
        charcode = self.charcodeAt(ev.pos())
        if charcode != -1 and self.isprint(charcode):
            self.select(charcode)
            if ev.button() != Qt.RightButton:
                self.characterClicked.emit(chr(charcode))
    
    def charcodeRect(self, charcode):
        """Returns the rectangular box around the given charcode, if any."""
        if self._range[0] <= charcode <= self._range[1]:
            row, col = divmod(charcode - self._range[0], self._column_count)
            s = self._square
            return QRect(col * s, row * s, s, s)
        
    def charcodeAt(self, position):
        row = position.y() // self._square
        col = position.x() // self._square
        if col <= self._column_count:
            charcode = self._range[0] + row * self._column_count + col
            if charcode <= self._range[1]:
                return charcode
        return -1

    def event(self, ev):
        if ev.type() == QEvent.ToolTip:
            if self._showToolTips:
                c = self.charcodeAt(ev.pos())
                if c:
                    text = self.getToolTipText(c)
                    if text:
                        rect = self.charcodeRect(c)
                        QToolTip.showText(ev.globalPos(), text, self, rect)
                        ev.accept()
                        return True
        elif ev.type() == QEvent.QueryWhatsThis:
            if self._showWhatsThis:
                ev.accept()
                return True
        elif ev.type() == QEvent.WhatsThis:
            ev.accept()
            if self._showWhatsThis:
                c = self.charcodeAt(ev.pos())
                text = self.getWhatsThisText(c) if c else None
                if text:
                    QWhatsThis.showText(ev.globalPos(), text, self)
                else:
                    QWhatsThis.leaveWhatsThisMode()
            return True
        return super(CharMap, self).event(ev)
    
    def getToolTipText(self, charcode):
        try:
            return unicodedata.name(chr(charcode))
        except ValueError:
            pass
    
    def getWhatsThisText(self, charcode):
        try:
            name = unicodedata.name(chr(charcode))
        except ValueError:
            return
        return whatsthis_html.format(
            self._font.family(), chr(charcode), name, charcode)
    
    def setShowToolTips(self, enabled):
        self._showToolTips = bool(enabled)
    
    def showToolTips(self):
        return self._showToolTips

    def setShowWhatsThis(self, enabled):
        self._showWhatsThis = bool(enabled)
    
    def showWhatsThis(self):
        return self._showWhatsThis

    def isprint(self, charcode):
        """Returns True if the given charcode is printable."""
        return isprint(charcode)