Exemplo n.º 1
0
def loadAppIcons():
    """loadAppIcons()
    Load the application iconsr.
    """
    # Get directory containing the icons
    appiconDir = os.path.join(pyzo.pyzoDir, "resources", "appicons")

    # Determine template for filename of the application icon-files.
    fnameT = "pyzologo{}.png"

    # Construct application icon. Include a range of resolutions. Note that
    # Qt somehow does not use the highest possible res on Linux/Gnome(?), even
    # the logo of qt-designer when alt-tabbing looks a bit ugly.
    pyzo.icon = QtGui.QIcon()
    for sze in [16, 32, 48, 64, 128, 256]:
        fname = os.path.join(appiconDir, fnameT.format(sze))
        if os.path.isfile(fname):
            pyzo.icon.addFile(fname, QtCore.QSize(sze, sze))

    # Set as application icon. This one is used as the default for all
    # windows of the application.
    QtWidgets.qApp.setWindowIcon(pyzo.icon)

    # Construct another icon to show when the current shell is busy
    artist = IconArtist(pyzo.icon)  # extracts the 16x16 version
    artist.setPenColor("#0B0")
    for x in range(11, 16):
        d = x - 11  # runs from 0 to 4
        artist.addLine(x, 6 + d, x, 15 - d)
    pm = artist.finish().pixmap(16, 16)
    #
    pyzo.iconRunning = QtGui.QIcon(pyzo.icon)
    pyzo.iconRunning.addPixmap(pm)  # Change only 16x16 icon
Exemplo n.º 2
0
    def _print(self):
        """Generate the pdf for preview and export"""

        if self.editor is not None:

            cursor = self.editor.textCursor()
            cursor.movePosition(cursor.Start)
            cursor.movePosition(cursor.End, cursor.KeepAnchor)

            cursor.insertText(pyzo.editors.getCurrentEditor().toPlainText())
            self._set_zoom(self.zoom_selected)

            # Print with line numbers
            lines = self.editor.toPlainText().splitlines()
            nzeros = len(str(len(lines)))

            self._apply_syntax_highlighting()
            starting_line = 0

            self._change_orientation()

            # Print name or filename in the editor
            if self.combobox_file_name.currentIndex():
                starting_line = 1
                if self.combobox_file_name.currentIndex() == 1:
                    lines.insert(0, "# " + self.editor_name + "\n")
                elif self.combobox_file_name.currentIndex() == 2:
                    lines.insert(0, "# " + self.editor_filename + "\n")

            # Print line numbers in the editor
            if self.show_line_number:
                for i in range(starting_line, len(lines)):
                    lines[i] = (str(i + 1 - starting_line).rjust(nzeros, "0") +
                                "| " + lines[i])

            cursor = self.editor.textCursor()
            cursor.movePosition(cursor.Start)
            cursor.movePosition(cursor.End, cursor.KeepAnchor)
            cursor.insertText("\n".join(lines))

            # Highlight line numbers
            if self.show_line_number:
                cursor.movePosition(cursor.Start, cursor.MoveAnchor)
                # Move the cursor down 2 lines if a title is printed
                if starting_line != 0:
                    cursor.movePosition(cursor.NextBlock, cursor.MoveAnchor, 2)
                # Apply background for lines numbers
                for i in range(len(lines)):
                    fmt = QtGui.QTextCharFormat()
                    fmt.setBackground(QtGui.QColor(240, 240, 240))
                    cursor.movePosition(cursor.Right, cursor.KeepAnchor,
                                        nzeros)
                    cursor.setCharFormat(fmt)
                    cursor.movePosition(cursor.NextBlock, cursor.MoveAnchor)
                    cursor.movePosition(cursor.StartOfBlock, cursor.MoveAnchor)
Exemplo n.º 3
0
 def setPenColor(self, color):
     """setPenColor(color)
     Set the color of the pen. Color can be anything that can be passed to
     Qcolor().
     """
     pen = QtGui.QPen()
     if isinstance(color, tuple):
         pen.setColor(QtGui.QColor(*color))
     else:
         pen.setColor(QtGui.QColor(color))
     self._painter.setPen(pen)
Exemplo n.º 4
0
def loadIcons():
    """loadIcons()
    Load all icons in the icon dir.
    """
    # Get directory containing the icons
    iconDir = os.path.join(pyzo.pyzoDir, "resources", "icons")

    # Construct other icons
    dummyIcon = IconArtist().finish()
    pyzo.icons = ssdf.new()
    for fname in os.listdir(iconDir):
        if fname.endswith(".png"):
            try:
                # Short and full name
                name = fname.split(".")[0]
                name = name.replace("pyzo_", "")  # discart prefix
                ffname = os.path.join(iconDir, fname)
                # Create icon
                icon = QtGui.QIcon()
                icon.addFile(ffname, QtCore.QSize(16, 16))
                # Store
                pyzo.icons[name] = icon
            except Exception as err:
                pyzo.icons[name] = dummyIcon
                print("Could not load icon %s: %s" % (fname, str(err)))
Exemplo n.º 5
0
    def __init__(self, parent, i):
        QtWidgets.QWizardPage.__init__(self, parent)
        self._i = i

        # Create label for description
        self._text_label = QtWidgets.QLabel(self)
        self._text_label.setTextFormat(QtCore.Qt.RichText)
        self._text_label.setWordWrap(True)

        # Create label for image
        self._comicLabel = QtWidgets.QLabel(self)
        pm = QtGui.QPixmap()
        if "logo" in self._image_filename:
            pm.load(
                os.path.join(
                    pyzo.pyzoDir, "resources", "appicons", self._image_filename
                )
            )
        elif self._image_filename:
            pm.load(
                os.path.join(pyzo.pyzoDir, "resources", "images", self._image_filename)
            )
        self._comicLabel.setPixmap(pm)
        self._comicLabel.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

        # Layout
        theLayout = QtWidgets.QVBoxLayout(self)
        self.setLayout(theLayout)
        #
        theLayout.addWidget(self._text_label)
        theLayout.addStretch()
        theLayout.addWidget(self._comicLabel)
        theLayout.addStretch()
Exemplo n.º 6
0
    def __init__(self, parent):
        QtWidgets.QWizard.__init__(self, parent)

        # Set some appearance stuff
        self.setMinimumSize(600, 500)
        self.setWindowTitle(translate("wizard", "Getting started with Pyzo"))
        self.setWizardStyle(self.ModernStyle)
        self.setButtonText(self.CancelButton, "Stop")

        # Set logo
        pm = QtGui.QPixmap()
        pm.load(os.path.join(pyzo.pyzoDir, "resources", "appicons", "pyzologo48.png"))
        self.setPixmap(self.LogoPixmap, pm)

        # Define pages
        klasses = [
            IntroWizardPage,
            TwocomponentsWizardPage,
            EditorWizardPage,
            ShellWizardPage1,
            ShellWizardPage2,
            RuncodeWizardPage1,
            RuncodeWizardPage2,
            ToolsWizardPage1,
            ToolsWizardPage2,
            FinalPage,
        ]

        # Create pages
        self._n = len(klasses)
        for i, klass in enumerate(klasses):
            self.addPage(klass(self, i))
Exemplo n.º 7
0
 def getCrossIcon2(self):
     if hasattr(self, "_cross2"):
         pm = self._cross2
     else:
         pm = self._createCrossPixmap(240)
     # Set
     return QtGui.QIcon(pm)
Exemplo n.º 8
0
    def __init__(self, icon=None):

        # Get pixmap from given icon (None creates empty pixmap)
        self._pm = self._getPixmap(icon)

        # Instantiate painter for the pixmap
        self._painter = QtGui.QPainter()
        self._painter.begin(self._pm)
Exemplo n.º 9
0
 def SetItems(parentItem, fictiveObjects, level):
     level += 1
     for object in fictiveObjects:
         type = object.type
         if type not in showTypes and type != "nameismain":
             continue
         # Construct text
         if type == "import":
             text = "→ %s (%s)" % (object.name, object.text)
         elif type == "todo":
             text = object.name
         elif type == "nameismain":
             text = object.text
         elif type == "class":
             text = object.name
         elif type == "def":
             text = object.name + "()"
         elif type == "attribute":
             text = "- " + object.name
         elif type in ("cell", "##", "#%%", "# %%"):
             type = "cell"
             text = "## " + object.name + " " * 120
         else:
             text = "%s %s" % (type, object.name)
         # Create item
         thisItem = QtWidgets.QTreeWidgetItem(parentItem, [text])
         color = QtGui.QColor(colours[object.type])
         thisItem.setForeground(0, QtGui.QBrush(color))
         font = thisItem.font(0)
         font.setBold(True)
         if type == "cell":
             font.setUnderline(True)
         thisItem.setFont(0, font)
         thisItem.linenr = object.linenr
         # Is this the current item?
         if ln and object.linenr <= ln and object.linenr2 > ln:
             selectedItem[0] = thisItem
         # Any children that we should display?
         if object.children:
             SetItems(thisItem, object.children, level)
         # Set visibility
         thisItem.setExpanded(bool(level < showLevel))
Exemplo n.º 10
0
 def openColorDialog(self):
     """A simple function that opens a QColorDialog
     and link the dialog current color selection
     to the QLineEdit text
     """
     dlg = QtWidgets.QColorDialog(self)
     dlg.setWindowTitle("Pick a color for the " + self.name.lower())
     dlg.setCurrentColor(QtGui.QColor(self.text()))
     dlg.currentColorChanged.connect(lambda clr: self.setText(clr.name()))
     dlg.setModal(False)
     dlg.exec_()
Exemplo n.º 11
0
    def _getPixmap(self, icon):

        # Get icon if given by name
        if isinstance(icon, str):
            icon = pyzo.icons[icon]

        # Create pixmap
        if icon is None:
            pm = QtGui.QPixmap(16, 16)
            pm.fill(QtGui.QColor(0, 0, 0, 0))
            return pm
        elif isinstance(icon, tuple):
            pm = QtGui.QPixmap(icon[0], icon[1])
            pm.fill(QtGui.QColor(0, 0, 0, 0))
            return pm
        elif isinstance(icon, QtGui.QPixmap):
            return icon
        elif isinstance(icon, QtGui.QIcon):
            return icon.pixmap(16, 16)
        else:
            raise ValueError("Icon for IconArtis should be icon, pixmap or name.")
Exemplo n.º 12
0
 def _change_orientation(self):
     """Set document in portrait or landscape orientation"""
     index = self.combobox_orientation.currentIndex()
     if hasattr(self.printer, "setPageLayout"):  # qt6
         base = QtGui.QPageLayout
         orientation = [base.Portrait, base.Landscape][index]
         layout = QtGui.QPageLayout()
         layout.setOrientation(orientation)
         self.printer.setPageLayout(layout)
     else:  # qt5
         base = QtPrintSupport.QPrinter
         orientation = [base.Portrait, base.Landscape][index]
         self.printer.setOrientation(orientation)
Exemplo n.º 13
0
    def __init__(self, name, *args, **kwargs):
        """The name is displayed in the QColorDialog"""
        super().__init__(*args, **kwargs)
        self.name = name
        self.button = QtWidgets.QToolButton(self)
        self.button.setIcon(QtGui.QIcon(pyzo.icons.cog))
        self.button.setStyleSheet("border: 0px; padding: 0px")
        self.button.clicked.connect(self.openColorDialog)

        frameWidth = self.style().pixelMetric(
            QtWidgets.QStyle.PM_DefaultFrameWidth)
        buttonSize = self.button.sizeHint()

        self.setStyleSheet("QLineEdit {padding-right: %dpx; }" %
                           (buttonSize.width() + frameWidth + 1))
Exemplo n.º 14
0
    def __init__(self, parent):
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle(pyzo.translate("menu dialog", "About Pyzo"))
        self.resize(600, 500)

        # Layout
        layout = QtWidgets.QVBoxLayout(self)
        self.setLayout(layout)

        # Create image and title
        im = QtGui.QPixmap(
            os.path.join(pyzo.pyzoDir, "resources", "appicons",
                         "pyzologo64.png"))
        imlabel = QtWidgets.QLabel(self)
        imlabel.setPixmap(im)
        textlabel = QtWidgets.QLabel(self)
        textlabel.setText("<h3>Pyzo: the Interactive Editor for Python</h3>")
        #
        titleLayout = QtWidgets.QHBoxLayout()
        titleLayout.addWidget(imlabel, 0)
        titleLayout.addWidget(textlabel, 1)
        #
        layout.addLayout(titleLayout, 0)

        # Create tab bar
        self._tabs = QtWidgets.QTabWidget(self)
        self._tabs.setDocumentMode(True)
        layout.addWidget(self._tabs, 1)

        # Create button box
        self._butBox = QtWidgets.QDialogButtonBox(self)
        self._butBox.setOrientation(QtCore.Qt.Horizontal)
        self._butBox.setStandardButtons(self._butBox.Close)
        layout.addWidget(self._butBox, 0)

        # Signals
        self._butBox.rejected.connect(self.close)

        # Create tabs
        self.createGeneralTab()
Exemplo n.º 15
0
            # Otherwise we finish it ourselves
            aco.finish()


if __name__ == "__main__":
    # Do some stubbing to run this module as a unit separate from pyzo
    # TODO: untangle pyzo from this module where possible
    class DummyParser:
        def parseThis(self, x):
            pass

    pyzo.parser = DummyParser()
    EditorContextMenu = QtWidgets.QMenu  # noqa
    app = QtWidgets.QApplication([])
    win = PyzoEditor(None)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+C"),
                        win).activated.connect(win.copy)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+X"),
                        win).activated.connect(win.cut)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+V"),
                        win).activated.connect(win.paste)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+Shift+V"),
                        win).activated.connect(win.pasteAndSelect)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+Z"),
                        win).activated.connect(win.undo)
    QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+Y"),
                        win).activated.connect(win.redo)

    tmp = "foo(bar)\nfor bar in range(5):\n  print bar\n"
    tmp += "\nclass aap:\n  def monkey(self):\n    pass\n\n"
    win.setPlainText(tmp)
Exemplo n.º 16
0
    def updateStructure(self):
        """Updates the tree."""

        # Get editor
        editor = pyzo.editors.getCurrentEditor()
        if not editor:
            return

        # Something to show
        result = pyzo.parser._getResult()
        if result is None:
            return

        # Do the ids match?
        id0, id1, id2 = self._currentEditorId, id(editor), result.editorId
        if id0 != id1 or id0 != id2:
            return

        # Get current line number and the structure
        ln = editor.textCursor().blockNumber()
        ln += 1  # is ln as in line number area

        # Define colours
        colours = {
            "cell": "#b58900",
            "class": "#cb4b16",
            "def": "#073642",
            "attribute": "#657b83",
            "import": "#268bd2",
            "todo": "#d33682",
            "nameismain": "#859900",
        }
        # colours = {'cell':'#007F00', 'class':'#0000FF', 'def':'#007F7F',
        #            'attribute':'#444444', 'import':'#8800BB', 'todo':'#FF3333',
        #            'nameismain':'#007F00'}

        # Define what to show
        showTypes = self._config.showTypes

        # Define to what level to show (now is also a good time to save)
        showLevel = int(self._slider.value())
        self._config.level = showLevel
        showLevel = showLevel if showLevel < 5 else 99

        # Define function to set items
        selectedItem = [None]

        def SetItems(parentItem, fictiveObjects, level):
            level += 1
            for object in fictiveObjects:
                type = object.type
                if type not in showTypes and type != "nameismain":
                    continue
                # Construct text
                if type == "import":
                    text = "→ %s (%s)" % (object.name, object.text)
                elif type == "todo":
                    text = object.name
                elif type == "nameismain":
                    text = object.text
                elif type == "class":
                    text = object.name
                elif type == "def":
                    text = object.name + "()"
                elif type == "attribute":
                    text = "- " + object.name
                elif type in ("cell", "##", "#%%", "# %%"):
                    type = "cell"
                    text = "## " + object.name + " " * 120
                else:
                    text = "%s %s" % (type, object.name)
                # Create item
                thisItem = QtWidgets.QTreeWidgetItem(parentItem, [text])
                color = QtGui.QColor(colours[object.type])
                thisItem.setForeground(0, QtGui.QBrush(color))
                font = thisItem.font(0)
                font.setBold(True)
                if type == "cell":
                    font.setUnderline(True)
                thisItem.setFont(0, font)
                thisItem.linenr = object.linenr
                # Is this the current item?
                if ln and object.linenr <= ln and object.linenr2 > ln:
                    selectedItem[0] = thisItem
                # Any children that we should display?
                if object.children:
                    SetItems(thisItem, object.children, level)
                # Set visibility
                thisItem.setExpanded(bool(level < showLevel))

        # Go
        self._tree.setUpdatesEnabled(False)
        self._tree.clear()
        SetItems(self._tree, result.rootItem.children, 0)
        self._tree.setUpdatesEnabled(True)

        # Handle selected item
        selectedItem = selectedItem[0]
        if selectedItem:
            selectedItem.setBackground(0, QtGui.QBrush(QtGui.QColor("#CCC")))
            self._tree.scrollToItem(selectedItem)  # ensure visible
Exemplo n.º 17
0
 def finish(self, icon=None):
     """finish()
     Finish the drawing and return the resulting icon.
     """
     self._painter.end()
     return QtGui.QIcon(self._pm)
Exemplo n.º 18
0
 def getCrossIcon1(self):
     if hasattr(self, "_cross1"):
         pm = self._cross1
     else:
         pm = self._createCrossPixmap(80)
     return QtGui.QIcon(pm)