Esempio n. 1
0
    def make_image(path, src, fail_ok=False):
        """relative to path (if needed), make a QGraphicsPixmapItem
        for the image named in src, returning None if not available,
        or an 'No Image' image if fail_ok == False"""

        if '//' not in src or src.startswith('file://'):
            testpath = src
            if '//' in testpath:
                testpath = testpath.split('//', 1)[-1]
            #
            # file on local file system
            testpath = g.os_path_finalize_join(path, testpath)
            if g.os_path_exists(testpath):
                return QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(testpath))
            #
            # explicit file://, but no such file exists
            if src.startswith('file://'):
                return None if fail_ok else GetImage._no_image()
        #
        # no explict file://, so try other protocols
        testpath = src if '//' in src else 'http://%s' % (src)
        data = GetImage.get_url(testpath)
        if data:
            img = QtGui.QPixmap()
            if img.loadFromData(data):
                return QtWidgets.QGraphicsPixmapItem(img)
        return None if fail_ok else GetImage._no_image()
Esempio n. 2
0
 def image(self, pane, fn, center=None, height=None, width=None):
     '''Put an image in the indicated pane.'''
     m = self
     parent = m.pane_widget(pane)
     if parent:
         w = QtGui.QLabel('label', parent)
         fn = m.resolve_icon_fn(fn)
         if not fn: return None
         pixmap = QtGui.QPixmap(fn)
         if not pixmap:
             return g.trace('Not a pixmap: %s' % (fn))
         if height:
             pixmap = pixmap.scaledToHeight(height)
         if width:
             pixmap = pixmap.scaledToWidth(width)
         w.setPixmap(pixmap)
         if center:
             g_w = w.geometry()
             g_p = parent.geometry()
             dx = (g_p.width() - g_w.width()) / 2
             w.move(g_w.x() + dx, g_w.y() + 10)
         w.show()
         m.widgets.append(w)
         return w
     else:
         g.trace('bad pane: %s' % (pane))
         return None
Esempio n. 3
0
def main():
    # stupid test
    a = QtGui.QApplication([])
    b = QtGui.QPushButton("Say hello", None)
    g.procs.add(['ls', '/tmp'])
    g.procs.add(['ls', '-la'])
    #a.setMainWidget(b)
    b.show()
    a.exec_()
Esempio n. 4
0
 def showMessage(self, msg, color='black'):
     '''Show the message in the label area.'''
     try:
         fg = QtGui.QColor(color)
     except Exception:
         fg = QtGui.QColor('black')
     pal = QtGui.QPalette(self.UI.label.palette())
     pal.setColor(QtGui.QPalette.WindowText, fg)
     self.UI.label.setPalette(pal)
     self.UI.label.setText(msg)
Esempio n. 5
0
 def showMessage(self, msg, color):
     """Show the message in the label area."""
     ui = self.UI
     fg = QtGui.QColor(color)
     pal = QtGui.QPalette(ui.label.palette())
     if isQt6:
         pal.setColor(pal.ColorRole.Window, fg)  # #2197
     else:
         pal.setColor(QtGui.QPalette.WindowText, fg)
     ui.label.setPalette(pal)
     ui.label.setText(msg)
    def create_frame(self, filename, filenames, window):

        QLabel = QtWidgets.QLabel
        # Create the frame.
        frame = QtWidgets.QFrame(parent=window)
        # Create the vertical layout.
        layout = QtWidgets.QVBoxLayout()
        frame.setLayout(layout)
        # Set the font.
        font = QtGui.QFont()
        font.setBold(True)
        font.setPointSize(12)
        # Create the labels..
        ctime = time.ctime(os.path.getctime(filename))
        struct_time = time.strptime(ctime)
        creation_time = time.strftime('%Y %m %d', struct_time)
        file_label = QLabel(text=filename, parent=frame)
        file_label.setFont(font)
        layout.addWidget(file_label)
        size = os.path.getsize(filename) / 1000
        info_label = QLabel(text=f"size: {size} KB date: {creation_time}")
        info_label.setFont(font)
        layout.addWidget(info_label)
        # Create the delete button, centered.
        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addStretch()
        delete_button = QtWidgets.QPushButton(text='Delete', parent=frame)
        button_layout.addWidget(delete_button)
        button_layout.addStretch()
        layout.addLayout(button_layout)

        # Set the button action.

        def delete_action(arg):
            self.delete_file(filename)

        delete_button.clicked.connect(delete_action)
        # Create the picture area.
        picture = QtWidgets.QLabel('picture', parent=frame)
        layout.addWidget(picture)
        # Display the picture.
        pixmap = QtGui.QPixmap(filename)
        try:
            TransformationMode = QtCore.Qt if isQt5 else QtCore.Qt.TransformationMode
            image = pixmap.scaledToHeight(
                self.window_height, TransformationMode.SmoothTransformation)  # pylint: disable=no-member
            picture.setPixmap(image)
            picture.adjustSize()
            return frame
        except Exception:
            g.trace('Bad image')
            g.es_exception()
            return None
Esempio n. 7
0
    def exportGraph(self):

        image = QtGui.QImage(2048,1536,QtGui.QImage.Format_ARGB32_Premultiplied)
        painter = QtGui.QPainter(image)
        self.ui.canvas.render(painter)
        painter.end()
        filepath, extension = QtWidgets.QFileDialog.getSaveFileName(
            caption="Export to File",
            filter="*.png",
        )
        if filepath:
            image.save(filepath)
Esempio n. 8
0
    def clearFormatting(self):

        node = self.node[self.lastNodeItem]
        item = self.nodeItem[node]
        # FIXME: need node.clear_formatting()
        if hasattr(item, 'bg'):
            item.bg.setBrush(QtGui.QBrush(QtGui.QColor(200, 240, 200)))
        if hasattr(item, 'text'):
            item.text.setDefaultTextColor(QtGui.QColor(0, 0, 0))
        if 'color' in node.u['_bklnk']:
            del node.u['_bklnk']['color']
        if 'tcolor' in node.u['_bklnk']:
            del node.u['_bklnk']['tcolor']
        self.releaseNode(self.nodeItem[node])
Esempio n. 9
0
    def __init__(self, c):

        self.c = c
        self.c.graphcanvasController = self
        self.selectPen = QtGui.QPen(QtGui.QColor(255, 0, 0))
        self.selectPen.setWidth(2)
        self.ui = graphcanvasUI(self)
        g.registerHandler('headkey2', lambda a, b: self.do_update())
        g.registerHandler("select2", self.onSelect2)
        # g.registerHandler('open2', self.loadLinks)
        # already missed initial 'open2' because of after-create-leo-frame, so
        # self.loadLinksInt()
        self.initIvars()
        self.reloadSettings()
Esempio n. 10
0
def colorize_headlines_visitor(c, p, item):
    '''Item is a QTreeWidgetItem.'''
    if '_bklnk' in p.v.u:
        # f = item.font(0)
        # f.setItalic(True)
        # f.setBold(True)
        # item.setFont(0,f)
        # item.setForeground(0, QtGui.QColor(100, 0, 0))
        if 'color' in p.v.u['_bklnk']:
            item.setBackground(0, QtGui.QColor(p.v.u['_bklnk']['color']))
        if 'tcolor' in p.v.u['_bklnk']:
            item.setForeground(0, QtGui.QColor(p.v.u['_bklnk']['tcolor']))
            f = item.font(0)
            f.setBold(True)
    raise leoPlugins.TryNext
Esempio n. 11
0
 def mkitem(self, d):
     """ dict with field->value """
     si = QtGui.QStandardItem()
     for k, v in d.items():
         rid = self.roleids[k]
         si.setData(v, rid)
     return si
Esempio n. 12
0
 def __init__(self, c):
     '''Ctor for WikiView class.'''
     self.c = c
     c._wikiview = self
     leadins, self.urlpats = self.parse_options()
     assert len(leadins) == len(self.urlpats), (leadins, self.urlpats)
     self.colorizer = c.frame.body.colorizer
     if hasattr(self.colorizer, 'set_wikiview_patterns'):
         self.colorizer.set_wikiview_patterns(leadins, self.urlpats)
     self.select = 'select3'  # Leo hook to hide text
     self.pts=1  # hidden text size (0.1 does not work!)
     self.pct=1  # hidden text letter spacing
     self.active = c.config.getBool('wikiview-active')
         # This setting is True by default, so the redundancy is harmless.
     w = c.frame.body.widget
     if not w:
         return # w may not exist during unit testing.
     g.registerHandler(self.select,self.hide)
     w.cursorPositionChanged.connect(self.unhide)
     # size to restore text to when unhiding,
     # w.currentFont().pointSize() is -1 which doesn't work, hence QFontInfo
     self.size = QtGui.QFontInfo(w.currentFont()).pointSize()
     # apply hiding for initial load (`after-create-leo-frame` from module level
     # init() / onCreate())
     self.hide(self.select, {'c': c})
Esempio n. 13
0
def showFonts(self, event=None):
    """Open a tab in the log pane showing a font picker."""
    c = self.c
    p = c.p

    picker = QtWidgets.QFontDialog()
    if p.h.startswith('@font'):
        (name, family, weight, slant, size) = leoConfig.parseFont(p.b)
    else:
        name, family, weight, slant, size = None, None, False, False, 12
    try:
        font = QtGui.QFont()
        if family: font.setFamily(family)
        font.setBold(weight)
        font.setItalic(slant)
        font.setPointSize(size)
        picker.setCurrentFont(font)
    except ValueError:
        pass
    if not picker.exec_():
        g.es("No font selected")
    else:
        font = picker.selectedFont()
        udata = c.undoer.beforeChangeNodeContents(p)
        comments = [x for x in g.splitLines(p.b) if x.strip().startswith('#')]
        defs = [
            '\n' if comments else '',
            '%s_family = %s\n' % (name, font.family()),
            '%s_weight = %s\n' % (name, 'bold' if font.bold() else 'normal'),
            '%s_slant = %s\n' % (name, 'italic' if font.italic() else 'roman'),
            '%s_size = %s\n' % (name, font.pointSizeF())
        ]
        p.b = ''.join(comments + defs)
        c.undoer.afterChangeNodeContents(p, 'change-font', udata)
Esempio n. 14
0
    def complete(self,event):

        c = self.c
        cpl = self.completer
        p = c.p
        w = self.w # A leoQTextEditWidget

        head, tail = self.get_current_line(w)
        m = self.get_attr_target_python(head)
        if m:
            obj = m.group(1)
            prefix = m.group(3)
            klasses = self.guess_class(c,p, obj)
        else:
            klasses = []

        if klasses:
            hits = self.lookup_methods(klasses, prefix)
        else:
            s = self.get_word()
            hits = self.lookup(s)

        model = QtGui.QStringListModel(hits)
        cpl.setModel(model)
        cpl.setCompletionPrefix(prefix)
        cpl.complete()
Esempio n. 15
0
 def init_image(self, fn, magnification, position, size):
     '''Init the image whose file name fn is given.'''
     demo, widget = g.app.demo, self
     fn = demo.get_icon_fn(fn)
     if not fn:
         g.trace('can not resolve', fn)
         return
     pixmap = QtGui.QPixmap(fn)
     if not pixmap:
         g.trace('Not a pixmap:', fn)
         return
     if magnification:
         if size:
             h, w = size
         else:
             r = pixmap.size()
             h, w = r.height(), r.width()
         size = h*magnification, w*magnification
     if size:
         try:
             h, w = size
             h = demo.get_int(h)
             w = demo.get_int(w)
             if h is not None:
                 pixmap = pixmap.scaledToHeight(h)
             if w is not None:
                 pixmap = pixmap.scaledToWidth(w)
         except ValueError:
             g.trace('invalid size', repr(size))
     if position:
         demo.set_position(widget, position)
     widget.setPixmap(pixmap)
Esempio n. 16
0
def showColorWheel(self, event=None):
    '''Show a Qt color dialog.'''
    c = self.c; p = c.p
    picker = QtWidgets.QColorDialog()
    in_color_setting = p.h.startswith('@color ')
    try:
        text = QtWidgets.QApplication.clipboard().text()
        if in_color_setting:
            text = p.h.split('=', 1)[1].strip()
        color = QtGui.QColor(text)
        picker.setCurrentColor(color)
    except (ValueError, IndexError) as e:
        g.trace('error caught', e)
    if not picker.exec_():
        g.es("No color selected")
    elif in_color_setting:
        udata = c.undoer.beforeChangeNodeContents(p)
        p.h = '%s = %s' % (
            p.h.split('=', 1)[0].strip(),
            picker.selectedColor().name(),
        )
        c.undoer.afterChangeNodeContents(p, 'change-color', udata)
    else:
        text = picker.selectedColor().name()
        g.es("copied to clipboard:", text)
        QtWidgets.QApplication.clipboard().setText(text)
    def qtKey(self, event):
        '''
        Return the components of a Qt key event.

        Modifiers are handled separately.

        Return (keynum, text, toString, ch).

        keynum: event.key()
        ch:     g.u(chr(keynum)) or '' if there is an exception.
        toString:
            For special keys: made-up spelling that become part of the setting.
            For all others:   QtGui.QKeySequence(keynum).toString()
        text:   event.text()
        '''
        keynum = event.key()
        text = event.text()  # This is the unicode character!
        qt = QtCore.Qt
        d = {
            qt.Key_Alt:
            'Key_Alt',
            qt.Key_AltGr:
            'Key_AltGr',
            # On Windows, when the KeyDown event for this key is sent,
            # the Ctrl+Alt modifiers are also set.
            qt.Key_Control:
            'Key_Control',  # MacOS: Command key
            qt.Key_Meta:
            'Key_Meta',
            # MacOS: Control key, Alt-Key on Microsoft keyboard on MacOs.
            qt.Key_Shift:
            'Key_Shift',
            qt.Key_NumLock:
            'Num_Lock',
            # 868.
        }
        if d.get(keynum):
            if 0:  # Allow bare modifier key.
                toString = d.get(keynum)
            else:
                toString = ''
        else:
            toString = QtGui.QKeySequence(keynum).toString()
        # Fix bug 1244461: Numpad 'Enter' key does not work in minibuffer
        if toString == 'Enter':
            toString = 'Return'
        if toString == 'Esc':
            toString = 'Escape'
        try:
            ch1 = chr(keynum)
        except ValueError:
            ch1 = ''
        try:
            ch = g.u(ch1)
        except UnicodeError:
            ch = ch1
        text = g.u(text)
        toString = g.u(toString)
        return keynum, text, toString, ch
Esempio n. 18
0
    def clearFormatting(self):

        if self.lastNodeItem not in self.node:
            return
        node = self.node[self.lastNodeItem]
        item = self.nodeItem[node]
        # FIXME: need node.clear_formatting()
        if hasattr(item, 'bg') and hasattr(item.bg, 'setBrush'):
            item.bg.setBrush(QtGui.QBrush(QtGui.QColor(200, 240, 200)))
        if hasattr(item, 'text'):
            item.text.setDefaultTextColor(QtGui.QColor(0, 0, 0))
        if 'color' in node.u['_bklnk']:
            del node.u['_bklnk']['color']
        if 'tcolor' in node.u['_bklnk']:
            del node.u['_bklnk']['tcolor']
        self.releaseNode(self.nodeItem[node])
        self.c.redraw()  # update color of node in the tree too
Esempio n. 19
0
    def __init__(self, glue, hierarchyLink=False, *args, **kargs):
        """:Parameters:
            - `glue`: glue object owning this

        pass glue object and let it key nodeItems to leo nodes
        """
        self.glue = glue
        QtWidgets.QGraphicsItemGroup.__init__(self)
        self.line = QtWidgets.QGraphicsLineItem(*args)

        pen = QtGui.QPen()

        self.line.setZValue(0)
        if not hierarchyLink:
            self.setZValue(1)
            pen.setWidth(2)
        else:
            self.setZValue(0)
            pen.setColor(QtGui.QColor(240, 240, 240))
            pen.setWidth(2)  # (0.5)

        self.line.setPen(pen)
        self.addToGroup(self.line)

        self.head = QtWidgets.QGraphicsPolygonItem()

        if hierarchyLink:
            self.head.setBrush(QtGui.QBrush(QtGui.QColor(180, 180, 180)))
        else:
            self.head.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))

        self.head.setPen(QtGui.QPen(QtConst.NoPen))
        self.addToGroup(self.head)
Esempio n. 20
0
    def __init__(self, glue, hierarchyLink=False, *args, **kargs):
        """:Parameters:
            - `glue`: glue object owning this

        pass glue object and let it key nodeItems to leo nodes
        """
        # pylint: disable=keyword-arg-before-vararg
        # putting *args first is invalid in Python 2.x.
        self.glue = glue
        super().__init__()
        self.line = QtWidgets.QGraphicsLineItem(*args)

        pen = QtGui.QPen()

        self.line.setZValue(0)
        if not hierarchyLink:
            self.setZValue(1)
            pen.setWidth(2)
        else:
            self.setZValue(0)
            pen.setColor(QtGui.QColor(240, 240, 240))
            pen.setWidth(2)  # (0.5)

        self.line.setPen(pen)
        self.addToGroup(self.line)

        self.head = QtWidgets.QGraphicsPolygonItem()

        if hierarchyLink:
            self.head.setBrush(QtGui.QBrush(QtGui.QColor(180, 180, 180)))
        else:
            self.head.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))

        self.head.setPen(QtGui.QPen(QtConst.NoPen))
        self.addToGroup(self.head)
Esempio n. 21
0
    def __init__(self, c):

        self.c = c

        self.graph_manual_layout = c.config.getBool('graph-manual-layout',
                                                    default=False)

        self.c.graphcanvasController = self

        self.selectPen = QtGui.QPen(QtGui.QColor(255, 0, 0))
        self.selectPen.setWidth(2)

        self.ui = graphcanvasUI(self)

        g.registerHandler('headkey2', lambda a, b: self.do_update())
        g.registerHandler("select2", self.onSelect2)

        self.initIvars()
Esempio n. 22
0
 def do_update(self):
     poly = QtGui.QPolygonF()
     marginX = self.text.document().size().width() / 2
     marginY = self.text.document().size().height() / 2
     poly.append(QtCore.QPointF(-marginX, marginY))
     poly.append(QtCore.QPointF(marginX, 3 * marginY))
     poly.append(QtCore.QPointF(3 * marginX, marginY))
     poly.append(QtCore.QPointF(marginX, -marginY))
     self.bg.setPolygon(poly)
Esempio n. 23
0
 def __init__(self, fieldlist):
     self.rolenames = rn = {}
     self.roleids = ri = {}
     for n, f in enumerate(fieldlist):
         rid = n + 100
         rn[rid] = f
         ri[f] = rid
     self.model = mo = QtGui.QStandardItemModel()
     mo.setRoleNames(rn)
Esempio n. 24
0
 def bg_item(self):
     """return a canvas item for the shape in the background"""
     bg = QtWidgets.QGraphicsPolygonItem()
     poly = QtGui.QPolygonF()
     poly.append(QtCore.QPointF(-5, 5))
     poly.append(QtCore.QPointF(15, -5))
     poly.append(QtCore.QPointF(35, 5))
     poly.append(QtCore.QPointF(15, 15))
     bg.setPolygon(poly)
     return bg
Esempio n. 25
0
    def __init__(self, c=None, lep=None, *args, **kwargs):
        """set up"""
        super(LEP_VanillaScintilla, self).__init__(*args, **kwargs)
        self.c = c
        self.lep = lep
        self.textChanged.connect(self.text_changed)

        font = QtGui.QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(14)

        lexer = Qsci.QsciLexerPython()
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
        # self.SendScintilla(Qsci.QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')

        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QtGui.QColor("#ffe4e4"))
Esempio n. 26
0
 def __init__(self, c):
     self.c = c
     #@+at
     #     c.k.registerCommand('upload',shortcut=None,func=self.upload)
     #     script = "c.k.simulateCommand('upload')"
     #     g.app.gui.makeScriptButton(c,script=script,buttonText='Upload')
     #@@c
     ib_w = self.c.frame.iconBar.w
     action = QtGui.QAction('Upload', ib_w)
     self.c.frame.iconBar.add(qaction=action, command=self.upload)
Esempio n. 27
0
 def complex_document(self, nodes, heads=False):
     """Create a complex document."""
     doc = QtGui.QTextDocument()
     doc.setDefaultStyleSheet(self.stylesheet)
     contents = ''
     for n in nodes:
         if heads:
             contents += '<h1>%s</h1>\n' % (self.sanitize_html(n.h))
         contents += '<pre>%s</pre>\n' % (self.sanitize_html(n.b))
     doc.setHtml(contents)
     return doc
Esempio n. 28
0
 def setBackgroundColor(self, colorName, name, w):
     '''Set the background color of the vr pane.'''
     pc = self
     if not colorName: return
     styleSheet = 'QTextEdit#%s { background-color: %s; }' % (name, colorName)
     # g.trace(name,colorName)
     if QtGui.QColor(colorName).isValid():
         w.setStyleSheet(styleSheet)
     elif colorName not in pc.badColors:
         pc.badColors.append(colorName)
         g.warning('invalid body background color: %s' % (colorName))
Esempio n. 29
0
 def document(self, text, head=None):
     """Create a Qt document."""
     doc = QtGui.QTextDocument()
     doc.setDefaultStyleSheet(self.stylesheet)
     text = self.sanitize_html(text)
     if head:
         head = self.sanitize_html(head)
         contents = "<h1>%s</h1>\n<pre>%s</pre>" % (head, text)
     else:
         contents = f"<pre>{text}<pre>"
     doc.setHtml(contents)
     return doc
Esempio n. 30
0
def createTrayIcon():
    g.trayIconMenu = QtWidgets.QMenu()

    def new_note():
        c = g.app.commanders()[0]
        c.k.simulateCommand('stickynote-new')

    g.trayIconMenu.addAction("New note", new_note)
    g.trayIcon = QtWidgets.QSystemTrayIcon()
    g.trayIcon.setContextMenu(g.trayIconMenu)
    g.trayIcon.setIcon(QtGui.QIcon(g.app.leoDir + "/Icons/leoapp32.png"))
    g.trayIcon.setVisible(True)