Exemplo n.º 1
0
class CharMap(preferences.Group):
    def __init__(self, page):
        super(CharMap, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Special Characters"))
        self.fontLabel.setText(_("Font:"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        font = self.font()
        family = s.value("fontfamily", "", str)
        if family:
            font.setFamily(family)
        font.setPointSizeF(s.value("fontsize", font.pointSizeF(), float))
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(font.pointSizeF())

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
Exemplo n.º 2
0
class FontLayout(QGridLayout):
    """Font selection"""
    def __init__(self, value, parent=None):
        QGridLayout.__init__(self)
        font = tuple_to_qfont(value)
        assert font is not None
        
        # Font family
        self.family = QFontComboBox(parent)
        self.family.setCurrentFont(font)
        self.addWidget(self.family, 0, 0, 1, -1)
        
        # Font size
        self.size = QComboBox(parent)
        self.size.setEditable(True)
        sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72]
        size = font.pointSize()
        if size not in sizelist:
            sizelist.append(size)
            sizelist.sort()
        self.size.addItems([str(s) for s in sizelist])
        self.size.setCurrentIndex(sizelist.index(size))
        self.addWidget(self.size, 1, 0)
        
        # Italic or not
        self.italic = QCheckBox(self.tr("Italic"), parent)
        self.italic.setChecked(font.italic())
        self.addWidget(self.italic, 1, 1)
        
        # Bold or not
        self.bold = QCheckBox(self.tr("Bold"), parent)
        self.bold.setChecked(font.bold())
        self.addWidget(self.bold, 1, 2)
        
    def get_font(self):
        font = self.family.currentFont()
        font.setItalic(self.italic.isChecked())
        font.setBold(self.bold.isChecked())
        font.setPointSize(int(self.size.currentText()))
        return qfont_to_tuple(font)
Exemplo n.º 3
0
class LogTool(preferences.Group):
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)

        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)

        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)

        self.hideauto = QCheckBox(toggled=self.changed)
        layout.addWidget(self.hideauto)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("LilyPond Log"))
        self.fontLabel.setText(_("Font:"))
        self.showlog.setText(_("Show log when a job is started"))
        self.rawview.setText(_("Display plain log output"))
        self.rawview.setToolTip(
            _("If checked, Frescobaldi will not shorten filenames in the log output."
              ""))
        self.hideauto.setText(_("Hide automatic engraving jobs"))
        self.hideauto.setToolTip(
            _("If checked, Frescobaldi will not show the log for automatically\n"
              "started engraving jobs (LilyPond->Auto-engrave)."))

    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))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("log")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
        s.setValue("show_on_start", self.showlog.isChecked())
        s.setValue("rawview", self.rawview.isChecked())
        s.setValue("hide_auto_engrave", self.hideauto.isChecked())
Exemplo n.º 4
0
class GlobalFontDialog(widgets.dialog.Dialog):
    def __init__(self, parent=None):
        super(GlobalFontDialog, self).__init__(parent)
        self._messageLabel.setWordWrap(True)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.mainWidget().setLayout(layout)

        self.romanLabel = QLabel()
        self.romanCombo = QFontComboBox()
        self.sansLabel = QLabel()
        self.sansCombo = QFontComboBox()
        self.typewriterLabel = QLabel()
        self.typewriterCombo = QFontComboBox(
            fontFilters=QFontComboBox.MonospacedFonts)

        layout.addWidget(self.romanLabel, 0, 0)
        layout.addWidget(self.romanCombo, 0, 1, 1, 2)
        layout.addWidget(self.sansLabel, 1, 0)
        layout.addWidget(self.sansCombo, 1, 1, 1, 2)
        layout.addWidget(self.typewriterLabel, 2, 0)
        layout.addWidget(self.typewriterCombo, 2, 1, 1, 2)

        self.loadSettings()
        self.finished.connect(self.saveSettings)
        app.translateUI(self)

    def translateUI(self):
        self.setWindowTitle(app.caption(_("Global Fonts")))
        self.setMessage(
            _("Please select the three global fonts to use for "
              r"<code>\roman</code>, <code>\sans</code>, and <code>\typewriter</code> "
              "respectively."))
        self.romanLabel.setText(_("Roman Font:"))
        self.sansLabel.setText(_("Sans Font:"))
        self.typewriterLabel.setText(_("Typewriter Font:"))

    def romanFont(self):
        return self.romanCombo.currentFont().family()

    def setromanFont(self, family):
        self.romanCombo.setCurrentFont(QFont(family))

    def sansFont(self):
        return self.sansCombo.currentFont().family()

    def setSansFont(self, family):
        self.sansCombo.setCurrentFont(QFont(family))

    def typewriterFont(self):
        return self.typewriterCombo.currentFont().family()

    def settypewriterFont(self, family):
        self.typewriterCombo.setCurrentFont(QFont(family))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("global_font_dialog")
        roman = s.value("roman", "Century Schoolbook L", str)
        self.romanCombo.setCurrentFont(QFont(roman))
        sans = s.value("sans", "sans-serif", str)
        self.sansCombo.setCurrentFont(QFont(sans))
        typewriter = s.value("typewriter", "monospace", str)
        self.typewriterCombo.setCurrentFont(QFont(typewriter))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("global_font_dialog")
        s.setValue("roman", self.romanCombo.currentFont().family())
        s.setValue("sans", self.sansCombo.currentFont().family())
        s.setValue("typewriter", self.typewriterCombo.currentFont().family())
Exemplo n.º 5
0
    rotationSliderY = QSlider(Qt.Horizontal)
    rotationSliderY.setTickInterval(15)
    rotationSliderY.setTickPosition(QSlider.TicksAbove)
    rotationSliderY.setMinimum(-90)
    rotationSliderY.setValue(0)
    rotationSliderY.setMaximum(90)

    fontSizeSlider = QSlider(Qt.Horizontal)
    fontSizeSlider.setTickInterval(10)
    fontSizeSlider.setTickPosition(QSlider.TicksBelow)
    fontSizeSlider.setMinimum(1)
    fontSizeSlider.setValue(30)
    fontSizeSlider.setMaximum(100)

    fontList = QFontComboBox()
    fontList.setCurrentFont(QFont('Times New Roman'))

    shadowQuality = QComboBox()
    shadowQuality.addItem("None")
    shadowQuality.addItem("Low")
    shadowQuality.addItem("Medium")
    shadowQuality.addItem("High")
    shadowQuality.addItem("Low Soft")
    shadowQuality.addItem("Medium Soft")
    shadowQuality.addItem("High Soft")
    shadowQuality.setCurrentIndex(5)

    rangeList = QComboBox()
    rangeList.addItems(GraphModifier.years)
    rangeList.addItem("All")
    rangeList.setCurrentIndex(len(GraphModifier.years))
Exemplo n.º 6
0
                                   checked=True)

    gridCheckBox = QCheckBox(Tr.get("Show grid", "Show grid"), checked=True)

    shadowQuality = QComboBox()
    shadowQuality.addItem("None")
    shadowQuality.addItem("Low")
    shadowQuality.addItem("Medium")
    shadowQuality.addItem("High")
    shadowQuality.addItem("Low Soft")
    shadowQuality.addItem("Medium Soft")
    shadowQuality.addItem("High Soft")
    shadowQuality.setCurrentIndex(4)

    fontList = QFontComboBox()
    fontList.setCurrentFont(QFont('Arial'))

    vLayout.addWidget(labelButton, 0, Qt.AlignTop)
    vLayout.addWidget(cameraButton, 0, Qt.AlignTop)
    vLayout.addWidget(itemCountButton, 0, Qt.AlignTop)
    vLayout.addWidget(backgroundCheckBox)
    vLayout.addWidget(gridCheckBox)
    vLayout.addWidget(smoothCheckBox, 0, Qt.AlignTop)
    vLayout.addWidget(QLabel(Tr.get("Change dot style", "Change dot style")))
    vLayout.addWidget(itemStyleList)
    vLayout.addWidget(QLabel(Tr.get("Change theme", "Change theme")))
    vLayout.addWidget(themeList)
    vLayout.addWidget(
        QLabel(Tr.get("Adjust shadow quality", "Adjust shadow quality")))
    vLayout.addWidget(shadowQuality)
    vLayout.addWidget(QLabel(Tr.get("Change font", "Change font")))
Exemplo n.º 7
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.view = TextView(self)
        self.setCentralWidget(self.view)

        self.toolbar = self.addToolBar('Text Effects')

        # Set up the text effects tools
        actionGroup = QActionGroup(self)

        noneAction = QAction(QIcon("none.png"), "&Clear", self)
        noneAction.setStatusTip("Clear Effects")
        noneAction.triggered.connect(self.view.noEffect)
        actionGroup.addAction(noneAction)

        blurAction = QAction(QIcon("blur.png"), "&Blur", self)
        blurAction.setStatusTip("Blur Text")
        blurAction.triggered.connect(self.view.blur)
        actionGroup.addAction(blurAction)

        opacityAction = QAction(QIcon("opacity.png"), "&Transparency", self)
        opacityAction.setStatusTip("Fade Text")
        opacityAction.triggered.connect(self.view.opacity)
        actionGroup.addAction(opacityAction)

        shadowAction = QAction(QIcon("shadow.png"), "&Drop Shadow", self)
        shadowAction.setStatusTip("Drop-shadow Text")
        shadowAction.triggered.connect(self.view.shadow)
        actionGroup.addAction(shadowAction)

        self.toolbar.addActions(actionGroup.actions())
        self.toolbar.addSeparator()

        # Set up the font selection tools
        boldAction = QAction(QIcon("bold.png"), "&Bold", self)
        boldAction.setStatusTip("Bold Text")
        boldAction.setCheckable(True)
        boldAction.setChecked(True)
        boldAction.triggered[bool].connect(self.view.bold)
        self.toolbar.addAction(boldAction)

        italicAction = QAction(QIcon("italic.png"), "&Italic", self)
        italicAction.setStatusTip("Italic Text")
        italicAction.setCheckable(True)
        italicAction.triggered[bool].connect(self.view.italic)
        self.toolbar.addAction(italicAction)

        self.fontBox = QFontComboBox(self)
        self.fontBox.setCurrentFont(QFont("PT Sans", 16, QFont.Bold))
        self.fontBox.currentFontChanged.connect(self.view.fontFamily)
        self.toolbar.addWidget(self.fontBox)

        self.fontSizeBox = QComboBox(self)
        self.fontSizeBox.setEditable(True)
        strlist = []
        intlist = QFontDatabase.standardSizes()
        for item in intlist:
            strlist.append(str(item))
        self.fontSizeBox.addItems(strlist)
        self.fontSizeBox.setCurrentText("16")
        self.fontSizeBox.currentTextChanged.connect(self.view.fontSize)
        self.toolbar.addWidget(self.fontSizeBox)

        self.setGeometry(300, 300, 600, 500)
        self.setWindowTitle('Renderer')
        self.show()
Exemplo n.º 8
0
class TextItemDlg(QDialog):
    def __init__(self, item=None, position=None, scene=None, parent=None):
        super(QDialog, self).__init__(parent)

        self.item = item
        self.position = position
        self.scene = scene

        self.editor = QTextEdit()
        self.editor.setAcceptRichText(False)
        self.editor.setTabChangesFocus(True)
        editorLabel = QLabel("&Text:")
        editorLabel.setBuddy(self.editor)
        self.fontComboBox = QFontComboBox()
        self.fontComboBox.setCurrentFont(QFont("Times", PointSize))
        fontLabel = QLabel("&Font:")
        fontLabel.setBuddy(self.fontComboBox)
        self.fontSpinBox = QSpinBox()
        self.fontSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.fontSpinBox.setRange(6, 280)
        self.fontSpinBox.setValue(PointSize)
        fontSizeLabel = QLabel("&Size:")
        fontSizeLabel.setBuddy(self.fontSpinBox)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

        if self.item is not None:
            self.editor.setPlainText(self.item.toPlainText())
            self.fontComboBox.setCurrentFont(self.item.font())
            self.fontSpinBox.setValue(self.item.font().pointSize())

        layout = QGridLayout()
        layout.addWidget(editorLabel, 0, 0)
        layout.addWidget(self.editor, 1, 0, 1, 6)
        layout.addWidget(fontLabel, 2, 0)
        layout.addWidget(self.fontComboBox, 2, 1, 1, 2)
        layout.addWidget(fontSizeLabel, 2, 3)
        layout.addWidget(self.fontSpinBox, 2, 4, 1, 2)
        layout.addWidget(self.buttonBox, 3, 0, 1, 6)
        self.setLayout(layout)

        self.fontComboBox.currentFontChanged.connect(self.updateUi)
        self.fontSpinBox.valueChanged.connect(self.updateUi)
        self.editor.textChanged.connect(self.updateUi)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.setWindowTitle("Page Designer - {0} Text Item".format(
            "Add" if self.item is None else "Edit"))
        self.updateUi()

    def updateUi(self):
        font = self.fontComboBox.currentFont()
        font.setPointSize(self.fontSpinBox.value())
        self.editor.document().setDefaultFont(font)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(
            bool(self.editor.toPlainText()))

    def accept(self):
        if self.item is None:
            self.item = TextItem("", self.position, self.scene)
        font = self.fontComboBox.currentFont()
        font.setPointSize(self.fontSpinBox.value())
        self.item.setFont(font)
        self.item.setPlainText(self.editor.toPlainText())
        self.item.update()
        global Dirty
        Dirty = True
        QDialog.accept(self)
Exemplo n.º 9
0
class BarTop(QWidget):
    """
    class that holds the top bar attributes
    """
    def __init__(self, path_res: str, document: Document):
        """
        sets up the top bar and its features
        :return: returns nothing
        """
        super().__init__()
        logging.debug("Creating Top Bar")
        self.path_res: str = path_res
        self.document: Document = document
        self.doc_props: DocProps = self.document.doc_props

        self.combo_title_style = None
        self.combo_font_style = None
        self.combo_font_size = None

        self.button_bold = None
        self.button_ital = None
        self.button_strike = None
        self.button_under = None

        self.combo_text_color = None
        self.button_clear = None
        self.combo_text_align = None
        self.button_mode_switch = None

    def makeMainLayout(self):
        """
        You can get the layout generated with self.layout()
        :return: the main layout of the top bar
        """
        horizontal_layout = QHBoxLayout()
        horizontal_layout.setContentsMargins(0, 0, 0, 0)
        horizontal_layout.setSpacing(3)
        self.setLayout(horizontal_layout)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        return horizontal_layout

    def makeTitleStyleBox(self) -> QComboBox:
        """
        Create Title Style Drop Down
        """
        # ComboBox for title style
        self.combo_title_style = QComboBox(self)
        view = QListView(self.combo_title_style)
        view.setStyleSheet("QListView::item { height : 23 px; }"
                           "selection-background-color: rgba(0,0,0,0.2);")
        self.combo_title_style.setView(view)
        self.combo_title_style.setToolTip('Styles')
        self.combo_title_style.addItems(self.doc_props.dict_title_styles)
        # traverses through combo_title_style items index
        for x in range(view.model().rowCount()):
            # mods by two to get the index with titles else gives "update" titles index
            # changes font to be bold for if and italic for else
            if x % 2 == 0:
                font = QFont()
                font.setWeight(QFont.Bold)
                self.combo_title_style.setItemData(x, font, Qt.FontRole)
            else:
                font = QFont()
                color = QBrush()
                font.setItalic(True)
                color.setColor(QColor("gray"))
                self.combo_title_style.setItemData(x, font, Qt.FontRole)
                self.combo_title_style.setItemData(x, color, Qt.ForegroundRole)
        # adds separators to clean up look of QComboBox
        for x in range(2, 23, 3):
            size = QSize()
            size.setHeight(10)
            separator = QStandardItem()
            separator.setSizeHint(size)
            view.model().insertRow(x, separator)
            view.model().item(x).setEnabled(False)
        self.combo_title_style.setFocusPolicy(Qt.NoFocus)
        self.combo_title_style.setMaxVisibleItems(view.model().rowCount())
        self.combo_title_style.setItemData(0, "test", QtCore.Qt.ToolTipRole)
        numKey = Qt.Key_1
        index = 0
        title_list = list(self.doc_props.dict_title_styles.keys())
        for key in range(0, 13, 2):
            shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.ALT + numKey), self)
            shortcut.activated.connect(
                partial(self.titleStyleHelper, title_list[key]))
            self.combo_title_style.setItemData(
                index, "Ctrl+Alt+" + str(numKey - Qt.Key_1 + 1),
                QtCore.Qt.ToolTipRole)
            index += 3
            numKey += 1
        shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_0), self)
        shortcut.activated.connect(
            partial(self.titleStyleHelper,
                    self.document.doc_props.text_reset_title))
        self.combo_title_style.setItemData(index, "Ctrl+Alt+0",
                                           QtCore.Qt.ToolTipRole)
        self.combo_title_style.textActivated.connect(self.titleStyleHelper)
        return self.combo_title_style

    def titleStyleHelper(self, state):
        """
        Helper function for title style
        calls function for selected title style type
        :return: returns nothing
        """
        if self.doc_props.text_update_title not in state and \
                self.doc_props.text_reset_title not in state:
            self.document.changeTitleStyle(state)
        elif self.doc_props.text_update_title in state:
            self.document.updateTitleStyle(state)
        else:
            self.document.resetTitleStyle()
            self.combo_title_style.setCurrentIndex(0)

    def makeComboFontStyleBox(self) -> QFontComboBox:
        """
        Create Font Style DropDown
        """
        # ComboBox for font sizes
        self.combo_font_style = QFontComboBox(self)
        self.combo_font_style.setToolTip('Change font')
        self.combo_font_style.setFocusPolicy(Qt.NoFocus)
        self.combo_font_style.currentFontChanged.connect(
            self.document.onFontStyleChanged)
        self.combo_font_style.setCurrentFont(self.document.currentFont())
        return self.combo_font_style

    def makeComboFontSizeBox(self) -> QComboBox:
        """
        Create Font Size Dropdown
        """
        # Adds functionality to the ComboBox
        self.combo_font_size = QComboBox(self)
        self.combo_font_size.setToolTip('Change font size')
        self.combo_font_size.addItems(self.doc_props.list_font_sizes)
        self.combo_font_size.setFixedWidth(60)
        self.combo_font_size.setFocusPolicy(Qt.NoFocus)
        self.combo_font_size.setCurrentIndex(
            self.doc_props.def_font_size_index)
        self.combo_font_size.currentTextChanged.connect(
            self.document.onFontSizeChanged)
        return self.combo_font_size

    def makeBtnBold(self) -> QPushButton:
        """
        Create Bold Btn
        """
        # Button press to make text bold
        self.button_bold = QPushButton("B", self)
        self.button_bold.setToolTip('Bold your text. "Ctrl+B"')
        self.button_bold.setFixedWidth(33)
        self.button_bold.setStyleSheet("QPushButton { font:Bold }")
        self.button_bold.setCheckable(True)
        self.button_bold.setFocusPolicy(Qt.NoFocus)
        self.button_bold.clicked.connect(self.document.onFontBoldChanged)
        return self.button_bold

    def makeBtnItal(self) -> QPushButton:
        """
        Create Ital Btn
        """
        # Button press to make text italic
        self.button_ital = QPushButton("I", self)
        self.button_ital.setToolTip('Italicise your text. "Ctrl+I"')
        self.button_ital.setFixedWidth(33)
        self.button_ital.setStyleSheet("QPushButton { font:Italic }")
        self.button_ital.setCheckable(True)
        self.button_ital.setFocusPolicy(Qt.NoFocus)
        self.button_ital.clicked.connect(self.document.onFontItalChanged)
        return self.button_ital

    def makeBtnStrike(self) -> QPushButton:
        """
        Create Strike Btn
        """
        # Button press to make text strikethrough
        self.button_strike = QPushButton("S", self)
        self.button_strike.setToolTip('Strikeout your text. "Ctrl+Shift+5"')
        self.button_strike.setFixedWidth(33)
        f = self.button_strike.font()
        f.setStrikeOut(True)
        self.button_strike.setFont(f)
        # self.button_strike.adjustSize()
        self.button_strike.setStyleSheet(
            "QPushButton { text-decoration: line-through }")
        self.button_strike.setCheckable(True)
        self.button_strike.setFocusPolicy(Qt.NoFocus)
        self.button_strike.clicked.connect(self.document.onFontStrikeChanged)
        return self.button_strike

    def makeBtnUnder(self) -> QPushButton:
        """
        Create Underline Button
        """
        # Button press to underline text
        self.button_under = QPushButton("U", self)
        self.button_under.setToolTip('Underline your text. "Ctrl+U"')
        self.button_under.setFixedWidth(33)
        self.button_under.setStyleSheet(
            "QPushButton { text-decoration: underline }")
        self.button_under.setCheckable(True)
        self.button_under.setFocusPolicy(Qt.NoFocus)
        self.button_under.clicked.connect(self.document.onFontUnderChanged)
        return self.button_under

    def updateTextColor(self, index: int):
        """
        Updates styles for font color
        """
        color_list = list(self.doc_props.dict_colors.values())
        style = "QComboBox::drop-down { border: 0px;}" \
                "QComboBox { background-color: " + list(color_list)[index] + ";" + \
                "border: 1px solid gray;" \
                "border-radius: 3px;" \
                "selection-background-color: rgba(0,0,0,0.2)}" \
                "QComboBox QAbstractItemView { min-width:30px; }"
        self.combo_text_color.setStyleSheet(style)

    def makeComboFontColor(self) -> QComboBox:
        """
        Create Font Color Dropdown
        """
        # Button to change text color
        self.combo_text_color = QComboBox(self)
        color_list = self.doc_props.dict_colors.values()
        self.combo_text_color.setFixedWidth(35)
        self.combo_text_color.setFixedHeight(20)
        model = self.combo_text_color.model()
        for i, c in enumerate(color_list):
            item = QtGui.QStandardItem()
            item.setBackground(QtGui.QColor(c))
            model.appendRow(item)
            self.combo_text_color.setItemData(i, c)
        self.combo_text_color.currentIndexChanged.connect(
            self.document.onTextColorChanged)
        self.combo_text_color.currentIndexChanged.connect(self.updateTextColor)
        self.combo_text_color.setFocusPolicy(Qt.NoFocus)
        self.combo_text_color.setToolTip("Change Text color.")
        def_index = list(self.doc_props.dict_colors.keys()).index(
            self.doc_props.def_text_color_key)
        self.combo_text_color.setCurrentIndex(def_index)
        self.updateTextColor(self.combo_text_color.currentIndex())
        self.combo_text_color.view().setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)

        return self.combo_text_color

    def makeClearFormatting(self) -> QPushButton:
        """
        Create Clear Formatting Button
        """
        # Button to Clear Formatting
        self.button_clear = QPushButton(html.unescape('&#574;'))
        self.button_clear.setToolTip('Clear Formatting. "Ctrl+0"')
        self.button_clear.setFixedWidth(33)
        self.button_clear.setFocusPolicy(Qt.NoFocus)
        self.button_clear.clicked.connect(
            self.document.clearSelectionFormatting)
        return self.button_clear

    def makeComboTextAlign(self) -> QComboBox:
        """
        Create Text Alignment Dropdown
        """
        # Adds ability to change alignment of text
        self.combo_text_align = QComboBox(self)
        self.combo_text_align.setToolTip('Change text alignment')
        self.combo_text_align.addItems(self.doc_props.dict_text_aligns)
        self.combo_text_align.setFocusPolicy(Qt.NoFocus)
        self.combo_text_align.currentIndexChanged.connect(
            self.document.onTextAlignmentChanged)
        def_index = list(self.doc_props.dict_text_aligns).index(
            self.doc_props.def_text_align_key)
        self.combo_text_align.setCurrentIndex(def_index)
        return self.combo_text_align

    def makeBulletList(self) -> QPushButton:
        """
        Create Bullet List Dropdown
        """
        # Adds ability to change alignment of text
        button_bullet_list = QPushButton(html.unescape('&#8226;'), self)
        button_bullet_list.setToolTip('Bulleted List')
        button_bullet_list.setFixedWidth(33)
        button_bullet_list.setFocusPolicy(Qt.NoFocus)
        button_bullet_list.clicked.connect(self.document.bulletList)
        return button_bullet_list

    def makeBtnFormatMode(self, callback) -> QPushButton:
        """
        Create Enable Format Mode Button
        """
        # Mode Switching button to the very right (after stretch)
        self.button_mode_switch = QPushButton("Formatting Mode", self)

        self.button_mode_switch.setToolTip("Enable Document Formatting")
        # Used to keep button enabled in setFormattingMode
        self.button_mode_switch.setProperty("persistent", True)
        self.button_mode_switch.setCheckable(True)
        self.button_mode_switch.setFocusPolicy(Qt.NoFocus)
        self.button_mode_switch.clicked.connect(callback)
        return self.button_mode_switch

    def setFormattingButtonsEnabled(self, state):
        """
        Sets all formatting options to Enabled or Disabled
        :param state: boolean that sets the states
        :return: returns nothing
        """
        # Toggle the state of all buttons in the menu
        logging.info(str(state))

        a: QWidget
        for a in self.children():
            if not a.property("persistent"):
                a.setEnabled(state)

    def updateFormatOnSelectionChange(self):
        """
        Selected text format reflected in the TopBar
        :return: returns nothing
        """
        # Block signals

        a: QWidget
        for a in self.children():
            if not a.property("persistent"):
                a.blockSignals(True)

        if self.combo_title_style is not None:
            title = self.document.currentCharFormat()
            index = 0
            title_list = list(self.doc_props.dict_title_styles.values())
            # adds separator slots to the list to make the index match the list in topbar
            for x in range(2, 23, 3):
                title_list.insert(x, None)
            if title in title_list:
                index = title_list.index(title)
            self.combo_title_style.setCurrentIndex(index)

        # Update the font style displayed
        if self.combo_font_style is not None:
            self.combo_font_style.setCurrentFont(self.document.currentFont())
        # Update the font size displayed
        if self.combo_font_size is not None:
            size = int(self.document.currentCharFormat().fontPointSize())
            if size != 0:
                size_index = self.doc_props.list_font_sizes.index(str(size))
                self.combo_font_size.setCurrentIndex(size_index)
        # Update extra formatting options
        if self.button_ital is not None:
            self.button_ital.setChecked(self.document.fontItalic())
        if self.button_under is not None:
            self.button_under.setChecked(self.document.fontUnderline())
        if self.button_bold is not None:
            self.button_bold.setChecked(
                self.document.fontWeight() == QFont.Bold)
        if self.button_strike is not None:
            self.button_strike.setChecked(
                self.document.currentCharFormat().fontStrikeOut())
        # update the text color
        if self.combo_text_color is not None:
            color = self.document.currentCharFormat().foreground().color(
            ).name()
            index = 0
            color_list = list(self.doc_props.dict_colors.values())
            if color in color_list:
                index = color_list.index(color)
            self.updateTextColor(index)

        # Update the text alignment
        if self.combo_text_align is not None:
            align = self.document.alignment()
            align_list = list(self.doc_props.dict_text_aligns.values())
            if align in align_list:
                align_index = align_list.index(align)
                self.combo_text_align.setCurrentIndex(align_index)
        # Unblock signals

        a: QWidget
        for a in self.children():
            if not a.property("persistent"):
                a.blockSignals(False)
Exemplo n.º 10
0
class Browser(preferences.Group):
    def __init__(self, page):
        super(Browser, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.languagesLabel = QLabel()
        self.languages = QComboBox(currentIndexChanged=self.changed)
        layout.addWidget(self.languagesLabel, 0, 0)
        layout.addWidget(self.languages, 0, 1)
        
        items = ['', '']
        items.extend(language_names.languageName(l, l) for l in lilydoc.translations)
        self.languages.addItems(items)
        
        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6, 32)
        self.fontSize.setSingleStep(1)
        
        layout.addWidget(self.fontLabel, 1, 0)
        layout.addWidget(self.fontChooser, 1, 1)
        layout.addWidget(self.fontSize, 1, 2)
        
        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("Documentation Browser"))
        self.languagesLabel.setText(_("Preferred Language:"))
        self.languages.setItemText(0, _("Default"))
        self.languages.setItemText(1, _("English (untranslated)"))
        self.fontLabel.setText(_("Font:"))
        
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        lang = s.value("language", "default", str)
        if lang in lilydoc.translations:
            i = lilydoc.translations.index(lang) + 2
        elif lang == "C":
            i = 1
        else:
            i = 0
        self.languages.setCurrentIndex(i)
        
        font = self.font()
        family = s.value("fontfamily", "", str)
        if family:
            font.setFamily(family)
        size = s.value("fontsize", 16, int)
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(size)

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        langs = ['default', 'C'] + lilydoc.translations
        s.setValue("language", langs[self.languages.currentIndex()])
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
Exemplo n.º 11
0
class GTextToolbar(QToolBar):
    """A toolbar for the Editor UI instanciated in a window.
    """

    def __init__(self, parent):
        super().__init__(parent)

        self.editor: GTextEditor = None
        self.setIconSize(QSize(16, 16))

        self._fonts = QFontComboBox(self)
        self.addWidget(self._fonts)

        self._ttype = QComboBox(self)
        self._ttype.addItems([item.comment for item in Format])
        self.addWidget(self._ttype)

        self._mtype = QComboBox(self)
        self._mtype.addItems(["LaTex", "MathML", "Ignore"])
        self.addWidget(self._mtype)

        self._fsize = QComboBox(self)
        self._fsize.addItems(["7", "8", "9", "10", "11", "12", "13", "14",
                              "18", "24", "36", "48", "64"])
        self.addWidget(self._fsize)
        self.addSeparator()

        self._bold = QAction(QIcon(f"{IMG_PATH}/bold.png"), "Bold", self)
        self._bold.setShortcut(QKeySequence.Bold)
        self._bold.setCheckable(True)
        self.addAction(self._bold)

        self._italic = QAction(QIcon(f"{IMG_PATH}/italic.png"), "Italic", self)
        self._italic.setShortcut(QKeySequence.Italic)
        self._italic.setCheckable(True)
        self.addAction(self._italic)

        self._underline = QAction(QIcon(f"{IMG_PATH}/underline.png"),
                                  "Underline", self)
        self._underline.setShortcut(QKeySequence.Underline)
        self._underline.setCheckable(True)
        self.addAction(self._underline)
        self.addSeparator()

        self._alignl = QAction(QIcon(f"{IMG_PATH}/alignment.png"),
                               "Align left", self)
        self._alignl.setCheckable(True)
        self.addAction(self._alignl)

        self._alignc = QAction(QIcon(f"{IMG_PATH}/align_center.png"),
                               "Align center", self)
        self._alignc.setCheckable(True)
        self.addAction(self._alignc)

        self._alignr = QAction(QIcon(f"{IMG_PATH}/align_right.png"),
                               "Align right", self)
        self._alignr.setCheckable(True)
        self.addAction(self._alignr)

        self._alignj = QAction(QIcon(f"{IMG_PATH}/align_justify.png"),
                               "Justify", self)
        self._alignj.setCheckable(True)
        self.addAction(self._alignj)

        format_group = QActionGroup(self)
        format_group.setExclusive(True)
        format_group.addAction(self._alignl)
        format_group.addAction(self._alignc)
        format_group.addAction(self._alignr)
        format_group.addAction(self._alignj)

        self._wrap = QAction(QIcon(f"{IMG_PATH}/wrap.png"),
                             "Wrap text to window", self)
        self._wrap.setStatusTip("Toggle wrap text to window")
        self._wrap.setCheckable(True)
        self._wrap.setChecked(True)
        self.addAction(self._wrap)
        self.addSeparator()

        self._html = QAction(QIcon(f"{IMG_PATH}/html.png"),
                             "Selected text as HTML", self)
        self._html.setCheckable(False)
        self._html.triggered.connect(self.__to_html)
        self.addAction(self._html)

        # Format-related widgets/actions, used to disable/enable signals.
        self._format_actions = [self._fonts, self._fsize, self._bold,
                                self._underline, self._italic]
        # No need to disable signals for alignment, as they are paragraph-wide.
        self.setFocusPolicy(Qt.ClickFocus)
        self.setDisabled(True)

    def __align_left(self):
        self.editor.setAlignment(Qt.AlignLeft)

    def __align_center(self):
        self.editor.setAlignment(Qt.AlignCenter)

    def __align_right(self):
        self.editor.setAlignment(Qt.AlignRight)

    def __align_justf(self):
        self.editor.setAlignment(Qt.AlignJustify)

    def __wrap_text(self):
        self.editor.setLineWrapMode(int(self.editor.lineWrapMode() == 0))

    def __to_html(self):
        text = self.editor.textCursor().selectedText()
        self.editor.textCursor().insertHtml(text)

    def hasFocus(self) -> bool:  # pylint: disable=C0103
        """_summary_

        Returns:
            bool: _description_
        """
        return super().hasFocus() or self._fonts.hasFocus() or \
            self._fsize.hasFocus() or self._mtype.hasFocus() or \
            self._ttype.hasFocus()

    def update_editor(self, text_editor: GTextEditor) -> None:
        """Update the font format toolbar/actions when a new text selection
        is made. This is neccessary to keep toolbars/etc. in sync with the
        current edit state.
        """
        self.setDisabled(text_editor is None)
        if text_editor == self.editor:
            return
        if self.editor is not None:
            self._ttype.currentIndexChanged.disconnect()
            self._fonts.currentFontChanged.disconnect()
            self._fsize.currentIndexChanged[str].disconnect()
            self._bold.toggled.disconnect()
            self._underline.toggled.disconnect()
            self._italic.toggled.disconnect()
            self._alignl.triggered.disconnect()
            self._alignc.triggered.disconnect()
            self._alignr.triggered.disconnect()
            self._alignj.triggered.disconnect()
            self._wrap.triggered.disconnect()
        self.editor = text_editor
        if self.editor is not None:
            for _obj in self._format_actions:
                _obj.blockSignals(True)
            self._fonts.setCurrentFont(self.editor.currentFont())
            self._fsize.setCurrentText(str(int(self.editor.fontPointSize())))
            self._italic.setChecked(self.editor.fontItalic())
            self._underline.setChecked(self.editor.fontUnderline())
            self._bold.setChecked(self.editor.fontWeight() == QFont.Bold)
            self._alignl.setChecked(self.editor.alignment() == Qt.AlignLeft)
            self._alignc.setChecked(self.editor.alignment() == Qt.AlignCenter)
            self._alignr.setChecked(self.editor.alignment() == Qt.AlignRight)
            self._alignj.setChecked(self.editor.alignment() == Qt.AlignJustify)
            self._ttype.setCurrentText(self.editor.get_formatting())
            #self._mtype
            for _obj in self._format_actions:
                _obj.blockSignals(False)
            self._ttype.currentIndexChanged.connect(self.editor.update_fmt)
            self._fonts.currentFontChanged.connect(self.editor.setCurrentFont)
            self._underline.toggled.connect(self.editor.setFontUnderline)
            self._italic.toggled.connect(self.editor.setFontItalic)
            self._fsize.currentIndexChanged[str].connect(
                    lambda s: self.editor.setFontPointSize(float(s)))
            self._bold.toggled.connect(lambda x: self.editor.setFontWeight(
                    QFont.Bold if x else QFont.Normal))
            self._alignl.triggered.connect(self.__align_left)
            self._alignc.triggered.connect(self.__align_center)
            self._alignr.triggered.connect(self.__align_right)
            self._alignj.triggered.connect(self.__align_justf)
            self._wrap.triggered.connect(self.__wrap_text)
Exemplo n.º 12
0
class Browser(preferences.Group):
    def __init__(self, page):
        super(Browser, self).__init__(page)

        layout = QGridLayout()
        self.setLayout(layout)

        self.languagesLabel = QLabel()
        self.languages = QComboBox(currentIndexChanged=self.changed)
        layout.addWidget(self.languagesLabel, 0, 0)
        layout.addWidget(self.languages, 0, 1)

        items = ['', '']
        items.extend(
            language_names.languageName(l, l) for l in lilydoc.translations)
        self.languages.addItems(items)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6, 32)
        self.fontSize.setSingleStep(1)

        layout.addWidget(self.fontLabel, 1, 0)
        layout.addWidget(self.fontChooser, 1, 1)
        layout.addWidget(self.fontSize, 1, 2)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Documentation Browser"))
        self.languagesLabel.setText(_("Preferred Language:"))
        self.languages.setItemText(0, _("Default"))
        self.languages.setItemText(1, _("English (untranslated)"))
        self.fontLabel.setText(_("Font:"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        lang = s.value("language", "default", str)
        if lang in lilydoc.translations:
            i = lilydoc.translations.index(lang) + 2
        elif lang == "C":
            i = 1
        else:
            i = 0
        self.languages.setCurrentIndex(i)

        font = self.font()
        family = s.value("fontfamily", "", str)
        if family:
            font.setFamily(family)
        size = s.value("fontsize", 16, int)
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(size)

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        langs = ['default', 'C'] + lilydoc.translations
        s.setValue("language", langs[self.languages.currentIndex()])
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
Exemplo n.º 13
0
class TextoEnriquecido(QWidget):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.path holds the path of the currently open file.
        # If none, we haven't got a file open yet (or creating new).
        self.path = None

        self.setupUi()
        self.conectarWidgets()

    def setupUi(self):
        layoutPpal = QVBoxLayout(self)

        layoutToolBar = QHBoxLayout()
        edit_toolbar = QToolBar("Editar")
        edit_toolbar.setIconSize(QSize(16, 16))

        self.undo_action = QAction(QIcon(imagen('arrow-curve-180-left.png')), "Deshacer", self)
        self.undo_action.setStatusTip("Deshacer ultimo cambio")
        edit_toolbar.addAction(self.undo_action)

        self.redo_action = QAction(QIcon(imagen('arrow-curve.png')), "Rehacer", self)
        self.redo_action.setStatusTip("Rehacer ultimo cambio")
        edit_toolbar.addAction(self.redo_action)

        self.cut_action = QAction(QIcon(imagen('scissors.png')), "Cortar", self)
        self.cut_action.setStatusTip("Cortar texto seleccionado")
        self.cut_action.setShortcut(QKeySequence.Cut)
        edit_toolbar.addAction(self.cut_action)

        self.copy_action = QAction(QIcon(imagen('document-copy.png')), "Copiar", self)
        self.copy_action.setStatusTip("Copia texto seleccionado")
        self.copy_action.setShortcut(QKeySequence.Copy)
        edit_toolbar.addAction(self.copy_action)

        self.paste_action = QAction(QIcon(imagen('clipboard-paste-document-text.png')), "Pegar", self)
        self.paste_action.setStatusTip("Pegar desde ")
        self.paste_action.setShortcut(QKeySequence.Paste)
        edit_toolbar.addAction(self.paste_action)

        self.select_action = QAction(QIcon(imagen('selection-input.png')), "Seleccionar todo", self)
        self.select_action.setStatusTip("Seleccionar todo el texto")
        self.select_action.setShortcut(QKeySequence.SelectAll)
        edit_toolbar.addAction(self.select_action)

        self.wrap_action = QAction(QIcon(imagen('arrow-continue.png')), "Ajusta el texto a la ventana", self)
        self.wrap_action.setStatusTip("Ajusta/desajusta el texto a la ventana")
        self.wrap_action.setCheckable(True)
        self.wrap_action.setChecked(True)
        edit_toolbar.addAction(self.wrap_action)

        layoutToolBar.addWidget(edit_toolbar)

        toolbar_formato = QToolBar("Formato")
        toolbar_formato.setIconSize(QSize(16, 16))

        self.fonts = QFontComboBox()
        toolbar_formato.addWidget(self.fonts)

        self.fontsize = QComboBox()
        self.fontsize.addItems([str(s) for s in FONT_SIZES])
        toolbar_formato.addWidget(self.fontsize)

        self.bold_action = QAction(QIcon(imagen('edit-bold.png')), "Negrita", self)
        self.bold_action.setStatusTip("Negrita")
        self.bold_action.setShortcut(QKeySequence.Bold)
        self.bold_action.setCheckable(True)
        toolbar_formato.addAction(self.bold_action)

        self.italic_action = QAction(QIcon(imagen('edit-italic.png')), "Italica", self)
        self.italic_action.setStatusTip("Italica")
        self.italic_action.setShortcut(QKeySequence.Italic)
        self.italic_action.setCheckable(True)
        toolbar_formato.addAction(self.italic_action)

        self.underline_action = QAction(QIcon(imagen('edit-underline.png')), "Subrayado", self)
        self.underline_action.setStatusTip("Subrayado")
        self.underline_action.setShortcut(QKeySequence.Underline)
        self.underline_action.setCheckable(True)
        toolbar_formato.addAction(self.underline_action)

        self.alignl_action = QAction(QIcon(imagen('edit-alignment.png')), "Alinear izquierda", self)
        self.alignl_action.setStatusTip("Alinear texto a la izquierda")
        self.alignl_action.setCheckable(True)
        toolbar_formato.addAction(self.alignl_action)

        self.alignc_action = QAction(QIcon(imagen('edit-alignment-center.png')), "Alinear centrado", self)
        self.alignc_action.setStatusTip("Alineacion centrada del texto")
        self.alignc_action.setCheckable(True)
        toolbar_formato.addAction(self.alignc_action)

        self.alignr_action = QAction(QIcon(imagen('edit-alignment-right.png')), "Alinear derecha", self)
        self.alignr_action.setStatusTip("Alinear texto a la derecha")
        self.alignr_action.setCheckable(True)
        toolbar_formato.addAction(self.alignr_action)

        self.alignj_action = QAction(QIcon(imagen('edit-alignment-justify.png')), "Justificar", self)
        self.alignj_action.setStatusTip("Texto justificado")
        self.alignj_action.setCheckable(True)
        toolbar_formato.addAction(self.alignj_action)

        format_group = QActionGroup(self)
        format_group.setExclusive(True)
        format_group.addAction(self.alignl_action)
        format_group.addAction(self.alignc_action)
        format_group.addAction(self.alignr_action)
        format_group.addAction(self.alignj_action)

        layoutToolBar.addWidget(toolbar_formato)

        layoutPpal.addLayout(layoutToolBar)
        self.editor = TextEdit(tamanio=10)
        self.editor.setAutoFormatting(QTextEdit.AutoAll)
        # Initialize default font size.
        font = QFont('Times', 12)
        self.editor.setFont(font)
        # We need to repeat the size to init the current format.
        self.editor.setFontPointSize(12)

        layoutPpal.addWidget(self.editor)

        # A list of all format-related widgets/actions, so we can disable/enable signals when updating.
        self._format_actions = [
            self.fonts,
            self.fontsize,
            self.bold_action,
            self.italic_action,
            self.underline_action,
            # We don't need to disable signals for alignment, as they are paragraph-wide.
        ]

        # Initialize.
        self.update_format()

    def conectarWidgets(self):
        self.fonts.currentFontChanged.connect(self.editor.setCurrentFont)
        self.editor.selectionChanged.connect(self.update_format)
        self.undo_action.triggered.connect(self.editor.undo)
        self.redo_action.triggered.connect(self.editor.redo)
        self.cut_action.triggered.connect(self.editor.cut)
        self.copy_action.triggered.connect(self.editor.copy)
        self.paste_action.triggered.connect(self.editor.paste)
        self.select_action.triggered.connect(self.editor.selectAll)
        self.wrap_action.triggered.connect(self.edit_toggle_wrap)
        # Connect to the signal producing the text of the current selection. Convert the string to float
        # and set as the pointsize. We could also use the index + retrieve from FONT_SIZES.
        self.fontsize.currentIndexChanged[str].connect(lambda s: self.editor.setFontPointSize(float(s)) )
        self.bold_action.toggled.connect(lambda x: self.editor.setFontWeight(QFont.Bold if x else QFont.Normal))
        self.italic_action.toggled.connect(self.editor.setFontItalic)
        self.underline_action.toggled.connect(self.editor.setFontUnderline)
        self.alignl_action.triggered.connect(lambda: self.editor.setAlignment(Qt.AlignLeft))
        self.alignc_action.triggered.connect(lambda: self.editor.setAlignment(Qt.AlignCenter))
        self.alignr_action.triggered.connect(lambda: self.editor.setAlignment(Qt.AlignRight))
        self.alignj_action.triggered.connect(lambda: self.editor.setAlignment(Qt.AlignJustify))

    def block_signals(self, objects, b):
        for o in objects:
            o.blockSignals(b)

    def update_format(self):
        """
        Update the font format toolbar/actions when a new text selection is made. This is neccessary to keep
        toolbars/etc. in sync with the current edit state.
        :return:
        """
        # Disable signals for all format widgets, so changing values here does not trigger further formatting.
        self.block_signals(self._format_actions, True)

        self.fonts.setCurrentFont(self.editor.currentFont())
        # Nasty, but we get the font-size as a float but want it was an int
        self.fontsize.setCurrentText(str(int(self.editor.fontPointSize())))

        self.italic_action.setChecked(self.editor.fontItalic())
        self.underline_action.setChecked(self.editor.fontUnderline())
        self.bold_action.setChecked(self.editor.fontWeight() == QFont.Bold)

        self.alignl_action.setChecked(self.editor.alignment() == Qt.AlignLeft)
        self.alignc_action.setChecked(self.editor.alignment() == Qt.AlignCenter)
        self.alignr_action.setChecked(self.editor.alignment() == Qt.AlignRight)
        self.alignj_action.setChecked(self.editor.alignment() == Qt.AlignJustify)

        self.block_signals(self._format_actions, False)

    def edit_toggle_wrap(self):
        self.editor.setLineWrapMode( 1 if self.editor.lineWrapMode() == 0 else 0 )

    def file_open(self, archivo=''):
        # path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "HTML documents (*.html);Text documents (*.txt);All files (*.*)")
        path = archivo
        try:
            with open(path, 'rU') as f:
                text = f.read()

        except Exception as e:
            self.dialog_critical(str(e))

        else:
            self.path = path
            # Qt will automatically try and guess the format as txt/html
            self.editor.setText(text)
            # self.update_title()

    def file_save(self, path=None):
        self.path = path
        if self.path is None:
            # If we do not have a path, we need to use Save As.
            return self.file_saveas()

        text = self.editor.toHtml() if splitext(self.path) in HTML_EXTENSIONS else self.editor.toPlainText()

        try:
            with open(self.path, 'w') as f:
                f.write(text)

        except Exception as e:
            self.dialog_critical(str(e))

    def file_saveas(self, path=None):
        if not path:
            # If dialog is cancelled, will return ''
            return

        text = self.editor.toHtml() if splitext(path) in HTML_EXTENSIONS else self.editor.toPlainText()

        try:
            with open(path, 'w') as f:
                f.write(text)

        except Exception as e:
            self.dialog_critical(str(e))

        else:
            self.path = path
            # self.update_title()

    def dialog_critical(self, s):
        dlg = QMessageBox(self)
        dlg.setText(s)
        dlg.setIcon(QMessageBox.Critical)
        dlg.show()

    def toHtml(self):
        return self.editor.toHtml()

    def toPlainText(self):
        return self.editor.toPlainText()
Exemplo n.º 14
0
class FontsColors(preferences.Page):
    def __init__(self, dialog):
        super(FontsColors, self).__init__(dialog)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        
        self.scheme = SchemeSelector(self)
        layout.addWidget(self.scheme)
        
        self.printScheme = QCheckBox()
        layout.addWidget(self.printScheme)
        
        hbox = QHBoxLayout()
        self.tree = QTreeWidget(self)
        self.tree.setHeaderHidden(True)
        self.tree.setAnimated(True)
        self.stack = QStackedWidget(self)
        hbox.addWidget(self.tree)
        hbox.addWidget(self.stack)
        layout.addLayout(hbox)
        
        hbox = QHBoxLayout()
        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox()
        self.fontSize = QDoubleSpinBox()
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)
        hbox.addWidget(self.fontLabel)
        hbox.addWidget(self.fontChooser, 1)
        hbox.addWidget(self.fontSize)
        layout.addLayout(hbox)
        
        # add the items to our list
        self.baseColorsItem = i = QTreeWidgetItem()
        self.tree.addTopLevelItem(i)
        self.defaultStylesItem = i = QTreeWidgetItem()
        self.tree.addTopLevelItem(i)
        
        self.defaultStyles = {}
        for name in textformats.defaultStyles:
            self.defaultStyles[name] = i = QTreeWidgetItem()
            self.defaultStylesItem.addChild(i)
            i.name = name
        self.defaultStylesItem.setExpanded(True)
        
        self.allStyles = {}
        for group, styles in ly.colorize.default_mapping():
            i = QTreeWidgetItem()
            children = {}
            self.allStyles[group] = (i, children)
            self.tree.addTopLevelItem(i)
            i.group = group
            for name, base, clss in styles:
                j = QTreeWidgetItem()
                j.name = name
                j.base = base
                i.addChild(j)
                children[name] = j
        
        self.baseColorsWidget = BaseColors(self)
        self.customAttributesWidget = CustomAttributes(self)
        self.emptyWidget = QWidget(self)
        self.stack.addWidget(self.baseColorsWidget)
        self.stack.addWidget(self.customAttributesWidget)
        self.stack.addWidget(self.emptyWidget)
        
        self.tree.currentItemChanged.connect(self.currentItemChanged)
        self.tree.setCurrentItem(self.baseColorsItem)
        self.scheme.currentChanged.connect(self.currentSchemeChanged)
        self.scheme.changed.connect(self.changed)
        self.baseColorsWidget.changed.connect(self.baseColorsChanged)
        self.customAttributesWidget.changed.connect(self.customAttributesChanged)
        self.fontChooser.currentFontChanged.connect(self.fontChanged)
        self.fontSize.valueChanged.connect(self.fontChanged)
        self.printScheme.clicked.connect(self.printSchemeChanged)
        
        app.translateUI(self)
        
    def translateUI(self):
        self.printScheme.setText(_("Use this scheme for printing"))
        self.fontLabel.setText(_("Font:"))
        self.baseColorsItem.setText(0, _("Base Colors"))
        self.defaultStylesItem.setText(0, _("Default Styles"))
        
        self.defaultStyleNames = defaultStyleNames()
        self.allStyleNames = allStyleNames()
        
        for name in textformats.defaultStyles:
            self.defaultStyles[name].setText(0, self.defaultStyleNames[name])
        for group, styles in ly.colorize.default_mapping():
            try:
                n = self.allStyleNames[group][0]
            except KeyError:
                n = group
            self.allStyles[group][0].setText(0, n)
            for name, base, clss in styles:
                try:
                    n = self.allStyleNames[group][1][name]
                except KeyError:
                    n = name
                self.allStyles[group][1][name].setText(0, n)
            
    def currentItemChanged(self, item, previous):
        if item is self.baseColorsItem:
            self.stack.setCurrentWidget(self.baseColorsWidget)
        elif not item.parent():
            self.stack.setCurrentWidget(self.emptyWidget)
        else:
            data = self.data[self.scheme.currentScheme()]
            w = self.customAttributesWidget
            self.stack.setCurrentWidget(w)
            toptext = None
            if item.parent() is self.defaultStylesItem:
                # default style
                w.setTitle(item.text(0))
                w.setTristate(False)
                w.setTextFormat(data.defaultStyles[item.name])
            else:
                # specific style of specific group
                group, name = item.parent().group, item.name
                w.setTitle("{0}: {1}".format(item.parent().text(0), item.text(0)))
                inherit = item.base
                if inherit:
                    toptext = _("(Inherits: {name})").format(name=self.defaultStyleNames[inherit])
                w.setTristate(bool(inherit))
                w.setTextFormat(data.allStyles[group][name])
            w.setTopText(toptext)
    
    def currentSchemeChanged(self):
        scheme = self.scheme.currentScheme()
        if scheme not in self.data:
            self.data[scheme] = textformats.TextFormatData(scheme)
        self.updateDisplay()
        if self.tree.currentItem():
            self.currentItemChanged(self.tree.currentItem(), None)
        with qutil.signalsBlocked(self.printScheme):
            self.printScheme.setChecked(scheme == self._printScheme)
    
    def fontChanged(self):
        data = self.data[self.scheme.currentScheme()]
        data.font = self.fontChooser.currentFont()
        data.font.setPointSizeF(self.fontSize.value())
        self.updateDisplay()
        self.changed.emit()
    
    def printSchemeChanged(self):
        if self.printScheme.isChecked():
            self._printScheme = self.scheme.currentScheme()
        else:
            self._printScheme = None
        self.changed.emit()
    
    def addSchemeData(self, scheme, tfd):
        self.data[scheme] = tfd
        
    def currentSchemeData(self):
        return self.data[self.scheme.currentScheme()]
        
    def updateDisplay(self):
        data = self.data[self.scheme.currentScheme()]
        
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(data.font)
            self.fontSize.setValue(data.font.pointSizeF())
        
        with qutil.signalsBlocked(self):
            # update base colors
            for name in textformats.baseColors:
                self.baseColorsWidget.color[name].setColor(data.baseColors[name])
        
        # update base colors for whole treewidget
        p = QApplication.palette()
        p.setColor(QPalette.Base, data.baseColors['background'])
        p.setColor(QPalette.Text, data.baseColors['text'])
        p.setColor(QPalette.Highlight, data.baseColors['selectionbackground'])
        p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext'])
        self.tree.setPalette(p)
        
        def setItemTextFormat(item, f):
            font = QFont(data.font)
            if f.hasProperty(QTextFormat.ForegroundBrush):
                item.setForeground(0, f.foreground().color())
            else:
                item.setForeground(0, data.baseColors['text'])
            if f.hasProperty(QTextFormat.BackgroundBrush):
                item.setBackground(0, f.background().color())
            else:
                item.setBackground(0, QBrush())
            font.setWeight(f.fontWeight())
            font.setItalic(f.fontItalic())
            font.setUnderline(f.fontUnderline())
            item.setFont(0, font)
            
        # update looks of default styles
        for name in textformats.defaultStyles:
            setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name])
        
        # update looks of all the specific styles
        for group, styles in ly.colorize.default_mapping():
            children = self.allStyles[group][1]
            for name, inherit, clss in styles:
                f = QTextCharFormat(data.defaultStyles[inherit]) if inherit else QTextCharFormat()
                f.merge(data.allStyles[group][name])
                setItemTextFormat(children[name], f)
        
    def baseColorsChanged(self, name):
        # keep data up to date with base colors
        data = self.data[self.scheme.currentScheme()]
        data.baseColors[name] = self.baseColorsWidget.color[name].color()
        self.updateDisplay()
        self.changed.emit()
    
    def customAttributesChanged(self):
        item = self.tree.currentItem()
        if not item or not item.parent():
            return
        data = self.data[self.scheme.currentScheme()]
        if item.parent() is self.defaultStylesItem:
            # a default style has been changed
            data.defaultStyles[item.name] = self.customAttributesWidget.textFormat()
        else:
            # a specific style has been changed
            group, name = item.parent().group, item.name
            data.allStyles[group][name] = self.customAttributesWidget.textFormat()
        self.updateDisplay()
        self.changed.emit()
        
    def import_(self, filename):
        from . import import_export
        import_export.importTheme(filename, self, self.scheme)
        
    def export(self, name, filename):
        from . import import_export
        try:
            import_export.exportTheme(self, name, filename)
        except (IOError, OSError) as e:
            QMessageBox.critical(self, _("Error"), _(
                "Can't write to destination:\n\n{url}\n\n{error}").format(
                url=filename, error=e.strerror))
    
    def loadSettings(self):
        self.data = {} # holds all data with scheme as key
        self._printScheme = QSettings().value("printer_scheme", "default", str)
        self.scheme.loadSettings("editor_scheme", "editor_schemes")
        
    def saveSettings(self):
        self.scheme.saveSettings("editor_scheme", "editor_schemes", "fontscolors")
        for scheme in self.scheme.schemes():
            if scheme in self.data:
                self.data[scheme].save(scheme)
        if self._printScheme:
            QSettings().setValue("printer_scheme", self._printScheme)
        else:
            QSettings().remove("printer_scheme")
Exemplo n.º 15
0
class comic_export_setting_dialog(QDialog):
    acbfStylesList = [
        "speech", "commentary", "formal", "letter", "code", "heading", "audio",
        "thought", "sign", "sound", "emphasis", "strong"
    ]

    def __init__(self):
        super().__init__()
        self.setLayout(QVBoxLayout())
        self.setWindowTitle(i18n("Export settings"))
        buttons = QDialogButtonBox(QDialogButtonBox.Ok
                                   | QDialogButtonBox.Cancel)

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        mainWidget = QTabWidget()
        self.layout().addWidget(mainWidget)
        self.layout().addWidget(buttons)

        # Set basic crop settings
        # Set which layers to remove before export.
        mainExportSettings = QWidget()
        mainExportSettings.setLayout(QVBoxLayout())
        groupExportCrop = QGroupBox(i18n("Crop settings"))
        formCrop = QFormLayout()
        groupExportCrop.setLayout(formCrop)
        self.chk_toOutmostGuides = QCheckBox(i18n("Crop to outmost guides"))
        self.chk_toOutmostGuides.setChecked(True)
        self.chk_toOutmostGuides.setToolTip(
            i18n(
                "This will crop to the outmost guides if possible and otherwise use the underlying crop settings."
            ))
        formCrop.addRow("", self.chk_toOutmostGuides)
        btn_fromSelection = QPushButton(
            i18n("Set margins from active selection"))
        btn_fromSelection.clicked.connect(self.slot_set_margin_from_selection)
        # This doesn't work.
        formCrop.addRow("", btn_fromSelection)
        self.spn_marginLeft = QSpinBox()
        self.spn_marginLeft.setMaximum(99999)
        self.spn_marginLeft.setSuffix(" px")
        formCrop.addRow(i18n("Left:"), self.spn_marginLeft)
        self.spn_marginTop = QSpinBox()
        self.spn_marginTop.setMaximum(99999)
        self.spn_marginTop.setSuffix(" px")
        formCrop.addRow(i18n("Top:"), self.spn_marginTop)
        self.spn_marginRight = QSpinBox()
        self.spn_marginRight.setMaximum(99999)
        self.spn_marginRight.setSuffix(" px")
        formCrop.addRow(i18n("Right:"), self.spn_marginRight)
        self.spn_marginBottom = QSpinBox()
        self.spn_marginBottom.setMaximum(99999)
        self.spn_marginBottom.setSuffix(" px")
        formCrop.addRow(i18n("Bottom:"), self.spn_marginBottom)
        groupExportLayers = QGroupBox(i18n("Layers"))
        formLayers = QFormLayout()
        groupExportLayers.setLayout(formLayers)
        self.cmbLabelsRemove = labelSelector()
        formLayers.addRow(i18n("Label for removal:"), self.cmbLabelsRemove)
        self.ln_text_layer_name = QLineEdit()
        self.ln_text_layer_name.setToolTip(
            i18n(
                "These are keywords that can be used to identify text layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated."
            ))
        self.ln_panel_layer_name = QLineEdit()
        self.ln_panel_layer_name.setToolTip(
            i18n(
                "These are keywords that can be used to identify panel layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated."
            ))
        formLayers.addRow(i18n("Text Layer Key:"), self.ln_text_layer_name)
        formLayers.addRow(i18n("Panel Layer Key:"), self.ln_panel_layer_name)

        mainExportSettings.layout().addWidget(groupExportCrop)
        mainExportSettings.layout().addWidget(groupExportLayers)
        mainWidget.addTab(mainExportSettings, i18n("General"))

        # CBZ, crop, resize, which metadata to add.
        CBZexportSettings = QWidget()
        CBZexportSettings.setLayout(QVBoxLayout())
        self.CBZactive = QCheckBox(i18n("Export to CBZ"))
        CBZexportSettings.layout().addWidget(self.CBZactive)
        self.CBZgroupResize = comic_export_resize_widget("CBZ")
        CBZexportSettings.layout().addWidget(self.CBZgroupResize)
        self.CBZactive.clicked.connect(self.CBZgroupResize.setEnabled)
        CBZgroupMeta = QGroupBox(i18n("Metadata to add"))
        # CBZexportSettings.layout().addWidget(CBZgroupMeta)
        CBZgroupMeta.setLayout(QFormLayout())

        mainWidget.addTab(CBZexportSettings, "CBZ")

        # ACBF, crop, resize, creator name, version history, panel layer, text layers.
        ACBFExportSettings = QWidget()
        ACBFform = QFormLayout()
        ACBFExportSettings.setLayout(QVBoxLayout())
        ACBFdocInfo = QGroupBox()
        ACBFdocInfo.setTitle(i18n("ACBF Document Info"))
        ACBFdocInfo.setLayout(ACBFform)
        self.lnACBFSource = QLineEdit()
        self.lnACBFSource.setToolTip(
            i18n(
                "Whether the acbf file is an adaption of an existing source, and if so, how to find information about that source. So for example, for an adapted webcomic, the official website url should go here."
            ))
        self.lnACBFID = QLabel()
        self.lnACBFID.setToolTip(
            i18n(
                "By default this will be filled with a generated universal unique identifier. The ID by itself is merely so that comic book library management programs can figure out if this particular comic is already in their database and whether it has been rated. Of course, the UUID can be changed into something else by manually changing the json, but this is advanced usage."
            ))
        self.spnACBFVersion = QSpinBox()
        self.ACBFhistoryModel = QStandardItemModel()
        acbfHistoryList = QListView()
        acbfHistoryList.setModel(self.ACBFhistoryModel)
        btn_add_history = QPushButton(i18n("Add history entry"))
        btn_add_history.clicked.connect(self.slot_add_history_item)
        self.chkIncludeTranslatorComments = QCheckBox()
        self.chkIncludeTranslatorComments.setText(
            i18n("Include Translator's Comments"))
        self.chkIncludeTranslatorComments.setToolTip(
            i18n(
                "A PO file can contain translator's comments. If this is checked, the translations comments will be added as references into the ACBF file."
            ))
        self.lnTranslatorHeader = QLineEdit()

        ACBFform.addRow(i18n("Source:"), self.lnACBFSource)
        ACBFform.addRow(i18n("ACBF UID:"), self.lnACBFID)
        ACBFform.addRow(i18n("Version:"), self.spnACBFVersion)
        ACBFform.addRow(i18n("Version History:"), acbfHistoryList)
        ACBFform.addRow("", btn_add_history)
        ACBFform.addRow("", self.chkIncludeTranslatorComments)
        ACBFform.addRow(i18n("Translator Header:"), self.lnTranslatorHeader)

        ACBFAuthorInfo = QWidget()
        acbfAVbox = QVBoxLayout(ACBFAuthorInfo)
        infoLabel = QLabel(
            i18n(
                "The people responsible for the generation of the CBZ/ACBF files."
            ))
        infoLabel.setWordWrap(True)
        ACBFAuthorInfo.layout().addWidget(infoLabel)
        self.ACBFauthorModel = QStandardItemModel(0, 6)
        labels = [
            i18n("Nick Name"),
            i18n("Given Name"),
            i18n("Middle Name"),
            i18n("Family Name"),
            i18n("Email"),
            i18n("Homepage")
        ]
        self.ACBFauthorModel.setHorizontalHeaderLabels(labels)
        self.ACBFauthorTable = QTableView()
        acbfAVbox.addWidget(self.ACBFauthorTable)
        self.ACBFauthorTable.setModel(self.ACBFauthorModel)
        self.ACBFauthorTable.verticalHeader().setDragEnabled(True)
        self.ACBFauthorTable.verticalHeader().setDropIndicatorShown(True)
        self.ACBFauthorTable.verticalHeader().setSectionsMovable(True)
        self.ACBFauthorTable.verticalHeader().sectionMoved.connect(
            self.slot_reset_author_row_visual)
        AuthorButtons = QHBoxLayout()
        btn_add_author = QPushButton(i18n("Add author"))
        btn_add_author.clicked.connect(self.slot_add_author)
        AuthorButtons.addWidget(btn_add_author)
        btn_remove_author = QPushButton(i18n("Remove author"))
        btn_remove_author.clicked.connect(self.slot_remove_author)
        AuthorButtons.addWidget(btn_remove_author)
        acbfAVbox.addLayout(AuthorButtons)

        ACBFStyle = QWidget()
        ACBFStyle.setLayout(QHBoxLayout())
        self.ACBFStylesModel = QStandardItemModel()
        self.ACBFStyleClass = QListView()
        self.ACBFStyleClass.setModel(self.ACBFStylesModel)
        ACBFStyle.layout().addWidget(self.ACBFStyleClass)
        ACBFStyleEdit = QWidget()
        ACBFStyleEditVB = QVBoxLayout(ACBFStyleEdit)
        self.ACBFfontCombo = QFontComboBox()
        self.ACBFdefaultFont = QComboBox()
        self.ACBFdefaultFont.addItems(
            ["sans-serif", "serif", "monospace", "cursive", "fantasy"])
        self.ACBFBold = QCheckBox(i18n("Bold"))
        self.ACBFItal = QCheckBox(i18n("Italic"))
        self.ACBFStyleClass.clicked.connect(self.slot_set_style)
        self.ACBFStyleClass.selectionModel().selectionChanged.connect(
            self.slot_set_style)
        self.ACBFStylesModel.itemChanged.connect(self.slot_set_style)
        self.ACBFfontCombo.currentFontChanged.connect(
            self.slot_font_current_style)
        self.ACBFfontCombo.setEditable(False)
        self.ACBFBold.toggled.connect(self.slot_font_current_style)
        self.ACBFItal.toggled.connect(self.slot_font_current_style)
        colorWidget = QGroupBox(self)
        colorWidget.setTitle(i18n("Text Colors"))
        colorWidget.setLayout(QVBoxLayout())
        self.regularColor = QColorDialog()
        self.invertedColor = QColorDialog()
        self.btn_acbfRegColor = QPushButton(i18n("Regular Text"), self)
        self.btn_acbfRegColor.clicked.connect(self.slot_change_regular_color)
        self.btn_acbfInvColor = QPushButton(i18n("Inverted Text"), self)
        self.btn_acbfInvColor.clicked.connect(self.slot_change_inverted_color)
        colorWidget.layout().addWidget(self.btn_acbfRegColor)
        colorWidget.layout().addWidget(self.btn_acbfInvColor)
        ACBFStyleEditVB.addWidget(colorWidget)
        ACBFStyleEditVB.addWidget(self.ACBFfontCombo)
        ACBFStyleEditVB.addWidget(self.ACBFdefaultFont)
        ACBFStyleEditVB.addWidget(self.ACBFBold)
        ACBFStyleEditVB.addWidget(self.ACBFItal)
        ACBFStyleEditVB.addStretch()
        ACBFStyle.layout().addWidget(ACBFStyleEdit)

        ACBFTabwidget = QTabWidget()
        ACBFTabwidget.addTab(ACBFdocInfo, i18n("Document Info"))
        ACBFTabwidget.addTab(ACBFAuthorInfo, i18n("Author Info"))
        ACBFTabwidget.addTab(ACBFStyle, i18n("Style Sheet"))
        ACBFExportSettings.layout().addWidget(ACBFTabwidget)
        mainWidget.addTab(ACBFExportSettings, i18n("ACBF"))

        # Epub export, crop, resize, other questions.
        EPUBexportSettings = QWidget()
        EPUBexportSettings.setLayout(QVBoxLayout())
        self.EPUBactive = QCheckBox(i18n("Export to EPUB"))
        EPUBexportSettings.layout().addWidget(self.EPUBactive)
        self.EPUBgroupResize = comic_export_resize_widget("EPUB")
        EPUBexportSettings.layout().addWidget(self.EPUBgroupResize)
        self.EPUBactive.clicked.connect(self.EPUBgroupResize.setEnabled)
        mainWidget.addTab(EPUBexportSettings, "EPUB")

        # For Print. Crop, no resize.
        TIFFExportSettings = QWidget()
        TIFFExportSettings.setLayout(QVBoxLayout())
        self.TIFFactive = QCheckBox(i18n("Export to TIFF"))
        TIFFExportSettings.layout().addWidget(self.TIFFactive)
        self.TIFFgroupResize = comic_export_resize_widget("TIFF")
        TIFFExportSettings.layout().addWidget(self.TIFFgroupResize)
        self.TIFFactive.clicked.connect(self.TIFFgroupResize.setEnabled)
        mainWidget.addTab(TIFFExportSettings, "TIFF")

        # SVG, crop, resize, embed vs link.
        #SVGExportSettings = QWidget()

        #mainWidget.addTab(SVGExportSettings, "SVG")

    """
    Add a history item to the acbf version history list.
    """

    def slot_add_history_item(self):
        newItem = QStandardItem()
        newItem.setText("v" + str(self.spnACBFVersion.value()) + "-" +
                        i18n("in this version..."))
        self.ACBFhistoryModel.appendRow(newItem)

    """
    Get the margins by treating the active selection in a document as the trim area.
    This allows people to snap selections to a vector or something, and then get the margins.
    """

    def slot_set_margin_from_selection(self):
        doc = Application.activeDocument()
        if doc is not None:
            if doc.selection() is not None:
                self.spn_marginLeft.setValue(doc.selection().x())
                self.spn_marginTop.setValue(doc.selection().y())
                self.spn_marginRight.setValue(doc.width() -
                                              (doc.selection().x() +
                                               doc.selection().width()))
                self.spn_marginBottom.setValue(doc.height() -
                                               (doc.selection().y() +
                                                doc.selection().height()))

    """
    Add an author with default values initialised.
    """

    def slot_add_author(self):
        listItems = []
        listItems.append(QStandardItem(i18n("Anon")))  # Nick name
        listItems.append(QStandardItem(i18n("John")))  # First name
        listItems.append(QStandardItem())  # Middle name
        listItems.append(QStandardItem(i18n("Doe")))  # Last name
        listItems.append(QStandardItem())  # email
        listItems.append(QStandardItem())  # homepage
        self.ACBFauthorModel.appendRow(listItems)

    """
    Remove the selected author from the author list.
    """

    def slot_remove_author(self):
        self.ACBFauthorModel.removeRow(
            self.ACBFauthorTable.currentIndex().row())

    """
    Ensure that the drag and drop of authors doesn't mess up the labels.
    """

    def slot_reset_author_row_visual(self):
        headerLabelList = []
        for i in range(self.ACBFauthorTable.verticalHeader().count()):
            headerLabelList.append(str(i))
        for i in range(self.ACBFauthorTable.verticalHeader().count()):
            logicalI = self.ACBFauthorTable.verticalHeader().logicalIndex(i)
            headerLabelList[logicalI] = str(i + 1)
        self.ACBFauthorModel.setVerticalHeaderLabels(headerLabelList)

    def slot_set_style(self):
        index = self.ACBFStyleClass.currentIndex()
        if index.isValid():
            item = self.ACBFStylesModel.item(index.row())
            font = QFont()
            font.setFamily(str(item.data(role=Qt.UserRole + 1)))
            self.ACBFfontCombo.setCurrentFont(font)
            self.ACBFdefaultFont.setCurrentText(
                str(item.data(role=Qt.UserRole + 2)))
            bold = item.data(role=Qt.UserRole + 3)
            if bold is not None:
                self.ACBFBold.setChecked(bold)
            else:
                self.ACBFBold.setChecked(False)
            italic = item.data(role=Qt.UserRole + 4)
            if italic is not None:
                self.ACBFItal.setChecked(italic)
            else:
                self.ACBFItal.setChecked(False)

    def slot_font_current_style(self):
        index = self.ACBFStyleClass.currentIndex()
        if index.isValid():
            item = self.ACBFStylesModel.item(index.row())
            font = QFont(self.ACBFfontCombo.currentFont())
            item.setData(font.family(), role=Qt.UserRole + 1)
            item.setData(self.ACBFdefaultFont.currentText(),
                         role=Qt.UserRole + 2)
            item.setData(self.ACBFBold.isChecked(), role=Qt.UserRole + 3)
            item.setData(self.ACBFItal.isChecked(), role=Qt.UserRole + 4)
            self.ACBFStylesModel.setItem(index.row(), item)

    def slot_change_regular_color(self):
        if (self.regularColor.exec_() == QDialog.Accepted):
            square = QPixmap(32, 32)
            square.fill(self.regularColor.currentColor())
            self.btn_acbfRegColor.setIcon(QIcon(square))

    def slot_change_inverted_color(self):
        if (self.invertedColor.exec_() == QDialog.Accepted):
            square = QPixmap(32, 32)
            square.fill(self.invertedColor.currentColor())
            self.btn_acbfInvColor.setIcon(QIcon(square))

    """
    Load the UI values from the config dictionary given.
    """

    def setConfig(self, config):
        if "cropToGuides" in config.keys():
            self.chk_toOutmostGuides.setChecked(config["cropToGuides"])
        if "cropLeft" in config.keys():
            self.spn_marginLeft.setValue(config["cropLeft"])
        if "cropTop" in config.keys():
            self.spn_marginTop.setValue(config["cropTop"])
        if "cropRight" in config.keys():
            self.spn_marginRight.setValue(config["cropRight"])
        if "cropBottom" in config.keys():
            self.spn_marginBottom.setValue(config["cropBottom"])
        if "labelsToRemove" in config.keys():
            self.cmbLabelsRemove.setLabels(config["labelsToRemove"])
        if "textLayerNames" in config.keys():
            self.ln_text_layer_name.setText(", ".join(
                config["textLayerNames"]))
        else:
            self.ln_text_layer_name.setText("text")
        if "panelLayerNames" in config.keys():
            self.ln_panel_layer_name.setText(", ".join(
                config["panelLayerNames"]))
        else:
            self.ln_panel_layer_name.setText("panels")
        self.CBZgroupResize.set_config(config)
        if "CBZactive" in config.keys():
            self.CBZactive.setChecked(config["CBZactive"])
        self.EPUBgroupResize.set_config(config)
        if "EPUBactive" in config.keys():
            self.EPUBactive.setChecked(config["EPUBactive"])
        self.TIFFgroupResize.set_config(config)
        if "TIFFactive" in config.keys():
            self.TIFFactive.setChecked(config["TIFFactive"])

        if "acbfAuthor" in config.keys():
            if isinstance(config["acbfAuthor"], list):
                for author in config["acbfAuthor"]:
                    listItems = []
                    listItems.append(QStandardItem(author.get("nickname", "")))
                    listItems.append(
                        QStandardItem(author.get("first-name", "")))
                    listItems.append(QStandardItem(author.get("initials", "")))
                    listItems.append(QStandardItem(author.get("last-name",
                                                              "")))
                    listItems.append(QStandardItem(author.get("email", "")))
                    listItems.append(QStandardItem(author.get("homepage", "")))
                    self.ACBFauthorModel.appendRow(listItems)
                pass
            else:
                listItems = []
                listItems.append(QStandardItem(
                    config["acbfAuthor"]))  # Nick name
                for i in range(0, 5):
                    listItems.append(QStandardItem())  # First name
                self.ACBFauthorModel.appendRow(listItems)

        if "acbfSource" in config.keys():
            self.lnACBFSource.setText(config["acbfSource"])
        if "acbfID" in config.keys():
            self.lnACBFID.setText(config["acbfID"])
        else:
            self.lnACBFID.setText(QUuid.createUuid().toString())
        if "acbfVersion" in config.keys():
            self.spnACBFVersion.setValue(config["acbfVersion"])
        if "acbfHistory" in config.keys():
            for h in config["acbfHistory"]:
                item = QStandardItem()
                item.setText(h)
                self.ACBFhistoryModel.appendRow(item)
        if "acbfStyles" in config.keys():
            styleDict = config.get("acbfStyles", {})
            for key in self.acbfStylesList:
                keyDict = styleDict.get(key, {})
                style = QStandardItem(key.title())
                style.setCheckable(True)
                if key in styleDict.keys():
                    style.setCheckState(Qt.Checked)
                else:
                    style.setCheckState(Qt.Unchecked)
                style.setData(keyDict.get("font",
                                          QFont().family()),
                              role=Qt.UserRole + 1)
                style.setData(keyDict.get("genericfont", "sans-serif"),
                              role=Qt.UserRole + 2)
                style.setData(keyDict.get("bold", False), role=Qt.UserRole + 3)
                style.setData(keyDict.get("ital", False), role=Qt.UserRole + 4)
                self.ACBFStylesModel.appendRow(style)
            keyDict = styleDict.get("general", {})
            self.regularColor.setCurrentColor(
                QColor(keyDict.get("color", "#000000")))
            square = QPixmap(32, 32)
            square.fill(self.regularColor.currentColor())
            self.btn_acbfRegColor.setIcon(QIcon(square))
            keyDict = styleDict.get("inverted", {})
            self.invertedColor.setCurrentColor(
                QColor(keyDict.get("color", "#FFFFFF")))
            square.fill(self.invertedColor.currentColor())
            self.btn_acbfInvColor.setIcon(QIcon(square))
        else:
            for key in self.acbfStylesList:
                style = QStandardItem(key.title())
                style.setCheckable(True)
                style.setCheckState(Qt.Unchecked)
                style.setData(QFont().family(), role=Qt.UserRole + 1)
                style.setData("sans-serif", role=Qt.UserRole + 2)
                style.setData(False, role=Qt.UserRole + 3)  #Bold
                style.setData(False, role=Qt.UserRole + 4)  #Italic
                self.ACBFStylesModel.appendRow(style)
        self.CBZgroupResize.setEnabled(self.CBZactive.isChecked())
        self.lnTranslatorHeader.setText(
            config.get("translatorHeader", "Translator's Notes"))
        self.chkIncludeTranslatorComments.setChecked(
            config.get("includeTranslComment", False))

    """
    Store the GUI values into the config dictionary given.
    
    @return the config diactionary filled with new values.
    """

    def getConfig(self, config):

        config["cropToGuides"] = self.chk_toOutmostGuides.isChecked()
        config["cropLeft"] = self.spn_marginLeft.value()
        config["cropTop"] = self.spn_marginTop.value()
        config["cropBottom"] = self.spn_marginRight.value()
        config["cropRight"] = self.spn_marginBottom.value()
        config["labelsToRemove"] = self.cmbLabelsRemove.getLabels()
        config["CBZactive"] = self.CBZactive.isChecked()
        config = self.CBZgroupResize.get_config(config)
        config["EPUBactive"] = self.EPUBactive.isChecked()
        config = self.EPUBgroupResize.get_config(config)
        config["TIFFactive"] = self.TIFFactive.isChecked()
        config = self.TIFFgroupResize.get_config(config)
        authorList = []
        for row in range(self.ACBFauthorTable.verticalHeader().count()):
            logicalIndex = self.ACBFauthorTable.verticalHeader().logicalIndex(
                row)
            listEntries = [
                "nickname", "first-name", "initials", "last-name", "email",
                "homepage"
            ]
            author = {}
            for i in range(len(listEntries)):
                entry = self.ACBFauthorModel.data(
                    self.ACBFauthorModel.index(logicalIndex, i))
                if entry is None:
                    entry = " "
                if entry.isspace() is False and len(entry) > 0:
                    author[listEntries[i]] = entry
                elif listEntries[i] in author.keys():
                    author.pop(listEntries[i])
            authorList.append(author)
        config["acbfAuthor"] = authorList
        config["acbfSource"] = self.lnACBFSource.text()
        config["acbfID"] = self.lnACBFID.text()
        config["acbfVersion"] = self.spnACBFVersion.value()
        versionList = []
        for r in range(self.ACBFhistoryModel.rowCount()):
            index = self.ACBFhistoryModel.index(r, 0)
            versionList.append(
                self.ACBFhistoryModel.data(index, Qt.DisplayRole))
        config["acbfHistory"] = versionList

        acbfStylesDict = {}
        for row in range(0, self.ACBFStylesModel.rowCount()):
            entry = self.ACBFStylesModel.item(row)
            if entry.checkState() == Qt.Checked:
                key = entry.text().lower()
                style = {}
                font = entry.data(role=Qt.UserRole + 1)
                if font is not None:
                    style["font"] = font
                genericfont = entry.data(role=Qt.UserRole + 2)
                if font is not None:
                    style["genericfont"] = genericfont
                bold = entry.data(role=Qt.UserRole + 3)
                if bold is not None:
                    style["bold"] = bold
                italic = entry.data(role=Qt.UserRole + 4)
                if italic is not None:
                    style["ital"] = italic
                acbfStylesDict[key] = style
        acbfStylesDict["general"] = {
            "color": self.regularColor.currentColor().name()
        }
        acbfStylesDict["inverted"] = {
            "color": self.invertedColor.currentColor().name()
        }
        config["acbfStyles"] = acbfStylesDict
        config["translatorHeader"] = self.lnTranslatorHeader.text()
        config[
            "includeTranslComment"] = self.chkIncludeTranslatorComments.isChecked(
            )

        # Turn this into something that retreives from a line-edit when string freeze is over.
        config["textLayerNames"] = self.ln_text_layer_name.text().split(",")
        config["panelLayerNames"] = self.ln_panel_layer_name.text().split(",")
        return config
Exemplo n.º 16
0
class MainWindow(QMainWindow):
    InsertTextButton = 10
    items = {-2: "source", -3: "channel", -4: "sink"}

    def __init__(self):
        import _diagramscene_rc

        super(MainWindow, self).__init__()

        self.config_manipulations = FlumeConfig(self)
        properties_generator.dump_props()

        self.create_actions()
        self.create_menus()
        self.create_tool_box()
        self.clicked_button_id = 0

        self.scene = DiagramScene(self.item_menu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))

        self.scene.itemInserted.connect(self.item_inserted)
        self.scene.textInserted.connect(self.text_inserted)
        self.scene.itemSelected.connect(self.item_selected)

        self.create_tool_bars()
        # self.scene.enable_grid()

        layout = QHBoxLayout()
        layout.addWidget(self.tool_box)
        self.view = QGraphicsView(self.scene)
        self.view.centerOn(0, 0)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("The Flume Illustrator")

    # noinspection PyAttributeOutsideInit,PyArgumentList
    def create_actions(self):

        self.to_front_action = QAction(QIcon(':/images/bringtofront.png'),
                                       "Bring to &Front", self, shortcut="Ctrl+F",
                                       statusTip="Bring item to front", triggered=self.bring_to_front)
        self.send_back_action = QAction(QIcon(':/images/sendtoback.png'),
                                        "Send to &Back", self, shortcut="Ctrl+B",
                                        statusTip="Send item to back", triggered=self.send_to_back)
        self.bold_action = QAction(QIcon(':/images/bold.png'),
                                   "Bold", self, checkable=True, shortcut="Ctrl+B",
                                   triggered=self.handle_font_change)
        self.italic_action = QAction(QIcon(':/images/italic.png'),
                                     "Italic", self, checkable=True, shortcut="Ctrl+I",
                                     triggered=self.handle_font_change)
        self.underline_action = QAction(QIcon(':/images/underline.png'),
                                        "Underline", self, checkable=True, shortcut="Ctrl+U",
                                        triggered=self.handle_font_change)

        self.delete_action = QAction(QIcon(':/images/delete.png'),
                                     "Delete", self, shortcut="Delete", statusTip='Delete item from diagram',
                                     triggered=self.delete_item)
        self.exit_action = QAction("Exit", self, shortcut="Ctrl+X",
                                   statusTip="Quit program", triggered=self.close)
        self.about_action = QAction("About", self, shortcut="Ctrl+B",
                                    triggered=self.about)
        self.load_config_action = QAction("Load", self, shortcut="Ctrl+O",
                                          statusTip="Load config file", triggered=self.config_manipulations.load_config)

        self.enable_grid_action = QAction("Enable grid", self, checkable=True, triggered=self.enable_grid)

    # noinspection PyAttributeOutsideInit
    def create_menus(self):
        self.file_menu = self.menuBar().addMenu("File")
        self.file_menu.addAction(self.load_config_action)
        self.file_menu.addAction(self.exit_action)

        self.item_menu = self.menuBar().addMenu("Item")
        self.item_menu.addAction(self.delete_action)
        self.item_menu.addSeparator()
        self.item_menu.addAction(self.to_front_action)
        self.item_menu.addAction(self.send_back_action)

        self.about_menu = self.menuBar().addMenu("Help")
        self.about_menu.addAction(self.about_action)

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_box(self):
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(False)
        self.button_group.buttonClicked[int].connect(self.button_group_clicked)

        layout = QGridLayout()
        layout.addWidget(self.create_cell_widget("Source", "source"), 0, 0)
        layout.addWidget(self.create_cell_widget("Channel", "channel"), 0, 1)
        layout.addWidget(self.create_cell_widget("Sink", "sink"), 1, 0)

        text_button = QToolButton()
        text_button.setCheckable(True)
        self.button_group.addButton(text_button, self.InsertTextButton)
        text_button.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        text_button.setIconSize(QSize(50, 50))

        text_layout = QGridLayout()
        text_layout.addWidget(text_button, 0, 0, Qt.AlignHCenter)
        text_layout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        text_widget = QWidget()
        text_widget.setLayout(text_layout)
        layout.addWidget(text_widget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        item_widget = QWidget()
        item_widget.setLayout(layout)

        self.tool_box = QToolBox()
        self.tool_box.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.tool_box.setMinimumWidth(item_widget.sizeHint().width())
        self.tool_box.addItem(item_widget, "Basic Flume Items")

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_bars(self):

        self.edit_tool_bar = self.addToolBar("Edit")
        self.edit_tool_bar.addAction(self.delete_action)
        self.edit_tool_bar.addAction(self.to_front_action)
        self.edit_tool_bar.addAction(self.send_back_action)

        self.edit_tool_bar.addAction(self.enable_grid_action)

        self.font_combo = QFontComboBox()
        self.font_combo.currentFontChanged.connect(self.current_font_changed)

        self.font_size_combo = QComboBox()
        self.font_size_combo.setEditable(True)
        for i in range(8, 30, 2):
            self.font_size_combo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.font_size_combo.setValidator(validator)
        self.font_size_combo.currentIndexChanged.connect(self.font_size_changed)

        self.font_color_tool_button = QToolButton()
        self.font_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.font_color_tool_button.setMenu(
            self.create_color_menu(self.text_color_changed, Qt.black))
        self.text_action = self.font_color_tool_button.menu().defaultAction()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               Qt.black))
        self.font_color_tool_button.setAutoFillBackground(True)
        self.font_color_tool_button.clicked.connect(self.text_button_triggered)

        self.fill_color_tool_button = QToolButton()
        self.fill_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.fill_color_tool_button.setMenu(
            self.create_color_menu(self.item_color_changed, Qt.white))
        self.fillAction = self.fill_color_tool_button.menu().defaultAction()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               Qt.white))
        self.fill_color_tool_button.clicked.connect(self.fill_button_triggered)

        self.line_color_tool_button = QToolButton()
        self.line_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.line_color_tool_button.setMenu(
            self.create_color_menu(self.line_color_changed, Qt.black))
        self.lineAction = self.line_color_tool_button.menu().defaultAction()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               Qt.black))
        self.line_color_tool_button.clicked.connect(self.line_button_triggered)

        self.text_tool_bar = self.addToolBar("Font")
        self.text_tool_bar.addWidget(self.font_combo)
        self.text_tool_bar.addWidget(self.font_size_combo)
        self.text_tool_bar.addAction(self.bold_action)
        self.text_tool_bar.addAction(self.italic_action)
        self.text_tool_bar.addAction(self.underline_action)

        self.color_tool_bar = self.addToolBar("Color")
        self.color_tool_bar.addWidget(self.font_color_tool_button)
        self.color_tool_bar.addWidget(self.fill_color_tool_button)
        self.color_tool_bar.addWidget(self.line_color_tool_button)

        self.loading_tool_bar = self.addToolBar("Load")
        self.loading_tool_bar.addAction(self.load_config_action)

        pointer_button = QToolButton()
        pointer_button.setCheckable(True)
        pointer_button.setChecked(True)
        pointer_button.setIcon(QIcon(":/images/pointer.png"))
        line_pointer_button = QToolButton()
        line_pointer_button.setCheckable(True)
        line_pointer_button.setIcon(QIcon(":/images/linepointer.png"))

        self.pointer_type_group = QButtonGroup()
        self.pointer_type_group.addButton(pointer_button, DiagramScene.MoveItem)
        self.pointer_type_group.addButton(line_pointer_button, DiagramScene.InsertLine)
        self.pointer_type_group.buttonClicked[int].connect(self.pointer_group_clicked)

        self.scene_scale_combo = QComboBox()
        self.scene_scale_combo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.scene_scale_combo.setCurrentIndex(2)
        self.scene_scale_combo.currentIndexChanged[str].connect(self.scene_scale_changed)

        self.pointer_tool_bar = self.addToolBar("Pointer type")
        self.pointer_tool_bar.addWidget(pointer_button)
        self.pointer_tool_bar.addWidget(line_pointer_button)
        self.pointer_tool_bar.addWidget(self.scene_scale_combo)

    def button_group_clicked(self, button_id):
        buttons = self.button_group.buttons()
        self.clicked_button_id = button_id
        for button in buttons:
            if self.button_group.button(button_id) != button:
                button.setChecked(False)
        if button_id == self.InsertTextButton:
            self.scene.set_mode(DiagramScene.InsertText)
        else:
            self.scene.set_item_type(self.items[button_id])
            self.scene.set_mode(DiagramScene.InsertItem)

    def delete_item(self):
        for item in self.scene.selectedItems():
            if isinstance(item, FlumeDiagramItem):
                item.remove_arrows()
            self.scene.removeItem(item)

    # noinspection PyTypeChecker,PyCallByClass
    def about(self):

        # noinspection PyArgumentList
        QMessageBox.about(self, "About Flume Illustrator", "The Flume illustrator shows config-file details")

    def pointer_group_clicked(self):
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def bring_to_front(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() >= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() + 0.1
        selected_item.setZValue(z_value)

    def send_to_back(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() <= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() - 0.1
        selected_item.setZValue(z_value)

    def scene_scale_changed(self, scale):
        new_scale = float(scale[:scale.index("%")]) / 100
        old_transform = self.view.transform()
        self.view.resetTransform()
        self.view.translate(old_transform.dx(), old_transform.dy())
        self.view.scale(new_scale, new_scale)

    def item_inserted(self, diagram_type):
        self.pointer_type_group.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.set_mode(self.scene.DefaultMode)
        self.button_group.button(self.clicked_button_id).setChecked(False)

    def text_inserted(self, item):
        self.button_group.button(self.InsertTextButton).setChecked(False)
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def current_font_changed(self, font):
        self.handle_font_change()

    def font_size_changed(self, font=None):
        self.handle_font_change()

    def text_color_changed(self):
        self.text_action = self.sender()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               QColor(self.text_action.data())))
        self.text_button_triggered()

    def item_color_changed(self):
        self.fillAction = self.sender()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               QColor(self.fillAction.data())))
        self.fill_button_triggered()

    def line_color_changed(self):
        self.lineAction = self.sender()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               QColor(self.lineAction.data())))
        self.line_button_triggered()

    def text_button_triggered(self):
        self.scene.set_text_color(QColor(self.text_action.data()))

    def fill_button_triggered(self):
        self.scene.set_item_color(QColor(self.fillAction.data()))

    def line_button_triggered(self):
        self.scene.set_line_color(QColor(self.lineAction.data()))

    def handle_font_change(self):
        font = self.font_combo.currentFont()
        font.setPointSize(int(self.font_size_combo.currentText()))
        if self.bold_action.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italic_action.isChecked())
        font.setUnderline(self.underline_action.isChecked())

        self.scene.setFont(font)

    def item_selected(self, item):
        font = item.font()
        self.font_combo.setCurrentFont(font)
        self.font_size_combo.setEditText(str(font.pointSize()))
        self.bold_action.setChecked(font.weight() == QFont.Bold)
        self.italic_action.setChecked(font.italic())
        self.underline_action.setChecked(font.underline())

    def create_cell_widget(self, text, diagram_type):
        item = FlumeObject(diagram_type, "")
        icon = QIcon(item.pictogram.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.button_group.addButton(button)  # , diagram_type

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignHCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    # noinspection PyArgumentList
    def create_color_menu(self, slot, default_color):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        color_menu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.create_color_icon(color), name, self,
                             triggered=slot)
            action.setData(QColor(color))
            color_menu.addAction(action)
            if color == default_color:
                color_menu.setDefaultAction(action)
        return color_menu

    @staticmethod
    def create_color_tool_button_icon(image_file, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(image_file)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    @staticmethod
    def create_color_icon(color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def enable_grid(self):
        if self.enable_grid_action.isChecked():
            color = Qt.black
        else:
            color = Qt.white
        for i in range(50):
            for j in range(50):
                self.scene.addEllipse(i * 100, j * 100, 2, 2, QPen(color))
Exemplo n.º 17
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        # View widget stuff

        self.view = TextView()
        self.centralWidget = QWidget(self)
        self.layout = QVBoxLayout(self.centralWidget)
        self.view.statusChanged.connect(self.quickViewStatusChanged)
        self.view.sceneGraphError.connect(self.sceneGraphError)

        self.container = QWidget.createWindowContainer(self.view)
        self.container.setMinimumSize(self.view.size())
        self.container.setFocusPolicy(Qt.TabFocus)
        self.layout.addWidget(self.container)

        self.setCentralWidget(self.centralWidget)
        self.statusBar().showMessage('Ready')

        # Menu stuff

        self.toolbar = self.addToolBar('Text Effects')

        # Set up the text effects tools
        actionGroup = QActionGroup(self)

        noneAction = QAction(QIcon("none.png"), "&Clear", self)
        noneAction.setStatusTip("Clear Effects")
        noneAction.triggered.connect(self.view.noEffect)
        actionGroup.addAction(noneAction)

        blurAction = QAction(QIcon("blur.png"), "&Blur", self)
        blurAction.setStatusTip("Blur Text")
        blurAction.triggered.connect(self.view.blur)
        actionGroup.addAction(blurAction)

        opacityAction = QAction(QIcon("opacity.png"), "&Transparency", self)
        opacityAction.setStatusTip("Fade Text")
        opacityAction.triggered.connect(self.view.opacity)
        actionGroup.addAction(opacityAction)

        shadowAction = QAction(QIcon("shadow.png"), "&Drop Shadow", self)
        shadowAction.setStatusTip("Drop-shadow Text")
        shadowAction.triggered.connect(self.view.shadow)
        actionGroup.addAction(shadowAction)

        self.toolbar.addActions(actionGroup.actions())
        self.toolbar.addSeparator()

        # Set up the font selection tools
        boldAction = QAction(QIcon("bold.png"), "&Bold", self)
        boldAction.setStatusTip("Bold Text")
        boldAction.setCheckable(True)
        boldAction.setChecked(False)
        boldAction.triggered[bool].connect(self.view.bold)
        self.toolbar.addAction(boldAction)

        italicAction = QAction(QIcon("italic.png"), "&Italic", self)
        italicAction.setStatusTip("Italic Text")
        italicAction.setCheckable(True)
        italicAction.triggered[bool].connect(self.view.italic)
        self.toolbar.addAction(italicAction)

        self.fontBox = QFontComboBox(self)
        self.fontBox.setCurrentFont(self.view.font)
        self.fontBox.currentFontChanged.connect(self.view.fontFamily)
        self.toolbar.addWidget(self.fontBox)

        self.fontSizeBox = QComboBox(self)
        self.fontSizeBox.setEditable(True)
        strlist = []
        intlist = QFontDatabase.standardSizes()
        for item in intlist:
            strlist.append(str(item))
        self.fontSizeBox.addItems(strlist)
        self.view.fontSize('24')
        self.fontSizeBox.setCurrentText(str(self.view.basicFontSize))
        self.fontSizeBox.currentTextChanged.connect(self.view.fontSize)
        self.toolbar.addWidget(self.fontSizeBox)

        self.setGeometry(300, 300, 600, 500)
        self.setWindowTitle('Renderer')
        self.show()

    def quickViewStatusChanged(status):
        if status is QQuickView.Error:
            errors = []
            for error in self.quickView.errors():
                errors.append(str(error))
            self.statusBar().showmessage((', ').join(errors))

    def sceneGraphError(error, message):
        self.statusBar.showMessage(message)
Exemplo n.º 18
0
class Preferences(QDialog):
    # Signal to warn that the window is closed
    settingsClosed = pyqtSignal()

    def __init__(self, parent=None):
        super(Preferences, self).__init__(parent)

        # Main container
        # This contains a grid
        main_box = QVBoxLayout(self)
        main_box.setContentsMargins(200, 50, 200, 100)

        # The grid contains two containers
        # left container and right container
        grid = QGridLayout()

        # Left Container
        left_container = QVBoxLayout()
        left_container.setContentsMargins(0, 0, 0, 0)

        # General
        group_gral = QGroupBox(self.tr("General"))
        box_gral = QVBoxLayout(group_gral)
        # Updates
        btn_updates = QPushButton(self.tr("Check for updates"))
        box_gral.addWidget(btn_updates)
        # Language
        group_language = QGroupBox(self.tr("Language"))
        box = QVBoxLayout(group_language)
        # Find .qm files in language path
        available_langs = file_manager.get_files_from_folder(
            settings.LANGUAGE_PATH)

        languages = ["English"] + available_langs
        self._combo_lang = QComboBox()
        box.addWidget(self._combo_lang)
        self._combo_lang.addItems(languages)
        self._combo_lang.currentIndexChanged[int].connect(
            self._change_lang)
        if PSetting.LANGUAGE:
            self._combo_lang.setCurrentText(PSetting.LANGUAGE)
        box.addWidget(QLabel(self.tr("(Requires restart)")))

        # Add widgets
        left_container.addWidget(group_gral)
        left_container.addWidget(group_language)
        left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                           QSizePolicy.Expanding))

        # Right Container
        right_container = QVBoxLayout()
        right_container.setContentsMargins(0, 0, 0, 0)

        # Editor
        editor_group = QGroupBox(self.tr("Editor Configurations"))
        box_editor = QHBoxLayout(editor_group)
        # Current line
        self._highlight_current_line = QCheckBox(
            self.tr("Highlight Current Line"))
        self._highlight_current_line.setChecked(
            PSetting.HIGHLIGHT_CURRENT_LINE)
        self._highlight_current_line.stateChanged[int].connect(
            self.__current_line_value_changed)
        box_editor.addWidget(self._highlight_current_line)
        # Matching paren
        self._matching_paren = QCheckBox(self.tr("Matching Parenthesis"))
        self._matching_paren.setChecked(
            PSetting.MATCHING_PARENTHESIS)
        self._matching_paren.stateChanged[int].connect(
            self.__set_enabled_matching_parenthesis)
        box_editor.addWidget(self._matching_paren)
        # Font group
        font_group = QGroupBox(self.tr("Font"))
        font_grid = QGridLayout(font_group)
        font_grid.addWidget(QLabel(self.tr("Family")), 0, 0)
        self._combo_font = QFontComboBox()
        self._combo_font.setCurrentFont(PSetting.FONT)
        font_grid.addWidget(self._combo_font, 0, 1)
        font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0)
        self._combo_font_size = QComboBox()
        fdb = QFontDatabase()
        combo_sizes = fdb.pointSizes(PSetting.FONT.family())
        current_size_index = combo_sizes.index(
            PSetting.FONT.pointSize())

        self._combo_font_size.addItems([str(f) for f in combo_sizes])
        self._combo_font_size.setCurrentIndex(current_size_index)
        font_grid.addWidget(self._combo_font_size, 1, 1)

        right_container.addWidget(editor_group)
        right_container.addWidget(font_group)
        right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                            QSizePolicy.Expanding))

        # Add widgets
        grid.addLayout(left_container, 0, 0)
        grid.addLayout(right_container, 0, 1)
        main_box.addLayout(grid)

        # Button close and reset
        hbox = QHBoxLayout()
        hbox.setSpacing(20)
        hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btn_cancel = QPushButton(self.tr("Back"))
        hbox.addWidget(btn_cancel)
        btn_reset = QPushButton(self.tr("Reset Configurations"))
        hbox.addWidget(btn_reset)
        main_box.addLayout(hbox)

        # Overlay
        self.overlay = overlay_widget.OverlayWidget(self)
        self.overlay.hide()

        # Effect and animations
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        duration, x = 180, 150  # Animation duration
        # Animation start
        # Opacity animation
        self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_s.setDuration(duration)
        self.opacity_animation_s.setStartValue(0.0)
        self.opacity_animation_s.setEndValue(1.0)
        # X animation
        self.x_animation_s = QPropertyAnimation(self, b"geometry")
        self.x_animation_s.setDuration(duration)
        self.x_animation_s.setStartValue(QRect(x, 0, parent.width(),
                                               parent.height()))
        self.x_animation_s.setEndValue(QRect(0, 0, parent.width(),
                                             parent.height()))
        # Animation end
        # Opacity animation
        self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_e.setDuration(duration)
        self.opacity_animation_e.setStartValue(1.0)
        self.opacity_animation_e.setEndValue(0.0)
        # X animation
        self.x_animation_e = QPropertyAnimation(self, b"geometry")
        self.x_animation_e.setDuration(duration)
        self.x_animation_e.setStartValue(QRect(0, 0, parent.width(),
                                               parent.height()))
        self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(),
                                             parent.height()))

        # Group animation start
        self.group_animation_s = QParallelAnimationGroup()
        self.group_animation_s.addAnimation(self.opacity_animation_s)
        self.group_animation_s.addAnimation(self.x_animation_s)

        # Group animation end
        self.group_animation_e = QParallelAnimationGroup()
        self.group_animation_e.addAnimation(self.opacity_animation_e)
        self.group_animation_e.addAnimation(self.x_animation_e)

        # Connections
        self.group_animation_e.finished.connect(
            self._on_group_animation_finished)
        btn_cancel.clicked.connect(self.close)
        btn_reset.clicked.connect(self._reset_settings)
        btn_updates.clicked.connect(self._check_for_updates)
        # self.thread.finished.connect(self._on_thread_finished)
        self._combo_font.currentFontChanged.connect(
            self._change_font)
        self._combo_font_size.currentTextChanged.connect(
            self._change_font_size)

    def __current_line_value_changed(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('highlight_current_line', value)
        PSetting.HIGHLIGHT_CURRENT_LINE = value

    def __set_enabled_matching_parenthesis(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue("matching_parenthesis", value)
        PSetting.MATCHING_PARENTHESIS = value

    def _change_font(self, font):
        # FIXME: un quilombo esto
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def _change_font_size(self, size):
        # FIXME: un quilombo esto
        font = self._combo_font.currentFont()
        font.setPointSize(int(size))
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def showEvent(self, event):
        super(Preferences, self).showEvent(event)
        self.group_animation_s.start()

    def resizeEvent(self, event):
        self.overlay.resize(self.size())
        event.accept()

    def done(self, result):
        self.res = result
        self.group_animation_e.start()

    def _on_group_animation_finished(self):
        super(Preferences, self).done(self.res)
        self.settingsClosed.emit()

    def _check_for_updates(self):
        # Thread
        self._thread = QThread()
        self._updater = updater.Updater()
        self._updater.moveToThread(self._thread)
        self._thread.started.connect(self._updater.check_updates)
        self._updater.finished.connect(self.__on_thread_update_finished)
        # Show overlay widget
        self.overlay.show()
        # Start thread
        self._thread.start()

    def __on_thread_update_finished(self):
        # Hide overlay widget
        self.overlay.hide()
        self._thread.quit()
        msg = QMessageBox(self)
        if not self._updater.error:
            if self._updater.version:
                version = self._updater.version
                msg.setWindowTitle(self.tr("New version available!"))
                msg.setText(self.tr("Check the web site to "
                                    "download <b>Pireal {}</b>".format(
                                        version)))
                download_btn = msg.addButton(self.tr("Download!"),
                                             QMessageBox.YesRole)
                msg.addButton(self.tr("Cancel"),
                              QMessageBox.RejectRole)
                msg.exec_()
                r = msg.clickedButton()
                if r == download_btn:
                    webbrowser.open_new(
                        "http://centaurialpha.github.io/pireal")
            else:
                msg.setWindowTitle(self.tr("Information"))
                msg.setText(self.tr("Last version installed"))
                msg.addButton(self.tr("Ok"),
                              QMessageBox.AcceptRole)
                msg.exec_()
        else:
            msg.critical(self, self.tr("Error"),
                         self.tr("Connection error"))

        self._thread.deleteLater()
        self._updater.deleteLater()

    def _reset_settings(self):
        """ Remove all settings """

        msg = QMessageBox(self)
        msg.setWindowTitle(self.tr("Reset Settings"))
        msg.setText(self.tr("Are you sure you want to clear all settings?"))
        msg.setIcon(QMessageBox.Question)
        msg.addButton(self.tr("No"), QMessageBox.NoRole)
        yes_btn = msg.addButton(self.tr("Yes"),
                                QMessageBox.YesRole)
        msg.exec_()
        r = msg.clickedButton()
        if r == yes_btn:
            QSettings(settings.SETTINGS_PATH, QSettings.IniFormat).clear()
            self.close()

    def _change_lang(self, index):
        lang = self._combo_lang.itemText(index)
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('language', lang)
Exemplo n.º 19
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # self.path holds the path of the currently open file
        # If none, we haven't got a file open yet (or creating new)
        self.path = None
        self.origin_text_length = 0
        self.modified_text_length = 0

        self.setup()
        self.menu_and_toolbar()

        self.slot()

        # Initialize
        self.update_format()
        self.update_title()

        self.show()

    def setup(self):
        layout = QVBoxLayout()

        # Editor 설정
        self.editor = TextEdit()
        self.editor.setAutoFormatting(QTextEdit.AutoAll)
        font = QFont("Times", 12)
        self.editor.setFont(font)
        self.editor.setFontPointSize(12)

        self.convert_button = QPushButton("Convert")

        layout.addWidget(self.editor)
        layout.addWidget(self.convert_button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        self.status = QStatusBar()
        self.setStatusBar(self.status)

        self.menuBar().setNativeMenuBar(False)

    def slot(self):
        self.editor.selectionChanged.connect(self.update_format)
        self.bold_action.toggled.connect(
            lambda x: self.editor.setFontWeight(QFont.Bold if x else QFont.Normal)
        )
        self.italic_action.toggled.connect(self.editor.setFontItalic)
        self.underline_action.toggled.connect(self.editor.setFontUnderline)
        self.new_file_action.triggered.connect(self.new_file)
        self.open_file_action.triggered.connect(self.file_open)
        self.save_file_action.triggered.connect(self.file_save)
        self.saveas_file_action.triggered.connect(self.file_saveas)
        self.undo_action.triggered.connect(self.editor.undo)
        self.redo_action.triggered.connect(self.editor.redo)
        self.cut_action.triggered.connect(self.editor.cut)
        self.copy_action.triggered.connect(self.editor.copy)
        self.paste_action.triggered.connect(self.editor.paste)
        self.select_action.triggered.connect(self.editor.selectAll)
        self.wrap_action.triggered.connect(self.edit_toggle_wrap)
        self.fonts.currentIndexChanged.connect(self.editor.setCurrentFont)
        self.fontsize.currentIndexChanged[str].connect(
            lambda s: self.editor.setFontPointSize(float(s))
        )
        self.text_color_action.triggered.connect(self.change_text_color)
        self.text_background_color_action.triggered.connect(
            self.change_text_background_color
        )
        self.alignl_action.triggered.connect(
            lambda: self.editor.setAlignment(Qt.AlignLeft)
        )
        self.alignc_action.triggered.connect(
            lambda: self.editor.setAlignment(Qt.AlignCenter)
        )
        self.alignr_action.triggered.connect(
            lambda: self.editor.setAlignment(Qt.AlignRight)
        )
        self.alignj_action.triggered.connect(
            lambda: self.editor.setAlignment(Qt.AlignJustify)
        )

        self.convert_button.clicked.connect(self.convert_to_html)

    def menu_and_toolbar(self):
        file_toolbar = QToolBar("File")
        file_toolbar.setIconSize(QSize(14, 14))
        self.addToolBar(file_toolbar)
        file_menu = self.menuBar().addMenu("&File")

        self.new_file_action = QAction(
            QIcon(os.path.join("images", "document-plus.png")), "New file", self
        )
        self.new_file_action.setStatusTip("Create new file")
        file_menu.addAction(self.new_file_action)
        file_toolbar.addAction(self.new_file_action)

        self.open_file_action = QAction(
            QIcon(os.path.join("images", "blue-folder-open-document.png")),
            "Open file...",
            self,
        )
        self.open_file_action.setStatusTip("Open file")
        file_menu.addAction(self.open_file_action)
        file_toolbar.addAction(self.open_file_action)

        self.save_file_action = QAction(
            QIcon(os.path.join("images", "disk.png")), "Save", self
        )
        self.save_file_action.setStatusTip("Save current page")
        file_menu.addAction(self.save_file_action)
        file_toolbar.addAction(self.save_file_action)

        self.saveas_file_action = QAction(
            QIcon(os.path.join("images", "disk--pencil.png")), "Save As...", self
        )
        self.saveas_file_action.setStatusTip("Save current page to specified file")
        file_menu.addAction(self.saveas_file_action)
        file_toolbar.addAction(self.saveas_file_action)

        edit_toolbar = QToolBar("Edit")
        edit_toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(edit_toolbar)
        edit_menu = self.menuBar().addMenu("&Edit")

        self.undo_action = QAction(
            QIcon(os.path.join("images", "arrow-curve-180-left.png")), "Undo", self
        )
        self.undo_action.setStatusTip("Undo last change")
        edit_menu.addAction(self.undo_action)
        edit_toolbar.addAction(self.undo_action)

        self.redo_action = QAction(
            QIcon(os.path.join("images", "arrow-curve.png")), "Redo", self
        )
        self.redo_action.setStatusTip("Redo last change")
        edit_menu.addAction(self.redo_action)
        edit_toolbar.addAction(self.redo_action)

        edit_menu.addSeparator()

        self.cut_action = QAction(
            QIcon(os.path.join("images", "scissors.png")), "Cut", self
        )
        self.cut_action.setStatusTip("Cut selected text")
        self.cut_action.setShortcut(QKeySequence.Cut)
        edit_toolbar.addAction(self.cut_action)
        edit_menu.addAction(self.cut_action)

        self.copy_action = QAction(
            QIcon(os.path.join("images", "document-copy.png")), "Copy", self
        )
        self.copy_action.setStatusTip("Copy selected text")
        self.copy_action.setShortcut(QKeySequence.Copy)
        edit_toolbar.addAction(self.copy_action)
        edit_menu.addAction(self.copy_action)

        self.paste_action = QAction(
            QIcon(os.path.join("images", "clipboard-paste-document-text.png")),
            "Paste",
            self,
        )
        self.paste_action.setStatusTip("Paste from clipboard")
        self.paste_action.setShortcut(QKeySequence.Paste)
        edit_toolbar.addAction(self.paste_action)
        edit_menu.addAction(self.paste_action)

        self.select_action = QAction(
            QIcon(os.path.join("images", "selection-input.png")), "Select all", self
        )
        self.select_action.setStatusTip("Select all text")
        self.select_action.setShortcut(QKeySequence.SelectAll)
        edit_menu.addAction(self.select_action)
        edit_toolbar.addAction(self.select_action)

        edit_menu.addSeparator()

        self.wrap_action = QAction(
            QIcon(os.path.join("images", "arrow-continue.png")),
            "Wrap text to window",
            self,
        )
        self.wrap_action.setStatusTip("Toggle wrap text to window")
        self.wrap_action.setCheckable(True)
        self.wrap_action.setChecked(True)
        edit_menu.addAction(self.wrap_action)
        edit_toolbar.addAction(self.wrap_action)

        format_toolbar = QToolBar("Format")
        format_toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(format_toolbar)
        format_menu = self.menuBar().addMenu("&Foramt")

        self.fonts = QFontComboBox()
        format_toolbar.addWidget(self.fonts)

        self.fontsize = QComboBox()
        self.fontsize.addItems([str(s) for s in FONT_SIZES])
        format_toolbar.addWidget(self.fontsize)

        self.bold_action = QAction(
            QIcon(os.path.join("images", "edit-bold.png")), "Bold", self
        )
        self.bold_action.setStatusTip("Bold")
        self.bold_action.setShortcut(QKeySequence.Bold)
        self.bold_action.setCheckable(True)
        format_toolbar.addAction(self.bold_action)
        format_menu.addAction(self.bold_action)

        self.italic_action = QAction(
            QIcon(os.path.join("images", "edit-italic.png")), "Italic", self
        )
        self.italic_action.setStatusTip("Italic")
        self.italic_action.setShortcut(QKeySequence.Italic)
        self.italic_action.setCheckable(True)
        format_toolbar.addAction(self.italic_action)
        format_menu.addAction(self.italic_action)

        self.underline_action = QAction(
            QIcon(os.path.join("images", "edit-underline.png")), "Underline", self
        )
        self.underline_action.setStatusTip("Underline")
        self.underline_action.setShortcut(QKeySequence.Underline)
        self.underline_action.setCheckable(True)
        format_toolbar.addAction(self.underline_action)
        format_menu.addAction(self.underline_action)

        self.text_color_action = QAction(
            QIcon(os.path.join("images", "color-pencil.png")), "Text Color", self
        )
        self.text_color_action.setStatusTip("Change text color")
        format_toolbar.addAction(self.text_color_action)
        format_menu.addAction(self.text_color_action)

        self.text_background_color_action = QAction(
            QIcon(os.path.join("images", "color.png")), "Background Color", self
        )
        self.text_background_color_action.setStatusTip("Change text background color")
        format_toolbar.addAction(self.text_background_color_action)
        format_menu.addAction(self.text_background_color_action)

        format_menu.addSeparator()
        format_toolbar.addSeparator()

        self.alignl_action = QAction(
            QIcon(os.path.join("images", "edit-alignment.png")), "Align left", self
        )
        self.alignl_action.setStatusTip("Align text left")
        self.alignl_action.setCheckable(True)
        format_toolbar.addAction(self.alignl_action)
        format_menu.addAction(self.alignl_action)

        self.alignc_action = QAction(
            QIcon(os.path.join("images", "edit-alignment-center.png")),
            "Align center",
            self,
        )
        self.alignc_action.setStatusTip("Align text center")
        self.alignc_action.setCheckable(True)
        format_toolbar.addAction(self.alignc_action)
        format_menu.addAction(self.alignc_action)

        self.alignr_action = QAction(
            QIcon(os.path.join("images", "edit-alignment-right.png")),
            "Align right",
            self,
        )
        self.alignr_action.setStatusTip("Align text right")
        self.alignr_action.setCheckable(True)
        format_toolbar.addAction(self.alignr_action)
        format_menu.addAction(self.alignr_action)

        self.alignj_action = QAction(
            QIcon(os.path.join("images", "edit-alignment-justify.png")), "Justify", self
        )
        self.alignj_action.setStatusTip("Justify text")
        self.alignj_action.setCheckable(True)
        format_toolbar.addAction(self.alignj_action)
        format_menu.addAction(self.alignj_action)

        format_group = QActionGroup(self)
        format_group.setExclusive(True)
        format_group.addAction(self.alignl_action)
        format_group.addAction(self.alignc_action)
        format_group.addAction(self.alignr_action)
        format_group.addAction(self.alignj_action)

        format_menu.addSeparator()

    def new_file(self):
        if self.path:
            if self.origin_text_length != self.modified_text_length:
                button_reply = QMessageBox.question(
                    self,
                    "PyQt5 Message",
                    "Do you want to save?",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.Yes,
                )
                if button_reply == QMessageBox.Yes:
                    self.file_save()
            self.path = None
        else:
            text = self.editor.toPlainText()
            if len(text) > 0:
                button_reply = QMessageBox.question(
                    self,
                    "PyQt5 message",
                    "Do you want to save?",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.Yes,
                )
                if button_reply == QMessageBox.Yes:
                    self.file_save()

        self.editor.selectAll()
        self.editor.clear()
        self.update_title()

    def block_signals(self, objects, b):
        for o in objects:
            o.blockSignals(b)

    def update_format(self):
        """
        Update the font format toolbar/action when a new text selection is made.
        This is neccessary to keep toolbars/etc.
        in sync with the current edit state

        :return:
        """

        # A list of all format-related widgets/actions, so we can disable/enable signals when updating.
        self._format_action = [
            self.fonts,
            self.fontsize,
            self.bold_action,
            self.italic_action,
            self.underline_action,
        ]

        # Disable signals for all format widgets, so changing values here does not trigger further formatting
        self.block_signals(self._format_action, True)

        self.fonts.setCurrentFont(self.editor.currentFont())
        self.fontsize.setCurrentText(str(int(self.editor.fontPointSize())))
        self.italic_action.setChecked(self.editor.fontItalic())
        self.underline_action.setChecked(self.editor.fontUnderline())
        self.bold_action.setChecked(self.editor.fontWeight() == QFont.Bold)

        self.alignl_action.setChecked(self.editor.alignment() == Qt.AlignLeft)
        self.alignc_action.setChecked(self.editor.alignment() == Qt.AlignCenter)
        self.alignr_action.setChecked(self.editor.alignment() == Qt.AlignRight)
        self.alignj_action.setChecked(self.editor.alignment() == Qt.AlignJustify)

        self.block_signals(self._format_action, False)

    def file_open(self):
        path, _ = QFileDialog.getOpenFileName(
            self,
            "Open file",
            "",
            "HTML documents (*.html);Text Documents (*.txt);All files (*.*)",
        )

        try:
            with open(path, "r") as f:
                text = f.read()
        except Exception as e:
            self.dialog_critical(str(e))
        else:
            self.path = path
            # Qt will automatically try and guess the format as txt/html
            self.editor.setText(text)
            self.update_title()

    def file_save(self):
        if self.path is None:
            # If we do not have a path, we need to use Save As.
            return self.file_saveas()

        text = (
            self.editor.toHtml()
            if splitext(self.path) in HTML_EXTENSIONS
            else self.editor.toPlainText()
        )

        try:
            with open(self.path, "w") as f:
                f.write(text)
        except Exception as e:
            self.dialog_critical(str(e))

    def file_saveas(self):
        path, _ = QFileDialog.getSaveFileName(
            self,
            "Save file",
            "",
            "HTML documents (*.html);Text documents (*.txt);All files (*.*)",
        )

        if not path:
            # If dialog is cancelled, will return ''
            return

        text = (
            self.editor.toHtml()
            if splitext(path) in HTML_EXTENSIONS
            else self.editor.toPlainText()
        )

        try:
            with open(path, "w") as f:
                f.write(text)
        except Exception as e:
            self.dialog_critical(str(e))
        else:
            self.path = path
            self.update_title()

    def convert_to_html(self):
        dialog = QDialog()

        tool_bar = QToolBar("Edit")
        tool_bar.setIconSize(QSize(14, 14))

        self.copy_html_button = QPushButton("Copy")

        self.html_dialog_editor = QTextEdit()
        self.html_dialog_editor.setReadOnly(True)

        html = self.editor.toHtml()
        body = re.search("<body.*/body>", html, re.I | re.S)
        self.html_dialog_editor.setPlainText(body.group()[89:-7])

        layout = QVBoxLayout()
        layout.addWidget(self.copy_html_button)
        layout.addWidget(self.html_dialog_editor)

        dialog.setLayout(layout)

        self.copy_html_button.clicked.connect(self.copy_html)

        dialog.exec()

    def copy_html(self):
        self.html_dialog_editor.selectAll()
        self.html_dialog_editor.copy()

    def update_title(self):
        self.setWindowTitle(os.path.basename(self.path) if self.path else "Untitled")

    def edit_toggle_wrap(self):
        self.editor.setLineWrapMode(1 if self.editor.lineWrapMode() == 0 else 0)

    def _get_color(self):
        color = QColorDialog()
        selected_color = color.getColor()
        if selected_color.isValid():
            return selected_color

    def change_text_color(self):
        color = self._get_color()
        if color is not None:
            self.editor.setTextColor(color)

    def change_text_background_color(self):
        color = self._get_color()
        if color is not None:
            self.editor.setTextBackgroundColor(color)

    def dialog_critical(self, s):
        dlg = QMessageBox(self)
        dlg.setText(s)
        dlg.setIcon(QMessageBox.Critical)
        dlg.show()
Exemplo n.º 20
0
class SettingsEditDialog(QDialog):

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

        self.setModal(True)
        self.setWindowTitle('Settings')
        self.setMinimumWidth(400)

        self.accepted.connect(self.save)

        # Editor group

        self.font_family_input = QFontComboBox()

        self.font_size_input = QSpinBox()
        self.font_size_input.setRange(8, 24)
        self.font_size_input.setSuffix(' pt')

        self.tab_size_input = QSpinBox()
        self.tab_size_input.setRange(1, 16)
        self.tab_size_input.setSuffix(' spaces')

        self.enable_text_wrapping_input = QCheckBox('Enable text wrapping')

        editor_layout = QFormLayout()
        editor_layout.addRow('Font family:', self.font_family_input)
        editor_layout.addRow('Font size:', self.font_size_input)
        editor_layout.addRow('Tab size:', self.tab_size_input)
        editor_layout.addRow('', self.enable_text_wrapping_input)

        editor_group = QGroupBox('Editor')
        editor_group.setLayout(editor_layout)

        # Buttons

        edit_project_button = QPushButton('Edit default project...')
        edit_project_button.clicked.connect(
            lambda: projects.show_edit_dialog('default'))

        save_button = QPushButton('OK')
        save_button.setDefault(True)
        save_button.clicked.connect(self.accept)

        cancel_button = QPushButton('Cancel')
        cancel_button.clicked.connect(self.reject)

        button_layout = QHBoxLayout()
        button_layout.addWidget(edit_project_button, 1, Qt.AlignLeft)
        button_layout.addWidget(save_button, 0, Qt.AlignRight)
        button_layout.addWidget(cancel_button)

        # Main layout

        main_layout = QVBoxLayout()
        main_layout.addWidget(editor_group)
        main_layout.addLayout(button_layout)

        self.setLayout(main_layout)

    def show(self):
        font = QFont(value('editor/font_family'))
        self.font_family_input.setCurrentFont(font)
        self.font_family_input.setCurrentText(QFontInfo(font).family())
        self.font_family_input.setFocus(Qt.OtherFocusReason)

        self.font_size_input.setValue(value('editor/font_size'))

        self.tab_size_input.setValue(value('editor/tab_size'))

        self.enable_text_wrapping_input.setChecked(
            value('editor/enable_text_wrapping'))

        super().show()

    def save(self):
        set_value('editor/font_family',
                  QFontInfo(self.font_family_input.currentFont()).family())
        set_value('editor/font_size', self.font_size_input.value())
        set_value('editor/tab_size', self.tab_size_input.value())
        set_value('editor/enable_text_wrapping',
                  self.enable_text_wrapping_input.isChecked())

        edit_dialog_saved().emit()
Exemplo n.º 21
0
class GlobalFontDialog(widgets.dialog.Dialog):
    def __init__(self, parent=None):
        super(GlobalFontDialog, self).__init__(parent)
        self._messageLabel.setWordWrap(True)
        
        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.mainWidget().setLayout(layout)
        
        self.romanLabel = QLabel()
        self.romanCombo = QFontComboBox()
        self.sansLabel = QLabel()
        self.sansCombo = QFontComboBox()
        self.typewriterLabel = QLabel()
        self.typewriterCombo = QFontComboBox(fontFilters=QFontComboBox.MonospacedFonts)
        
        layout.addWidget(self.romanLabel, 0, 0)
        layout.addWidget(self.romanCombo, 0, 1, 1, 2)
        layout.addWidget(self.sansLabel, 1, 0)
        layout.addWidget(self.sansCombo, 1, 1, 1, 2)
        layout.addWidget(self.typewriterLabel, 2, 0)
        layout.addWidget(self.typewriterCombo, 2, 1, 1, 2)
        
        self.loadSettings()
        self.finished.connect(self.saveSettings)
        app.translateUI(self)
        
    def translateUI(self):
        self.setWindowTitle(app.caption(_("Global Fonts")))
        self.setMessage(_(
            "Please select the three global fonts to use for "
            r"<code>\roman</code>, <code>\sans</code>, and <code>\typewriter</code> "
            "respectively."))
        self.romanLabel.setText(_("Roman Font:"))
        self.sansLabel.setText(_("Sans Font:"))
        self.typewriterLabel.setText(_("Typewriter Font:"))
    
    def romanFont(self):
        return self.romanCombo.currentFont().family()
    
    def setromanFont(self, family):
        self.romanCombo.setCurrentFont(QFont(family))
    
    def sansFont(self):
        return self.sansCombo.currentFont().family()
    
    def setSansFont(self, family):
        self.sansCombo.setCurrentFont(QFont(family))
    
    def typewriterFont(self):
        return self.typewriterCombo.currentFont().family()
    
    def settypewriterFont(self, family):
        self.typewriterCombo.setCurrentFont(QFont(family))
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("global_font_dialog")
        roman = s.value("roman", "Century Schoolbook L", str)
        self.romanCombo.setCurrentFont(QFont(roman))
        sans = s.value("sans", "sans-serif", str)
        self.sansCombo.setCurrentFont(QFont(sans))
        typewriter = s.value("typewriter", "monospace", str)
        self.typewriterCombo.setCurrentFont(QFont(typewriter))
    
    def saveSettings(self):
        s = QSettings()
        s.beginGroup("global_font_dialog")
        s.setValue("roman", self.romanCombo.currentFont().family())
        s.setValue("sans", self.sansCombo.currentFont().family())
        s.setValue("typewriter", self.typewriterCombo.currentFont().family())
Exemplo n.º 22
0
class LogTool(preferences.Group):
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)

        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)

        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)

        self.hideauto = QCheckBox(toggled=self.changed)
        layout.addWidget(self.hideauto)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("LilyPond Log"))
        self.fontLabel.setText(_("Font:"))
        self.showlog.setText(_("Show log when a job is started"))
        self.rawview.setText(_("Display plain log output"))
        self.rawview.setToolTip(_(
            "If checked, Frescobaldi will not shorten filenames in the log output."""))
        self.hideauto.setText(_("Hide automatic engraving jobs"))
        self.hideauto.setToolTip(_(
            "If checked, Frescobaldi will not show the log for automatically\n"
            "started engraving jobs (LilyPond->Auto-engrave)."))

    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))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("log")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
        s.setValue("show_on_start", self.showlog.isChecked())
        s.setValue("rawview", self.rawview.isChecked())
        s.setValue("hide_auto_engrave", self.hideauto.isChecked())
Exemplo n.º 23
0
class SettingsDialog(QDialog):
    def __init__(self, settings: Settings):
        super(SettingsDialog, self).__init__()
        self.settings = settings
        self.setWindowTitle("Sticky Note - Settings")
        self.layout = QFormLayout()

        self.fontSizeBox = QComboBox(self)
        for i in settings.getAllFontSizes():
            self.fontSizeBox.addItem(str(i))
        self.fontSizeBox.setCurrentText(str(settings.getFontSize()))
        self.layout.addRow("Font size", self.fontSizeBox)
        self.fontSizeBox.currentIndexChanged.connect(self.fontSizeChanged)

        self.fontFamilyBox = QFontComboBox(self)
        self.layout.addRow("Font Family", self.fontFamilyBox)
        self.fontFamilyBox.setCurrentFont(QFont(settings.getFontFamily()))
        self.fontFamilyBox.currentIndexChanged.connect(self.fontFamilyChanged)

        self.colorButton = QPushButton('', self)
        color = QColor(settings.getFontColor())
        self.fontColorChanged(color)
        self.colorButton.clicked.connect(self.showColors)
        self.layout.addRow("Font Color", self.colorButton)

        isAutoStartCheckBox = QCheckBox("Enable start on startup", self)
        #self.layout.addRow("", isAutoStartCheckBox)
        isAutoStartCheckBox.stateChanged.connect(self.actionEnableAutoStart)
        isAutoStartCheckBox.setChecked(settings.getStartOnStartup())

        QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self.buttonBox = QDialogButtonBox(QBtn)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.layout.addRow(self.buttonBox)

        self.setLayout(self.layout)
        self.setWindowFlags(Qt.Window)
        self.setFixedSize(350, 150)

    def fontColorChanged(self, color):
        if (color.isValid()):
            self.colorButton.setStyleSheet(
                "background-color: {0};border-color: {0}".format(color.name()))
            self.settings.setFontColor(color.name())

    def showColors(self):
        colorDialog = QColorDialog()
        color = colorDialog.getColor()
        if color:
            self.fontColorChanged(color)

    def fontSizeChanged(self):
        fontSize = str(self.fontSizeBox.currentText())
        self.settings.setFontSize(fontSize)

    def fontFamilyChanged(self):
        fontFamily = str(self.fontFamilyBox.currentText())
        self.settings.setFontFamily(fontFamily)

    def accept(self):
        ConfigParser.config_instance.saveSettings(self.settings)
        self.done(0)
        StickyNoteManager.sticky_note_manager_instance.updateSettings()

    def reject(self):
        self.done(0)

    def actionEnableAutoStart(self, res):
        self.settings.setStartOnStartup(bool(res))
Exemplo n.º 24
0
class SettinInterface(QWidget):
    def __init__(self, screen_scale_rate):
        super(SettinInterface, self).__init__()

        if 1.01 <= screen_scale_rate <= 1.49:
            self.rate = 1.25
            self.px = 80
            self.image_sign = 2
        else:
            self.rate = 1
            self.px = 75
            self.image_sign = 1

        self.get_settin()
        self.setupUi()

    def setupUi(self):

        # 窗口尺寸及不可拉伸
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.resize(404 * self.rate, 576 * self.rate)
        self.setMinimumSize(QSize(404 * self.rate, 576 * self.rate))
        self.setMaximumSize(QSize(404 * self.rate, 576 * self.rate))
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)

        # 窗口标题
        self.setWindowTitle("设置")

        # 窗口样式
        # self.setStyleSheet("QWidget {""font: 9pt \"华康方圆体W7\";"
        #                    "background-image: url(./config/Background%d.jpg);"
        #                    "background-repeat: no-repeat;"
        #                    "background-size:cover;""}" % self.image_sign)
        self.setStyleSheet("QWidget {" "font: 9pt \"微软雅黑\"};")  # 华康方圆体W7

        # 窗口图标
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap(folder_path + "/config/logo.ico"),
                            QIcon.Normal, QIcon.On)
        self.setWindowIcon(self.icon)

        # 顶部工具栏
        self.tabWidget = QTabWidget(self)
        self.tabWidget.setGeometry(
            QRect(-2, 0, 410 * self.rate, 580 * self.rate))
        self.tabWidget.setCurrentIndex(0)

        # 工具栏样式
        self.tabWidget.setStyleSheet("QTabBar::tab {"
                                     "min-width:%dpx;"
                                     "background: rgba(255, 255, 255, 1);"
                                     "}"
                                     "QTabBar::tab:selected {"
                                     "border-bottom: 2px solid #4796f0;"
                                     "}"
                                     "QLabel{"
                                     "background: transparent;"
                                     "}"
                                     "QCheckBox{"
                                     "background: transparent;"
                                     "}" % (self.px))

        # 工具栏2
        self.tab_2 = QWidget()
        self.tabWidget.addTab(self.tab_2, "")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), "设置")

        # 原语言标签
        self.translateSource_label_6 = QLabel(self.tab_2)
        self.translateSource_label_6.setGeometry(
            QRect(30 * self.rate, 20 * self.rate, 151 * self.rate,
                  16 * self.rate))
        self.translateSource_label_6.setText("待识别的语言类型:")

        # 原语言comboBox
        self.language_comboBox = QComboBox(self.tab_2)
        self.language_comboBox.setGeometry(
            QRect(190 * self.rate, 20 * self.rate, 150 * self.rate,
                  22 * self.rate))
        for idx, language_name in enumerate(config.language_name):
            self.language_comboBox.addItem("")
            self.language_comboBox.setItemText(idx, language_name[1])
        self.language_comboBox.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);")
        self.language_comboBox.setCurrentIndex(self.language)

        # 是否显示识别结果checkBox
        self.vis_result_checkBox = QCheckBox(self.tab_2)
        self.vis_result_checkBox.setGeometry(
            QRect(30 * self.rate, 52 * self.rate, 300 * self.rate,
                  16 * self.rate))
        self.vis_result_checkBox.setChecked(self.vis_result)
        self.vis_result_checkBox.setText("可视化识别结果(对识别结果进行修改及导出)")

        # 自动复制到剪贴板checkBox
        self.Clipboard_checkBox = QCheckBox(self.tab_2)
        self.Clipboard_checkBox.setGeometry(
            QRect(30 * self.rate, 80 * self.rate, 231 * self.rate,
                  16 * self.rate))
        self.Clipboard_checkBox.setChecked(self.showClipboard)
        self.Clipboard_checkBox.setText("识别结果自动复制到剪贴板")

        # 字体大小设定标签
        self.fontSize_label = QLabel(self.tab_2)
        self.fontSize_label.setGeometry(
            QRect(30 * self.rate, 120 * self.rate, 145 * self.rate,
                  16 * self.rate))
        self.fontSize_label.setText("显示文字大小:")

        # 字体大小设定
        self.fontSize_spinBox = QSpinBox(self.tab_2)
        self.fontSize_spinBox.setGeometry(
            QRect(190 * self.rate, 120 * self.rate, 50 * self.rate,
                  25 * self.rate))
        self.fontSize_spinBox.setMinimum(10)
        self.fontSize_spinBox.setMaximum(30)
        self.fontSize_spinBox.setStyleSheet(
            "background: rgba(255, 255, 255, 0)")
        self.fontSize_spinBox.setValue(self.fontSize)

        # 字体样式设定标签
        self.translate_label = QLabel(self.tab_2)
        self.translate_label.setGeometry(
            QRect(30 * self.rate, 145 * self.rate, 145 * self.rate,
                  20 * self.rate))
        self.translate_label.setText("显示字体类型:")

        # 字体样式设定
        self.fontComboBox = QFontComboBox(self.tab_2)
        self.fontComboBox.setGeometry(
            QRect(190 * self.rate, 145 * self.rate, 151 * self.rate,
                  25 * self.rate))
        self.fontComboBox.setStyleSheet("background: rgba(255, 255, 255, 0.4)")
        self.fontComboBox.activated[str].connect(self.get_fontType)
        self.ComboBoxFont = QFont(self.fontType)
        self.fontComboBox.setCurrentFont(self.ComboBoxFont)

        # 字体颜色设定标签
        self.colour_label = QLabel(self.tab_2)
        self.colour_label.setGeometry(
            QRect(30 * self.rate, 172 * self.rate, 340 * self.rate,
                  25 * self.rate))
        self.colour_label.setText("显示文字颜色:")

        # 字体颜色按钮
        self.originalColour_toolButton = QToolButton(self.tab_2)
        self.originalColour_toolButton.setGeometry(
            QRect(190 * self.rate, 175 * self.rate, 71 * self.rate,
                  25 * self.rate))
        self.originalColour_toolButton.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4); color: {};".format(
                self.originalColor))
        self.originalColour_toolButton.clicked.connect(
            lambda: self.get_font_color())
        self.originalColour_toolButton.setText("选择颜色")

        # 显示颜色样式checkBox
        self.showColorType_checkBox = QCheckBox(self.tab_2)
        self.showColorType_checkBox.setGeometry(
            QRect(30 * self.rate, 200 * self.rate, 340 * self.rate,
                  20 * self.rate))
        self.showColorType_checkBox.setChecked(self.showColorType)
        self.showColorType_checkBox.setText("是否使用实心字体样式(不勾选则显示描边字体样式)")

        # 截屏键快捷键checkBox
        self.shortcutKey2_checkBox = QCheckBox(self.tab_2)
        self.shortcutKey2_checkBox.setGeometry(
            QRect(30 * self.rate, 250 * self.rate, 160 * self.rate,
                  16 * self.rate))
        self.shortcutKey2_checkBox.setStyleSheet("background: transparent;")
        self.shortcutKey2_checkBox.setChecked(self.showHotKey2)
        self.shortcutKey2_checkBox.setText("是否使用截屏快捷键:")

        # 截屏键的快捷键
        self.HotKey2_ComboBox = QComboBox(self.tab_2)
        self.HotKey2_ComboBox.setGeometry(
            QRect(200 * self.rate, 250 * self.rate, 120 * self.rate,
                  21 * self.rate))
        self.HotKey2_ComboBox.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);")
        for index, HotKey in enumerate(self.HotKeys):
            self.HotKey2_ComboBox.addItem("")
            self.HotKey2_ComboBox.setItemText(index, HotKey)
        self.HotKey2_ComboBox.setCurrentIndex(self.showHotKey1Value2)

        # 翻译键快捷键checkBox
        self.shortcutKey1_checkBox = QCheckBox(self.tab_2)
        self.shortcutKey1_checkBox.setGeometry(
            QRect(30 * self.rate, 280 * self.rate, 160 * self.rate,
                  16 * self.rate))
        self.shortcutKey1_checkBox.setStyleSheet("background: transparent;")
        self.shortcutKey1_checkBox.setChecked(self.showHotKey1)
        self.shortcutKey1_checkBox.setText("是否使用识别快捷键:")

        # 翻译键的快捷键
        self.HotKey1_ComboBox = QComboBox(self.tab_2)
        self.HotKey1_ComboBox.setGeometry(
            QRect(200 * self.rate, 280 * self.rate, 120 * self.rate,
                  21 * self.rate))
        self.HotKey1_ComboBox.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);")
        for index, HotKey in enumerate(self.HotKeys):
            self.HotKey1_ComboBox.addItem("")
            self.HotKey1_ComboBox.setItemText(index, HotKey)
        self.HotKey1_ComboBox.setCurrentIndex(self.showHotKey1Value1)

        # 是否翻译
        self.translate_checkBox = QCheckBox(self.tab_2)
        self.translate_checkBox.setGeometry(
            QRect(30 * self.rate, 315 * self.rate, 300 * self.rate,
                  16 * self.rate))
        self.translate_checkBox.setChecked(self.need_translate)
        self.translate_checkBox.setText("是否翻译为汉语")

        # 是否翻译
        self.show_org_checkBox = QCheckBox(self.tab_2)
        self.show_org_checkBox.setGeometry(
            QRect(30 * self.rate, 340 * self.rate, 300 * self.rate,
                  16 * self.rate))
        self.show_org_checkBox.setChecked(self.showOriginal)
        self.show_org_checkBox.setText("翻译后是否显示原文")

        # 翻译框透明度设定标签1
        self.tab4_label_1 = QLabel(self.tab_2)
        self.tab4_label_1.setGeometry(
            QRect(30 * self.rate, 380 * self.rate, 211 * self.rate,
                  16 * self.rate))
        self.tab4_label_1.setText("调节显示界面的透明度")

        # 翻译框透明度设定
        self.horizontalSlider = QSlider(self.tab_2)
        self.horizontalSlider.setGeometry(
            QRect(30 * self.rate, 400 * self.rate, 347 * self.rate,
                  22 * self.rate))
        self.horizontalSlider.setStyleSheet("background: transparent;")
        self.horizontalSlider.setMaximum(100)
        self.horizontalSlider.setOrientation(Qt.Horizontal)
        self.horizontalSlider.setValue(self.horizontal)
        self.horizontalSlider.valueChanged.connect(self.get_horizontal)

        # 翻译框透明度设定标签2
        self.tab2_label_2 = QLabel(self.tab_2)
        self.tab2_label_2.setGeometry(
            QRect(30 * self.rate, 420 * self.rate, 61 * self.rate,
                  20 * self.rate))
        self.tab2_label_2.setText("完全透明")

        # 翻译框透明度设定标签3
        self.tab2_label_3 = QLabel(self.tab_2)
        self.tab2_label_3.setGeometry(
            QRect(310 * self.rate, 420 * self.rate, 71 * self.rate,
                  20 * self.rate))
        self.tab2_label_3.setText("完全不透明")

        # 工具栏3
        self.tab_3 = QWidget()
        self.tabWidget.addTab(self.tab_3, "")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), "关于")

        self.tab3_label = QLabel(self.tab_3)
        self.tab3_label.setGeometry(
            QRect(30 * self.rate, 75 * self.rate, 100 * self.rate,
                  40 * self.rate))
        self.tab3_label.setText("说明:")

        self.tab3_label2 = QLabel(self.tab_3)
        self.tab3_label2.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.tab3_label2.setWordWrap(True)
        self.tab3_label2.setGeometry(
            QRect(50 * self.rate, 100 * self.rate, 400 * self.rate,
                  80 * self.rate))
        self.tab3_label2.setText(
            "Dango-OCR是一款开源的OCR文字识别软件。\n如果在使用过程中有什么问题或者建议,欢迎微信交流(itlane)\n"
            "或者在github(https://github.com/zhangming8/Dango-ocr)\n上留言")

        self.tab3_label3 = QLabel(self.tab_3)
        self.tab3_label3.setWordWrap(True)
        self.tab3_label3.setGeometry(
            QRect(30 * self.rate, 350 * self.rate, 400 * self.rate,
                  80 * self.rate))
        self.tab3_label3.setText(
            "参考:\n        https://github.com/zhangming8/ocr_algo_server\n        "
            "https://github.com/PaddlePaddle/PaddleOCR\n        "
            "https://github.com/PantsuDango/Dango-Translator")

        # 设置保存按钮
        self.SaveButton = QPushButton(self)
        self.SaveButton.setGeometry(
            QRect(85 * self.rate, 515 * self.rate, 90 * self.rate,
                  30 * self.rate))
        self.SaveButton.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);font: 12pt;")
        self.SaveButton.setText("保存设置")

        # 设置返回按钮
        self.CancelButton = QPushButton(self)
        self.CancelButton.setGeometry(
            QRect(232 * self.rate, 515 * self.rate, 90 * self.rate,
                  30 * self.rate))
        self.CancelButton.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);font: 12pt")
        self.CancelButton.setText("退 出")

    def get_settin(self):  # 获取所有预设值

        with open(folder_path + '/config/settin.json') as file:
            self.data = load(file)

        # 获取各翻译源颜色预设值
        self.originalColor = self.data["fontColor"]["original"]

        # 获取翻译字体大小预设值
        self.fontSize = self.data["fontSize"]

        # 获取翻译字体样式预设值
        self.fontType = self.data["fontType"]

        # 获取颜色样式预设值
        self.showColorType = self.data["showColorType"]
        if self.showColorType == "True":
            self.showColorType = True
        else:
            self.showColorType = False

        # 获取是否显示原文预设值
        self.showOriginal = self.data["showOriginal"]
        if self.showOriginal == "True":
            self.showOriginal = True
        else:
            self.showOriginal = False

        # 获取是否将原文复制到剪贴板预设值
        self.showClipboard = self.data["showClipboard"]
        if self.showClipboard == "True":
            self.showClipboard = True
        else:
            self.showClipboard = False

        self.vis_result = self.data.get("vis_result", False)
        if self.vis_result == "True":
            self.vis_result = True
        else:
            self.vis_result = False

        self.need_translate = self.data.get("need_translate", False)
        if self.need_translate == "True":
            self.need_translate = True
        else:
            self.need_translate = False

        # 所有可设置的快捷键
        self.HotKeys = [
            'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11',
            'F12', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Back',
            'Tab', 'Space', 'Left', 'Up', 'Right', 'Down', 'Delete', 'Numpad0',
            'Numpad1', 'Numpad2', 'Numpad3', 'Numpad4', 'Numpad5', 'Numpad6',
            'Numpad7', 'Numpad8', 'Numpad9'
        ]
        self.QtHotKeys = [
            Qt.Key_F1, Qt.Key_F2, Qt.Key_F3, Qt.Key_F4, Qt.Key_F5, Qt.Key_F6,
            Qt.Key_F7, Qt.Key_F8, Qt.Key_F9, Qt.Key_F10, Qt.Key_F11,
            Qt.Key_F12, Qt.Key_A, Qt.Key_B, Qt.Key_C, Qt.Key_D, Qt.Key_E,
            Qt.Key_F, Qt.Key_G, Qt.Key_H, Qt.Key_I, Qt.Key_J, Qt.Key_K,
            Qt.Key_L, Qt.Key_M, Qt.Key_N, Qt.Key_O, Qt.Key_P, Qt.Key_Q,
            Qt.Key_R, Qt.Key_S, Qt.Key_T, Qt.Key_U, Qt.Key_V, Qt.Key_W,
            Qt.Key_X, Qt.Key_Y, Qt.Key_Z, Qt.Key_0, Qt.Key_1, Qt.Key_2,
            Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6, Qt.Key_7, Qt.Key_8,
            Qt.Key_9, Qt.Key_Back, Qt.Key_Tab, Qt.Key_Space, Qt.Key_Left,
            Qt.Key_Up, Qt.Key_Right, Qt.Key_Down, Qt.Key_Delete, Qt.Key_0,
            Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6,
            Qt.Key_7, Qt.Key_8, Qt.Key_9
        ]
        self.QtHotKeysMaps = {}
        for idx in range(len(self.HotKeys)):
            self.QtHotKeysMaps[self.HotKeys[idx]] = self.QtHotKeys[idx]

        # 获取翻译键快捷键的热键预设值
        self.showHotKey1Value1 = self.data["showHotKeyValue1"]
        self.showHotKey1Value1 = self.HotKeys.index(self.showHotKey1Value1)

        # 获取范围键快捷键的热键预设值
        self.showHotKey1Value2 = self.data["showHotKeyValue2"]
        self.showHotKey1Value2 = self.HotKeys.index(self.showHotKey1Value2)

        # 获取是否启用翻译键快捷键预设值
        self.showHotKey1 = self.data["showHotKey1"]
        if self.showHotKey1 == "True":
            self.showHotKey1 = True
        else:
            self.showHotKey1 = False

        # 获取是否启用范围键快捷键预设值
        self.showHotKey2 = self.data["showHotKey2"]
        if self.showHotKey2 == "True":
            self.showHotKey2 = True
        else:
            self.showHotKey2 = False

        # 获取文本框透明度预设值
        self.horizontal = self.data["horizontal"]

        # 获取翻译语言预设值
        self.language = config.language_map_reverse[self.data["language"]]

    def get_font_color(self):  # 各翻译源字体颜色
        color = QColorDialog.getColor()
        self.originalColor = color.name()
        self.originalColour_toolButton.setStyleSheet(
            "background: rgba(255, 255, 255, 0.4);color: {};".format(
                color.name()))
        self.data["fontColor"]["original"] = self.originalColor

    def get_fontType(self, text):  # 字体样式

        self.fontType = text
        self.data["fontType"] = self.fontType

    def showColorType_state(self):  # 颜色样式

        if self.showColorType_checkBox.isChecked():
            self.showColorType = "True"
        else:
            self.showColorType = "False"
        self.data["showColorType"] = self.showColorType

    def showClipboard_state(self):  # 是否将原文自动复制到剪贴板

        if self.Clipboard_checkBox.isChecked():
            self.showClipboard = "True"
        else:
            self.showClipboard = "False"
        self.data["showClipboard"] = self.showClipboard

    def VisResult_state(self):
        if self.vis_result_checkBox.isChecked():
            self.vis_result = "True"
        else:
            self.vis_result = "False"
        self.data["vis_result"] = self.vis_result

    def NeedTranslate_state(self):
        if self.translate_checkBox.isChecked():
            self.need_translate = "True"
        else:
            self.need_translate = "False"
        self.data["need_translate"] = self.need_translate

    def ShowOrigion_state(self):
        if self.show_org_checkBox.isChecked():
            self.showOriginal = "True"
        else:
            self.showOriginal = "False"
        self.data["showOriginal"] = self.showOriginal

    def showHotKey1_state(self):  # 是否启用翻译键快捷键

        if self.shortcutKey1_checkBox.isChecked():
            self.showHotKey1 = "True"
        else:
            self.showHotKey1 = "False"
        self.data["showHotKey1"] = self.showHotKey1

    def showHotKey2_state(self):  # 是否启用范围键快捷键

        if self.shortcutKey2_checkBox.isChecked():
            self.showHotKey2 = "True"
        else:
            self.showHotKey2 = "False"
        self.data["showHotKey2"] = self.showHotKey2

    def get_horizontal(self):  # 文本框透明度

        self.horizontal = self.horizontalSlider.value()
        self.data["horizontal"] = self.horizontal

    def save_fontSize(self):  # 翻译源字体大小

        self.data["fontSize"] = self.fontSize_spinBox.value()

    def range(self):

        with open(folder_path + '/config/settin.json') as file:
            data1 = load(file)

            self.data["range"]["X1"] = data1["range"]["X1"]
            self.data["range"]["Y1"] = data1["range"]["Y1"]
            self.data["range"]["X2"] = data1["range"]["X2"]
            self.data["range"]["Y2"] = data1["range"]["Y2"]

    def save_language(self):  # 保存翻译语种

        self.data["language"] = config.language_map[
            self.language_comboBox.currentIndex()][0]

    def save_showHotKeyValue1(self):  # 保存翻译键快捷键
        HotKey_index = self.HotKey1_ComboBox.currentIndex()
        self.data["showHotKeyValue1"] = self.HotKeys[HotKey_index]

    def save_showHotKeyValue2(self):  # 保存范围键快捷键
        HotKey_index = self.HotKey2_ComboBox.currentIndex()
        self.data["showHotKeyValue2"] = self.HotKeys[HotKey_index]

    def save_settin(self):

        self.range()
        self.get_horizontal()
        self.save_fontSize()

        self.showColorType_state()
        self.showClipboard_state()
        self.VisResult_state()
        self.NeedTranslate_state()
        self.ShowOrigion_state()
        self.save_language()

        self.showHotKey1_state()
        self.showHotKey2_state()
        self.save_showHotKeyValue1()
        self.save_showHotKeyValue2()

        with open(folder_path + '/config/settin.json', 'w') as file:
            dump(self.data, file, indent=2)

        MessageBox('保存设置', '保存成功啦 ヾ(๑╹◡╹)ノ"')
Exemplo n.º 25
0
    def __init__(self, data: TextData, parent, printable):
        super().__init__(data, parent, printable)

        font = data.getQFont()

        self.setMinimumWidth(256)

        self.edit_text = QLineEdit(self.data.text, self)
        self.edit_text.textChanged.connect(self.text_changed)
        self.layout.addWidget(QLabel('Text:'))
        self.layout.addWidget(self.edit_text)

        self.button_font = QPushButton(self.get_font_name())
        self.button_font.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        self.button_font.clicked.connect(self.button_font_clicked)

        button_default = QPushButton('Set as default', self)
        button_default.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        button_default.clicked.connect(self.default_clicked)

        font_layout = QVBoxLayout()
        font_family = QFontComboBox(self)
        font_family.setCurrentFont(font)
        font_family.currentFontChanged.connect(self.font_changed)
        self.font_family = font_family
        font_layout.addWidget(font_family)
        font_group = QGroupBox('Font:', self)
        font_group.setLayout(font_layout)

        self.layout.addWidget(font_group)

        buttons = QHBoxLayout()
        buttons.setSpacing(0)
        font_size = QSpinBox(self)
        font_size.setValue(font.pixelSize())
        font_size.valueChanged.connect(self.size_changed)
        self.font_size = font_size
        buttons.addWidget(QLabel('Size:'))
        buttons.addWidget(font_size)
        buttons.addWidget(QLabel('px'))
        buttons.addStretch()
        # buttons.addWidget(self.button_font)

        adjusted_size = QLabel(self)
        self.adjusted_size_label = adjusted_size

        self.auto_size = QCheckBox('Automatically scale font', self)
        self.auto_size.stateChanged.connect(self.auto_size_changed)
        buttons.addWidget(self.auto_size)

        buttons2 = QHBoxLayout()

        buttons2.addWidget(adjusted_size)
        buttons2.addWidget(button_default)

        font_layout.addLayout(buttons)
        font_layout.addLayout(buttons2)

        # font_preview = QLabel(self.data.text)
        # font_preview.setFont(font)
        # self.layout.addWidget(font_preview)

        self.layout.addStretch()
Exemplo n.º 26
0
class NoteView(QWidget):

    def __init__(self, parent: QWidget, noteViewManager: NoteViewManager, note: Note):
        super(QWidget, self).__init__(parent)

        self.noteViewManager = noteViewManager
        self.note = note
        self.notebook = self.noteViewManager.notebook
        self.setLayout(QVBoxLayout(self))

        self.lay = self.layout()

        self.noteContentEdit = NoteContentEdit(self, self.notebook, note)
        self.noteContentEdit.anchorClicked.connect(self.onAnchorClicked)

        self.attachmentsView = NoteAttachmentsView(self, self.notebook, note)

        self.attachmentsBox = CollapsibleBox(title="Attachments")

        tmpLay = QVBoxLayout()
        tmpLay.addWidget(self.attachmentsView)
        self.attachmentsBox.setContentLayout(tmpLay)
        self.attachmentsBox.setContentsMargins(0, 0, 0, 0)

        self.initFormatbar()

        self.fontBox.setCurrentFont(self.notebook.settings.font())
        self.fontSize.setValue(self.notebook.settings.font().pointSize())

        self.noteContentEdit.currentCharFormatChanged.connect(self.onCurrentCharFormatChanged)

        self.lay.addWidget(self.noteContentEdit)
        self.lay.addWidget(self.attachmentsBox)

    def initFormatbar(self):

        self.fontBox = QFontComboBox()
        self.fontBox.setCurrentFont(self.noteContentEdit.font())
        self.fontBox.currentFontChanged.connect(lambda font: self.noteContentEdit.setCurrentFont(font))

        # self.families = list(self.fontBox.itemText(i) for i in range(self.fontBox.count()))
        #
        # with open("fonts.txt", "w") as f:
        #     for name in self.families:
        #         f.write(name + "\r\n")

        self.fontSize = QSpinBox()
        self.fontSize.setValue(self.noteContentEdit.fontPointSize())
        self.fontSize.adjustSize()
        self.fontSize.setSuffix(" pt")

        self.fontSize.valueChanged.connect(lambda size: self.noteContentEdit.setFontPointSize(size))

        fontColor = QAction(QIcon("icons/font-color.png"), "Change font color", self)
        fontColor.triggered.connect(self.fontColorChanged)

        boldAction = QAction(QIcon("icons/bold.png"), "Bold", self)
        boldAction.triggered.connect(self.bold)

        italicAction = QAction(QIcon("icons/italic.png"), "Italic", self)
        italicAction.triggered.connect(self.italic)

        underlAction = QAction(QIcon("icons/underline.png"), "Underline", self)
        underlAction.triggered.connect(self.underline)

        strikeAction = QAction(QIcon("icons/strike.png"), "Strike-out", self)
        strikeAction.triggered.connect(self.strike)

        superAction = QAction(QIcon("icons/superscript.png"), "Superscript", self)
        superAction.triggered.connect(self.superScript)

        subAction = QAction(QIcon("icons/subscript.png"), "Subscript", self)
        subAction.triggered.connect(self.subScript)

        alignLeft = QAction(QIcon("icons/align-left.png"), "Align left", self)
        alignLeft.triggered.connect(self.alignLeft)

        alignCenter = QAction(QIcon("icons/align-center.png"), "Align center", self)
        alignCenter.triggered.connect(self.alignCenter)

        alignRight = QAction(QIcon("icons/align-right.png"), "Align right", self)
        alignRight.triggered.connect(self.alignRight)

        alignJustify = QAction(QIcon("icons/align-justify.png"), "Align justify", self)
        alignJustify.triggered.connect(self.alignJustify)

        indentAction = QAction(QIcon("icons/indent.png"), "Indent Area", self)
        indentAction.setShortcut("Ctrl+Tab")
        indentAction.triggered.connect(self.indent)

        dedentAction = QAction(QIcon("icons/dedent.png"), "Dedent Area", self)
        dedentAction.setShortcut("Shift+Tab")
        dedentAction.triggered.connect(self.dedent)

        backColor = QAction(QIcon("icons/highlight.png"), "Change background color", self)
        backColor.triggered.connect(self.highlight)

        bulletAction = QAction(QIcon("icons/bullet.png"), "Insert bullet List", self)
        bulletAction.setStatusTip("Insert bullet list")
        bulletAction.setShortcut("Ctrl+Shift+B")
        bulletAction.triggered.connect(self.bulletList)

        numberedAction = QAction(QIcon("icons/number.png"), "Insert numbered List", self)
        numberedAction.setStatusTip("Insert numbered list")
        numberedAction.setShortcut("Ctrl+Shift+L")
        numberedAction.triggered.connect(self.numberList)

        dateTimeAction = QAction(QIcon("icons/calender.png"), "Insert current date/time", self)
        dateTimeAction.setStatusTip("Insert current date/time")
        dateTimeAction.setShortcut("Ctrl+D")
        dateTimeAction.triggered.connect(self.insertDateTime)

        wordCountAction = QAction(QIcon("icons/count.png"), "See word/symbol count", self)
        wordCountAction.setStatusTip("See word/symbol count")
        wordCountAction.setShortcut("Ctrl+W")
        wordCountAction.triggered.connect(self.wordCount)

        tableAction = QAction(QIcon("icons/table.png"), "Insert table", self)
        tableAction.setStatusTip("Insert table")
        tableAction.setShortcut("Ctrl+T")
        tableAction.triggered.connect(self.insertTable)

        imageAction = QAction(QIcon("icons/image.png"), "Insert image", self)
        imageAction.setStatusTip("Insert image")
        imageAction.setShortcut("Ctrl+Shift+I")
        imageAction.triggered.connect(self.insertImage)

        linkAction = QAction(QIcon("icons/insert_link.png"), "Insert link", self)
        linkAction.setStatusTip("Insert link")
        # linkAction.setShortcut("Ctrl+Shift+L")
        linkAction.triggered.connect(self.insertLink)

        linkNoteAction = QAction(QIcon("icons/insert_note_link.png"), "Insert note link", self)
        linkNoteAction.setStatusTip("Insert note link")
        # linkAction.setShortcut("Ctrl+Shift+L")
        linkNoteAction.triggered.connect(self.insertNoteLink)

        attachAction = QAction(QIcon("icons/attach.png"), "Insert attachment", self)
        attachAction.setStatusTip("Insert attachment")
        attachAction.triggered.connect(self.insertAttachment)

        printAction = QAction(QIcon("icons/print.png"), "Print document", self)
        printAction.setStatusTip("Print document")
        printAction.setShortcut("Ctrl+P")
        printAction.triggered.connect(self.printHandler)

        previewAction = QAction(QIcon("icons/preview.png"), "Page view", self)
        previewAction.setStatusTip("Preview page before printing")
        previewAction.setShortcut("Ctrl+Shift+P")
        previewAction.triggered.connect(self.preview)

        viewHistoryAction = QAction(QIcon("icons/history.png"), "Show history", self)
        viewHistoryAction.setStatusTip("View note content history")
        viewHistoryAction.setShortcut("Ctrl+H")
        viewHistoryAction.triggered.connect(self.showHistory)

        self.formatbar = QToolBar("Format")
        self.formatbar.setIconSize(QSize(16, 16))

        self.lay.addWidget(self.formatbar)

        self.formatbar.addWidget(self.fontBox)
        self.formatbar.addWidget(self.fontSize)

        self.formatbar.addSeparator()

        self.formatbar.addAction(fontColor)
        self.formatbar.addAction(backColor)

        self.formatbar.addSeparator()

        self.formatbar.addAction(boldAction)
        self.formatbar.addAction(italicAction)
        self.formatbar.addAction(underlAction)
        self.formatbar.addAction(strikeAction)
        self.formatbar.addAction(superAction)
        self.formatbar.addAction(subAction)

        self.formatbar.addSeparator()

        self.formatbar.addAction(alignLeft)
        self.formatbar.addAction(alignCenter)
        self.formatbar.addAction(alignRight)
        self.formatbar.addAction(alignJustify)

        self.formatbar.addSeparator()

        self.formatbar.addAction(indentAction)
        self.formatbar.addAction(dedentAction)

        self.formatbar.addSeparator()

        self.formatbar.addAction(bulletAction)
        self.formatbar.addAction(numberedAction)

        self.formatbar.addSeparator()

        self.formatbar.addAction(wordCountAction)
        self.formatbar.addAction(tableAction)
        self.formatbar.addAction(dateTimeAction)
        self.formatbar.addAction(imageAction)

        self.formatbar.addSeparator()

        self.formatbar.addAction(linkAction)
        self.formatbar.addAction(linkNoteAction)
        self.formatbar.addAction(attachAction)

        self.formatbar.addSeparator()

        self.formatbar.addAction(viewHistoryAction)
        self.formatbar.addAction(previewAction)
        self.formatbar.addAction(printAction)

    def saveChanges(self):
        self.noteContentEdit.saveChanges()

    def fontColorChanged(self):

        # Get a color from the text dialog
        color = QColorDialog.getColor()

        # Set it as the new text color
        self.noteContentEdit.setTextColor(color)

    def highlight(self):

        color = QColorDialog.getColor()

        self.noteContentEdit.setTextBackgroundColor(color)

    def bold(self):

        if self.noteContentEdit.fontWeight() == QFont.Bold:

            self.noteContentEdit.setFontWeight(QFont.Normal)

        else:

            self.noteContentEdit.setFontWeight(QFont.Bold)

    def italic(self):

        state = self.noteContentEdit.fontItalic()

        self.noteContentEdit.setFontItalic(not state)

    def underline(self):

        state = self.noteContentEdit.fontUnderline()

        self.noteContentEdit.setFontUnderline(not state)

    def strike(self):

        # Grab the text's format
        fmt = self.noteContentEdit.currentCharFormat()

        # Set the fontStrikeOut property to its opposite
        fmt.setFontStrikeOut(not fmt.fontStrikeOut())

        # And set the next char format
        self.noteContentEdit.setCurrentCharFormat(fmt)

    def superScript(self):

        # Grab the current format
        fmt = self.noteContentEdit.currentCharFormat()

        # And get the vertical alignment property
        align = fmt.verticalAlignment()

        # Toggle the state
        if align == QTextCharFormat.AlignNormal:

            fmt.setVerticalAlignment(QTextCharFormat.AlignSuperScript)

        else:

            fmt.setVerticalAlignment(QTextCharFormat.AlignNormal)

        # Set the new format
        self.noteContentEdit.setCurrentCharFormat(fmt)

    def subScript(self):

        # Grab the current format
        fmt = self.noteContentEdit.currentCharFormat()

        # And get the vertical alignment property
        align = fmt.verticalAlignment()

        # Toggle the state
        if align == QTextCharFormat.AlignNormal:

            fmt.setVerticalAlignment(QTextCharFormat.AlignSubScript)

        else:

            fmt.setVerticalAlignment(QTextCharFormat.AlignNormal)

        # Set the new format
        self.noteContentEdit.setCurrentCharFormat(fmt)

    def alignLeft(self):
        self.noteContentEdit.setAlignment(Qt.AlignLeft)

    def alignRight(self):
        self.noteContentEdit.setAlignment(Qt.AlignRight)

    def alignCenter(self):
        self.noteContentEdit.setAlignment(Qt.AlignCenter)

    def alignJustify(self):
        self.noteContentEdit.setAlignment(Qt.AlignJustify)

    def indent(self):

        # Grab the cursor
        cursor = self.noteContentEdit.textCursor()

        if cursor.hasSelection():

            # Store the current line/block number
            temp = cursor.blockNumber()

            # Move to the selection's end
            cursor.setPosition(cursor.anchor())

            # Calculate range of selection
            diff = cursor.blockNumber() - temp

            direction = QTextCursor.Up if diff > 0 else QTextCursor.Down

            # Iterate over lines (diff absolute value)
            for n in range(abs(diff) + 1):
                # Move to start of each line
                cursor.movePosition(QTextCursor.StartOfLine)

                # Insert tabbing
                cursor.insertText("\t")

                # And move back up
                cursor.movePosition(direction)

        # If there is no selection, just insert a tab
        else:

            cursor.insertText("\t")

    def handleDedent(self, cursor):

        cursor.movePosition(QTextCursor.StartOfLine)

        # Grab the current line
        line = cursor.block().text()

        # If the line starts with a tab character, delete it
        if line.startswith("\t"):

            # Delete next character
            cursor.deleteChar()

        # Otherwise, delete all spaces until a non-space character is met
        else:
            for char in line[:8]:

                if char != " ":
                    break

                cursor.deleteChar()

    def dedent(self):

        cursor = self.noteContentEdit.textCursor()

        if cursor.hasSelection():

            # Store the current line/block number
            temp = cursor.blockNumber()

            # Move to the selection's last line
            cursor.setPosition(cursor.anchor())

            # Calculate range of selection
            diff = cursor.blockNumber() - temp

            direction = QTextCursor.Up if diff > 0 else QTextCursor.Down

            # Iterate over lines
            for n in range(abs(diff) + 1):
                self.handleDedent(cursor)

                # Move up
                cursor.movePosition(direction)

        else:
            self.handleDedent(cursor)

    def bulletList(self):

        cursor = self.noteContentEdit.textCursor()

        # Insert bulleted list
        cursor.insertList(QTextListFormat.ListDisc)

    def numberList(self):

        cursor = self.noteContentEdit.textCursor()

        # Insert list with numbers
        cursor.insertList(QTextListFormat.ListDecimal)

    def insertTable(self):
        Table(parent=self, text=self.noteContentEdit).show()

    def insertDateTime(self):
        # Grab cursor
        cursor = self.noteContentEdit.textCursor()

        datetime = strftime(self.noteViewManager.notebook.settings.date_time_insert_format())

        # Insert the comboBox's current text
        cursor.insertText(datetime)

    def wordCount(self):

        wc = WordCount(self, self.noteContentEdit)
        wc.text = self.noteContentEdit

        wc.getText()

        wc.show()

    def insertHyperLynk(self, url: str):
        cursor = QTextCursor(self.noteContentEdit.document())
        format = QTextCharFormat()
        format.setAnchor(True)
        format.setAnchorHref(url)
        cursor.mergeBlockCharFormat(format)

    def insertLink(self):

        dialog = LinkAddDialog(self.noteContentEdit)
        result = dialog.exec_()

        if result == QDialog.Accepted:
            cursor = self.noteContentEdit.textCursor()
            linkAdress = dialog.linkAdress
            linkCaption = dialog.linkCaption

            url = QUrl.fromUserInput(linkAdress)
            linkAdress = url.toString()
            cursor.insertHtml(f"<a href=\"{linkAdress}\" >{linkCaption}</a>")

    def insertNoteLink(self):
        cursor = self.noteContentEdit.textCursor()

        filename = QFileDialog.getOpenFileName(self.noteContentEdit, 'Open File', ".", "(*.nbf)")[0]

        if filename:
            notebook = Notebook.from_file(filename)
            dialog = NoteSelectDialog(parent=self, notebook=notebook)
            result = dialog.exec_()

            if result == QDialog.Accepted:
                url: QUrl = QUrl.fromLocalFile(filename)
                url.setScheme("notesmanager")
                query = QUrlQuery()
                query.addQueryItem("uuid", str(dialog.selectedNote.uuid))
                url.setQuery(query)
                cursor.insertHtml(f"<a href=\"{url.toString()}\" >{dialog.caption}</a>")

        # self.text.setReadOnly(True)
        # self.insertHyperLynk("www.google.com")

    def preview(self):

        # Open preview dialog
        preview = QPrintPreviewDialog()

        # If a print is requested, open print dialog
        preview.paintRequested.connect(lambda p: self.noteContentEdit.print_(p))

        preview.exec_()

    def printHandler(self):

        # Open printing dialog
        dialog = QPrintDialog()

        if dialog.exec_() == QDialog.Accepted:
            self.noteContentEdit.document().print_(dialog.printer())

    def showHistory(self):
        self.noteViewManager.saveChanges()

        dialog = NoteHistoryView(self, self.note)

        if dialog.exec_() == QDialog.Accepted:
            self.note.restore(dialog.restoreIndex)
            self.noteContentEdit.setHtml(self.note.content)

    def insertImage(self):

        # Get image file name
        # PYQT5 Returns a tuple in PyQt5
        filename = \
            QFileDialog.getOpenFileName(self.noteContentEdit, 'Insert image', ".",
                                        "Images (*.png *.xpm *.jpg *.bmp *.gif)")[
                0]

        if filename:

            # Create image object
            image = QImage(filename)

            # Error if unloadable
            if image.isNull():

                popup = QMessageBox(QMessageBox.Critical,
                                    "Image load error",
                                    "Could not load image file!",
                                    QMessageBox.Ok,
                                    self.noteContentEdit)
                popup.show()

            else:

                # from PIL import Image, ImageDraw
                import base64
                import os

                content_type = "image/" + os.path.splitext(filename)[1][1:]
                raw_data = base64.b64encode(open(filename, "rb").read())
                uri = ("data:" +
                       content_type + ";" +
                       "base64," + raw_data.decode())
                html_code = '<img src="' + uri + '"/>'
                print(html_code)

                cursor = self.noteContentEdit.textCursor()
                cursor.insertHtml(html_code)
                # random_filename = self.get_random_file_name(os.path.splitext(filename)[1][1:])
                # from shutil import copy
                # copy(filename, dst=random_filename)
                # cursor.insertImage(image, random_filename)
                # cursor.insertHtml(html)

    def onCurrentCharFormatChanged(self, format: QTextCharFormat) -> None:
        if format.isAnchor():
            new_format = QTextCharFormat()
            new_format.setFont(self.fontBox.currentFont())
            new_format.setFontPointSize(self.fontSize.value())
            self.noteContentEdit.setCurrentCharFormat(new_format)

    def onAnchorClicked(self, url: QUrl):
        from notes.ui.MainWindow import MainWindow
        import webbrowser

        host = url.host()
        print(url.scheme())
        scheme = url.scheme()

        if scheme == "http" or scheme == "https":
            webbrowser.open(url.toString())
        elif scheme == "notesmanager":
            url.setScheme("file")

            local_path = url.toLocalFile()
            query = QUrlQuery(url)
            uuid = query.queryItemValue("uuid")

            if local_path == self.notebook.attachment_base.filename:
                self.noteViewManager.openNote(self.noteViewManager.notebook.get_note_by_uuid(uuid))
            else:
                spawn = MainWindow(None, local_path, uuid)
                spawn.show()

    def insertAttachment(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.ExistingFiles)

        filenames = dialog.getOpenFileNames(self, 'Insert attachments', ".")[0]

        self.attachmentsView.addAttachments(filenames)
Exemplo n.º 27
0
class FontsColors(preferences.Page):
    def __init__(self, dialog):
        super(FontsColors, self).__init__(dialog)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.scheme = SchemeSelector(self)
        layout.addWidget(self.scheme)

        self.printScheme = QCheckBox()
        layout.addWidget(self.printScheme)

        hbox = QHBoxLayout()
        self.tree = QTreeWidget(self)
        self.tree.setHeaderHidden(True)
        self.tree.setAnimated(True)
        self.stack = QStackedWidget(self)
        hbox.addWidget(self.tree)
        hbox.addWidget(self.stack)
        layout.addLayout(hbox)

        hbox = QHBoxLayout()
        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox()
        self.fontSize = QDoubleSpinBox()
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)
        hbox.addWidget(self.fontLabel)
        hbox.addWidget(self.fontChooser, 1)
        hbox.addWidget(self.fontSize)
        layout.addLayout(hbox)

        # add the items to our list
        self.baseColorsItem = i = QTreeWidgetItem()
        self.tree.addTopLevelItem(i)
        self.defaultStylesItem = i = QTreeWidgetItem()
        self.tree.addTopLevelItem(i)

        self.defaultStyles = {}
        for name in textformats.defaultStyles:
            self.defaultStyles[name] = i = QTreeWidgetItem()
            self.defaultStylesItem.addChild(i)
            i.name = name
        self.defaultStylesItem.setExpanded(True)

        self.allStyles = {}
        for group, styles in ly.colorize.default_mapping():
            i = QTreeWidgetItem()
            children = {}
            self.allStyles[group] = (i, children)
            self.tree.addTopLevelItem(i)
            i.group = group
            for name, base, clss in styles:
                j = QTreeWidgetItem()
                j.name = name
                j.base = base
                i.addChild(j)
                children[name] = j

        self.baseColorsWidget = BaseColors(self)
        self.customAttributesWidget = CustomAttributes(self)
        self.emptyWidget = QWidget(self)
        self.stack.addWidget(self.baseColorsWidget)
        self.stack.addWidget(self.customAttributesWidget)
        self.stack.addWidget(self.emptyWidget)

        self.tree.currentItemChanged.connect(self.currentItemChanged)
        self.tree.setCurrentItem(self.baseColorsItem)
        self.scheme.currentChanged.connect(self.currentSchemeChanged)
        self.scheme.changed.connect(self.changed)
        self.baseColorsWidget.changed.connect(self.baseColorsChanged)
        self.customAttributesWidget.changed.connect(
            self.customAttributesChanged)
        self.fontChooser.currentFontChanged.connect(self.fontChanged)
        self.fontSize.valueChanged.connect(self.fontChanged)
        self.printScheme.clicked.connect(self.printSchemeChanged)

        app.translateUI(self)

    def translateUI(self):
        self.printScheme.setText(_("Use this scheme for printing"))
        self.fontLabel.setText(_("Font:"))
        self.baseColorsItem.setText(0, _("Base Colors"))
        self.defaultStylesItem.setText(0, _("Default Styles"))

        self.defaultStyleNames = defaultStyleNames()
        self.allStyleNames = allStyleNames()

        for name in textformats.defaultStyles:
            self.defaultStyles[name].setText(0, self.defaultStyleNames[name])
        for group, styles in ly.colorize.default_mapping():
            self.allStyles[group][0].setText(0, self.allStyleNames[group][0])
            for name, base, clss in styles:
                self.allStyles[group][1][name].setText(
                    0, self.allStyleNames[group][1][name])

    def currentItemChanged(self, item, previous):
        if item is self.baseColorsItem:
            self.stack.setCurrentWidget(self.baseColorsWidget)
        elif not item.parent():
            self.stack.setCurrentWidget(self.emptyWidget)
        else:
            data = self.data[self.scheme.currentScheme()]
            w = self.customAttributesWidget
            self.stack.setCurrentWidget(w)
            toptext = None
            if item.parent() is self.defaultStylesItem:
                # default style
                w.setTitle(item.text(0))
                w.setTristate(False)
                w.setTextFormat(data.defaultStyles[item.name])
            else:
                # specific style of specific group
                group, name = item.parent().group, item.name
                w.setTitle("{0}: {1}".format(item.parent().text(0),
                                             item.text(0)))
                inherit = item.base
                if inherit:
                    toptext = _("(Inherits: {name})").format(
                        name=self.defaultStyleNames[inherit])
                w.setTristate(bool(inherit))
                w.setTextFormat(data.allStyles[group][name])
            w.setTopText(toptext)

    def currentSchemeChanged(self):
        scheme = self.scheme.currentScheme()
        if scheme not in self.data:
            self.data[scheme] = textformats.TextFormatData(scheme)
        self.updateDisplay()
        if self.tree.currentItem():
            self.currentItemChanged(self.tree.currentItem(), None)
        with qutil.signalsBlocked(self.printScheme):
            self.printScheme.setChecked(scheme == self._printScheme)

    def fontChanged(self):
        data = self.data[self.scheme.currentScheme()]
        data.font = self.fontChooser.currentFont()
        data.font.setPointSizeF(self.fontSize.value())
        self.updateDisplay()
        self.changed.emit()

    def printSchemeChanged(self):
        if self.printScheme.isChecked():
            self._printScheme = self.scheme.currentScheme()
        else:
            self._printScheme = None
        self.changed.emit()

    def addSchemeData(self, scheme, tfd):
        self.data[scheme] = tfd

    def currentSchemeData(self):
        return self.data[self.scheme.currentScheme()]

    def updateDisplay(self):
        data = self.data[self.scheme.currentScheme()]

        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(data.font)
            self.fontSize.setValue(data.font.pointSizeF())

        with qutil.signalsBlocked(self):
            # update base colors
            for name in textformats.baseColors:
                self.baseColorsWidget.color[name].setColor(
                    data.baseColors[name])

        # update base colors for whole treewidget
        p = QApplication.palette()
        p.setColor(QPalette.Base, data.baseColors['background'])
        p.setColor(QPalette.Text, data.baseColors['text'])
        p.setColor(QPalette.Highlight, data.baseColors['selectionbackground'])
        p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext'])
        self.tree.setPalette(p)

        def setItemTextFormat(item, f):
            font = QFont(data.font)
            if f.hasProperty(QTextFormat.ForegroundBrush):
                item.setForeground(0, f.foreground().color())
            else:
                item.setForeground(0, data.baseColors['text'])
            if f.hasProperty(QTextFormat.BackgroundBrush):
                item.setBackground(0, f.background().color())
            else:
                item.setBackground(0, QBrush())
            font.setWeight(f.fontWeight())
            font.setItalic(f.fontItalic())
            font.setUnderline(f.fontUnderline())
            item.setFont(0, font)

        # update looks of default styles
        for name in textformats.defaultStyles:
            setItemTextFormat(self.defaultStyles[name],
                              data.defaultStyles[name])

        # update looks of all the specific styles
        for group, styles in ly.colorize.default_mapping():
            children = self.allStyles[group][1]
            for name, inherit, clss in styles:
                f = QTextCharFormat(data.defaultStyles[inherit]
                                    ) if inherit else QTextCharFormat()
                f.merge(data.allStyles[group][name])
                setItemTextFormat(children[name], f)

    def baseColorsChanged(self, name):
        # keep data up to date with base colors
        data = self.data[self.scheme.currentScheme()]
        data.baseColors[name] = self.baseColorsWidget.color[name].color()
        self.updateDisplay()
        self.changed.emit()

    def customAttributesChanged(self):
        item = self.tree.currentItem()
        if not item or not item.parent():
            return
        data = self.data[self.scheme.currentScheme()]
        if item.parent() is self.defaultStylesItem:
            # a default style has been changed
            data.defaultStyles[
                item.name] = self.customAttributesWidget.textFormat()
        else:
            # a specific style has been changed
            group, name = item.parent().group, item.name
            data.allStyles[group][
                name] = self.customAttributesWidget.textFormat()
        self.updateDisplay()
        self.changed.emit()

    def import_(self, filename):
        from . import import_export
        import_export.importTheme(filename, self, self.scheme)

    def export(self, name, filename):
        from . import import_export
        try:
            import_export.exportTheme(self, name, filename)
        except (IOError, OSError) as e:
            QMessageBox.critical(
                self, _("Error"),
                _("Can't write to destination:\n\n{url}\n\n{error}").format(
                    url=filename, error=e.strerror))

    def loadSettings(self):
        self.data = {}  # holds all data with scheme as key
        self._printScheme = QSettings().value("printer_scheme", "default", str)
        self.scheme.loadSettings("editor_scheme", "editor_schemes")

    def saveSettings(self):
        self.scheme.saveSettings("editor_scheme", "editor_schemes",
                                 "fontscolors")
        for scheme in self.scheme.schemes():
            if scheme in self.data:
                self.data[scheme].save(scheme)
        if self._printScheme:
            QSettings().setValue("printer_scheme", self._printScheme)
        else:
            QSettings().remove("printer_scheme")
Exemplo n.º 28
0
class AugerToolbar(QWidget):
    sig_font_changed = pyqtSignal(str)
    sig_size_changed = pyqtSignal(int)
    sig_ao_toggle = pyqtSignal(bool)

    def __init__(self, parent, flags=Qt.WindowFlags(Qt.Widget)):
        super().__init__(parent, flags)

        font_size_tooltip = 'Font Size (in pt.)'
        ao_tooltip = 'Append / Overwrite (Default: Overwrite)'

        # Font Selector
        self._fontbox = QFontComboBox(self)
        self._fontbox.currentFontChanged.connect(self.slot_font_changed)

        # Font Size Label Hint
        self._label_size = QLabel(self)
        self._label_size_pixmap = QPixmap()
        self._label_size_pixmap.load(
            Resources().resource(Resource.ResourceToolIcon,
                                 which=ToolIcon.ToolIconFontSize), None)
        self._label_size.setFixedSize(25, 25)
        self._label_size.setPixmap(self._label_size_pixmap)
        self._label_size.setToolTip(font_size_tooltip)

        # Font Size Input
        self._fontsize = QLineEdit('8', self)
        self._fontsize.setMaxLength(3)
        self._fontsize.setInputMask('00D')
        self._fontsize.setFixedSize(36, self._fontbox.height())
        self._fontsize.setToolTip(font_size_tooltip)
        self._fontsize.textChanged.connect(self.slot_size_changed)

        # The Append / Overwrite Toggler
        self._appendtoggler = AugerAppendToggler(self)
        self._appendtoggler.setFixedSize(25, 25)
        self._appendtoggler.setToolTip(ao_tooltip)
        self._appendtoggler.clicked.connect(self.slot_append_toggle)

        # The Undo Button
        self._undobutton = QPushButton(self)
        self._undobutton.setFixedSize(25, 25)
        self._undobutton.setToolTip('Undo')
        self._undobutton.setAccessibleName('toolbutton')
        self._undobutton.setIcon(
            QIcon(Resources().resource(Resource.ResourceToolIcon,
                                       which=ToolIcon.ToolIconUndo)))
        self._undobutton.setFlat(True)
        self._undobutton.setEnabled(False)
        self._undobutton.clicked.connect(self.slot_undo_clicked)

        # The Redo Button
        self._redobutton = QPushButton(self)
        self._redobutton.setFixedSize(25, 25)
        self._redobutton.setToolTip('Redo')
        self._redobutton.setAccessibleName('toolbutton')
        self._redobutton.setIcon(
            QIcon(Resources().resource(Resource.ResourceToolIcon,
                                       which=ToolIcon.ToolIconRedo)))
        self._redobutton.setFlat(True)
        self._redobutton.setEnabled(False)
        self._redobutton.clicked.connect(self.slot_redo_clicked)

        # The Layout holding all toolbar contents
        self._layout = QHBoxLayout(self)
        self._layout.addWidget(self._fontbox)
        self._layout.addWidget(self._label_size)
        self._layout.addWidget(self._fontsize)
        self._layout.addWidget(self._appendtoggler)
        self._layout.addWidget(self._undobutton)
        self._layout.addWidget(self._redobutton)

        self.setLayout(self._layout)

        # connect slots to the command manager for undo / redo
        get_app_instance().cmd_mgr.sig_undo_stack_changed.connect(
            self.slot_undo_available)
        get_app_instance().cmd_mgr.sig_redo_stack_changed.connect(
            self.slot_redo_available)

    # Override method
    def paintEvent(self, paint_event):  # pylint: disable=invalid-name
        def border_coords():
            coords = paint_event.rect()
            return coords.x(), coords.y(), coords.width(), coords.height()

        #
        # # # # # # # # # # #
        # make coordinates for border
        draw_rect = tuple(
            map(lambda x, y: x + y, border_coords(), (1, 1, -2, -2)))

        # Prevent the painting of a border around children within the widget
        if not self.childrenRect().contains(paint_event.rect()):
            painter = QPainter(self)
            painter.setPen(QPen(QColor(130, 135, 144, 255)))
            painter.drawRect(*draw_rect)

        return super().paintEvent(paint_event)

    def set_font_properties(self, family, size):
        self._fontbox.setCurrentFont(QFont(family))
        self._fontsize.setText(str(size))

    ########### SLOTS ############## SLOTS ############# SLOTS ##############

    def slot_font_changed(self, font):
        self.sig_font_changed.emit(font.family())

    def slot_size_changed(self, str_size):
        try:
            font_size = int(str_size)
        except ValueError:
            font_size = 0

        if font_size > 0:
            self.sig_size_changed.emit(font_size)

    def slot_append_toggle(self, state):
        self.sig_ao_toggle.emit(state)

    def slot_undo_available(self, num_undos):
        if num_undos > 0:
            self._undobutton.setEnabled(True)
        else:
            self._undobutton.setEnabled(False)

    def slot_redo_available(self, num_redos):
        if num_redos > 0:
            self._redobutton.setEnabled(True)
        else:
            self._redobutton.setEnabled(False)

    def slot_undo_clicked(self):  # pylint: disable=no-self-use
        get_app_instance().cmd_mgr.undo_last_command()

    def slot_redo_clicked(self):  # pylint: disable=no-self-use
        get_app_instance().cmd_mgr.redo_last_command()