Ejemplo n.º 1
0
def bzr_qcommands(c, p, menu):
    """see module docs."""

    menu = menu.addMenu("bzr")

    # special case, no q* command for stat
    def bzr_stat(c=c, p=p):
        path = g.scanAllAtPathDirectives(c, p) or c.getNodePath(p)
        cmd = subprocess.Popen(['bzr', 'stat', path],
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        stdout, stderr = cmd.communicate()
        g.es("\n\n".join([stdout, stderr]))

    action = menu.addAction('stat')
    action.connect(action, QtCore.SIGNAL("triggered()"), bzr_stat)

    qcoms = "qadd qannotate qbind qbranch qbrowse qcat qcommit qconfig " \
            "qconflicts qdiff qexport qgetnew qgetupdates qinfo qinit " \
            "qlog qmerge qplugins qpull qpush qrevert qrun qsend " \
            "qswitch qtag qunbind quncommit qupdate qversion qviewer".split()
    for qcom in qcoms:

        def cmd(c=c, p=p, qcom=qcom):
            path = g.scanAllAtPathDirectives(c, p) or c.getNodePath(p)
            cmd = subprocess.Popen(['bzr', qcom, path])
            cmd.communicate()

        action = menu.addAction(qcom)
        action.connect(action, QtCore.SIGNAL("triggered()"), cmd)
Ejemplo n.º 2
0
    def doLayout(self, rect, testOnly):

        x = rect.x()
        y = rect.y()
        lineHeight = 0
        for item in self.itemList:
            wid = item.widget()
            spaceX = self.spacing() + wid.style().layoutSpacing(
                QtWidgets.QSizePolicy.PushButton,
                QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Horizontal)
            spaceY = self.spacing() + wid.style().layoutSpacing(
                QtWidgets.QSizePolicy.PushButton,
                QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0
            if not testOnly:
                item.setGeometry(
                    QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())
        return y + lineHeight - rect.y()
Ejemplo n.º 3
0
    def minimumSize(self):

        size = QtCore.QSize()
        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())
        size += QtCore.QSize(2 * self.margin(), 2 * self.margin())
        return size
Ejemplo n.º 4
0
 def run(self):
     '''The thread's run method: called via start.'''
     # pylint: disable=arguments-differ
     from leo.core.leoQt import QtCore
     QtCore.pyqtRemoveInputHook() # From g.pdb
     if self.path:
         self.run_path(self.path)
     else:
         self.set_trace()
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
 def run(self):
     '''The thread's run method: called via start.'''
     # pylint: disable=arguments-differ
     from leo.core.leoQt import QtCore
     QtCore.pyqtRemoveInputHook() # From g.pdb
     if self.path:
         self.run_path(self.path)
     else:
         self.set_trace()
Ejemplo n.º 7
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
Ejemplo n.º 8
0
 def __init__(self, handler, delay=500, tag=None):
     """ctor for IdleTime class."""
     # For use by handlers...
     self.count = 0
     # The number of times handler has been called.
     self.starting_time = None
     # Time that the timer started.
     self.time = None
     # Time that the handle is called.
     self.tag = tag
     # An arbitrary string/object for use during debugging.
     # For use by the IdleTime class...
     self.delay = delay
     # The argument to self.timer.start:
     # 0 for idle time, otherwise a delay in msec.
     self.enabled = False
     # True: run the timer continuously.
     self.handler = handler
     # The user-provided idle-time handler.
     self.waiting_for_idle = False
     # True if we have already waited for the minimum delay\
     # Create the timer, but do not fire it.
     self.timer = QtCore.QTimer()
     self.timer.timeout.connect(self.at_idle_time)
     # Add this instance to the global idle_timers.list.
     # This reference prevents this instance from being destroyed.
     g.app.idle_timers.append(self)
Ejemplo n.º 9
0
    def start (self,event):
        
        c = self.c
        
        # Create the callback to insert the selected completion.
        def completion_callback(completion,self=self):
            self.end(completion)
        
        # Create the completer.
        cpl = c.frame.top.completer = self.completer = QCompleter()
        cpl.setWidget(self.body)
        cpl.connect(cpl,QtCore.SIGNAL("activated(QString)"),completion_callback)
        
        # Connect key strokes to the popup.
        # self.popup = cpl.popup()
        # self.popup_filter = PopupEventFilter(c,self.popup) # Required
        # self.popup.installEventFilter(self.popup_filter)
        # self.popup.setFocus()

        # Set the flag for the event filter: all keystrokes will go to cc.onKey.
        self.active = True
        self.ev_filter.ctagscompleter_active = True
        self.ev_filter.ctagscompleter_onKey = self.onKey
        
        # Show the completions.
        self.complete(event)
Ejemplo n.º 10
0
class Repeater(QtCore.QThread):
    """ execute f forever, signal on every run """

    fragment = QtCore.pyqtSignal(object)

    #@+others
    #@+node:ekr.20121126095734.12428: *3* __init__
    def __init__(self, f, parent=None):

        super().__init__(parent)
        self.f = f

    #@+node:ekr.20121126095734.12429: *3* run
    def run(self):
        while 1:
            try:
                res = self.f()
            except StopIteration:
                return
            except Exception:
                typ, val, tb = sys.exc_info()
                print('')
                print('threadutil.py: unexpected exception in Repeater.run')
                print('')
                # Like g.es_exception()
                lines = traceback.format_exception(typ, val, tb)
                for line in lines:
                    print(line.rstrip())
                return
            self.fragment.emit(res)
Ejemplo n.º 11
0
    def build(self, n=3, columns=3, year=None, month=None):

        self.calendars = []

        if year is None:
            year = datetime.date.today().year
        if month is None:
            month = datetime.date.today().month

        layout = QtWidgets.QGridLayout()
        while self.layout().count():
            self.layout().removeItem(self.layout().itemAt(0))
        self.layout().addLayout(layout)
        size = self.minimumSizeHint()
        x, y = size.width(), size.height()
        x *= min(n, columns)
        y *= 1 + ((n - 1) // columns)
        self.setMinimumSize(QtCore.QSize(x, y))

        for i in range(n):
            calendar = QtWidgets.QCalendarWidget()
            calendar.i = i
            calendar.setCurrentPage(year, month)
            month += 1
            if month == 13:
                year += 1
                month = 1
            calendar.currentPageChanged.connect(
                lambda year, month, cal=calendar: self.currentPageChanged(
                    year, month, cal))
            calendar.clicked.connect(self.return_result)
            calendar.activated.connect(self.return_result)
            self.calendars.append(calendar)
            layout.addWidget(calendar, i // columns, i % columns)
Ejemplo n.º 12
0
    def connected(self):

        '''Event handler for newConnection.'''

        lprint("hnd con")
        lsock = self.srv.nextPendingConnection()
        lprint("conn", lsock)

        buf =  LProtoBuf()

        self.ses[lsock] = ses_ent = {'_sock': lsock, '_buf': buf}

        def msg_recv_cb(msg):
            self.msg_received(msg, ses_ent)

        buf.set_recv_cb( msg_recv_cb )

        def readyread_cb():
            lprint("read ready")
            allbytes = lsock.readAll()
            buf = ses_ent['_buf']
            buf.push_bytes(allbytes)

        lsock.connect(lsock,
            QtCore.SIGNAL('readyRead()'),
            readyread_cb)
Ejemplo n.º 13
0
 def set_top_geometry(self, geometry):
     top = self.c.frame.top
     widget = getattr(top, 'leo_master', None) or top
     if isinstance(geometry, QtCore.QRect):
         widget.setGeometry(geometry)
     else:
         x, y, w, h = geometry
         widget.setGeometry(QtCore.QRect(x, y, w, h))
Ejemplo n.º 14
0
    def __init__(self):

        self.srv = QtNetwork.QLocalServer()
        self.receiver = None
        self.ses = {}

        self.is_connected = self.srv.connect(self.srv,
                                             QtCore.SIGNAL("newConnection()"),
                                             self.connected)
Ejemplo n.º 15
0
    def __init__(self, *args, **kargs):
        nodeBase.__init__(self, *args, **kargs)

        self.bg = self.bg_item()

        self.setZValue(20)
        self.bg.setZValue(10)

        self.bg.setPos(QtCore.QPointF(0, self.iconVPos))
        self.addToGroup(self.bg)
Ejemplo n.º 16
0
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)

        self.text = self.text_item()

        self.setZValue(20)
        self.text.setZValue(15)

        self.text.setPos(QtCore.QPointF(0, self.iconVPos))
        self.addToGroup(self.text)
Ejemplo n.º 17
0
    def setLine(self, x0, y0, x1, y1, hierarchyLink=False):

        self.line.setLine(x0, y0, x1, y1)

        x, y = x1 - (x1 - x0) / 3., y1 - (y1 - y0) / 3.

        if not hierarchyLink:
            r = 12.
        else:
            r = 6.

        a = atan2(y1 - y0, x1 - x0)
        w = 2.79252680
        pts = [
            QtCore.QPointF(x, y),
            QtCore.QPointF(x + r * cos(a + w), y + r * sin(a + w)),
            QtCore.QPointF(x + r * cos(a - w), y + r * sin(a - w)),
            # QtCore.QPointF(x, y),
        ]
        self.head.setPolygon(QtGui.QPolygonF(pts))
Ejemplo n.º 18
0
def async_syscmd(cmd, onfinished):
    proc = QtCore.QProcess()

    def cmd_handler(exitstatus):
        out = proc.readAllStandardOutput()
        err = proc.readAllStandardError()
        #print "got",out, "e", err, "r", exitstatus
        onfinished(exitstatus, out, err)

    proc.finished[int].connect(cmd_handler)

    proc.start(cmd)
Ejemplo n.º 19
0
 def __init__(self) -> None:
     """Ctor for the base BackgroundProcessManager class."""
     self.data: Any = None  # a ProcessData instance.
     self.process_queue: List = []  # List of g.Bunches.
     self.pid: Any = None  # The process id of the running process.
     self.lock = thread.allocate_lock()
     self.process_return_data: List[str] = None
     # #2528: A timer that runs independently of idle time.
     self.timer = None
     if QtCore:
         self.timer = QtCore.QTimer()
         self.timer.timeout.connect(self.on_idle)
Ejemplo n.º 20
0
    def __init__(self, c, mode="nav", parent=None):

        QtWidgets.QWidget.__init__(self, parent)

        self.ui = qt_quicksearch.Ui_LeoQuickSearchWidget()
        self.ui.setupUi(self)

        # set to True after return is pressed in nav mode, to disable live updates until field is cleaned again
        self.frozen = False
        w = self.ui.listWidget
        u = self.ui
        cc = QuickSearchController(c, w, u)
        self.scon = cc

        if mode == "popout":
            self.setWindowTitle("Go anywhere")
            if 1:
                self.ui.lineEdit.returnPressed.connect(self.selectAndDismiss)
            else:
                self.connect(self.ui.lineEdit,
                             QtCore.SIGNAL("returnPressed()"),
                             self.selectAndDismiss)
            threadutil.later(self.ui.lineEdit.setFocus)
        else:
            if 1:
                self.ui.lineEdit.returnPressed.connect(self.returnPressed)
            else:
                self.connect(self.ui.lineEdit,
                             QtCore.SIGNAL("returnPressed()"),
                             self.returnPressed)
        if 1:
            self.ui.lineEdit.textChanged.connect(self.liveUpdate)
        else:
            self.connect(self.ui.lineEdit,
                         QtCore.SIGNAL("textChanged(QString)"),
                         self.liveUpdate)

        self.ev_filter = QuickSearchEventFilter(c, w, self.ui.lineEdit)
        self.ui.lineEdit.installEventFilter(self.ev_filter)
        self.c = c
Ejemplo n.º 21
0
class UnitWorker(QtCore.QThread):
    """ Work on one work item at a time, start new one when it's done """

    resultReady = QtCore.pyqtSignal()

    #@+others
    #@+node:ekr.20121126095734.12437: *3* __init__
    def __init__(self):
        QtCore.QThread.__init__(self)
        self.cond = QtCore.QWaitCondition()
        self.mutex = QtCore.QMutex()
        self.input = None

    #@+node:ekr.20121126095734.12438: *3* set_worker
    def set_worker(self, f):
        self.worker = f

    #@+node:ekr.20121126095734.12439: *3* set_output_f
    def set_output_f(self, f):
        self.output_f = f

    #@+node:ekr.20121126095734.12440: *3* set_input
    def set_input(self, inp):
        self.input = inp
        self.cond.wakeAll()

    #@+node:ekr.20121126095734.12441: *3* do_work
    def do_work(self, inp):
        #print("Doing work", self.worker, self.input)
        self.output = self.worker(inp)
        #self.output_f(output)

        self.resultReady.emit()

        def L():
            #print "Call output"
            self.output_f(self.output)

        later(L)

    #@+node:ekr.20121126095734.12442: *3* run
    def run(self):

        m = self.mutex
        while 1:
            m.lock()
            self.cond.wait(m)
            inp = self.input
            self.input = None
            m.unlock()
            if inp is not None:
                self.do_work(inp)
Ejemplo n.º 22
0
    def __init__(self, *args, **kargs):
        nodeBase.__init__(self, *args, **kargs)

        self.text = self.text_item()
        # .text must be first for nodeComment, see its bg_item()
        self.bg = self.bg_item()
        if g.app.config.getBool("color_theme_is_dark"):
            bgcolor = QtGui.QColor(30, 50, 30)
        else:
            bgcolor = QtGui.QColor(200, 240, 200)
        self.bg.setBrush(QtGui.QBrush(bgcolor))

        self.setZValue(20)
        self.bg.setZValue(10)
        self.text.setZValue(15)
        self.bg.setPen(QtGui.QPen(QtConst.NoPen))

        self.text.setPos(QtCore.QPointF(0, self.iconVPos))
        self.addToGroup(self.text)

        self.bg.setPos(QtCore.QPointF(0, self.iconVPos))
        self.addToGroup(self.bg)
Ejemplo n.º 23
0
    def run_one(self, ent, key):
        p = ent['proc'] = QtCore.QProcess()

        def fini(code, status):
            del self.cur[key]
            out = str(p.readAllStandardOutput())
            err = str(p.readAllStandardError())
            cb = ent['cb'] or self.default_cb
            later(self.sched)
            cb(out, err, status, ent)

        cmd = ent['arg'][0]
        args = ent['arg'][1:]
        p.start(cmd, args)
        p.finished.connect(fini)
Ejemplo n.º 24
0
    def show_tip(self, action):
        """show_tip - show a tooltip, calculate the box in which
        the pointer must stay for the tip to remain visible

        :Parameters:
        - `self`: this handle
        - `action`: action triggering event to display
        """
        if action.toolTip() == action.text():
            tip = ""
        else:
            tip = action.toolTip()
        pos = QtGui.QCursor.pos()
        x = pos.x()
        y = pos.y()
        rect = QtCore.QRect(x - 5, y - 5, x + 5, y + 5)
        QtWidgets.QToolTip.showText(pos, tip, action.parentWidget(), rect)
Ejemplo n.º 25
0
class Repeater(QtCore.QThread):
    """ execute f forever, signal on every run """

    fragment = QtCore.pyqtSignal(object)

    #@+others
    #@+node:ekr.20121126095734.12428: *3* __init__
    def __init__(self, f, parent=None):

        QtCore.QThread.__init__(self, parent)
        self.f = f

    #@+node:ekr.20121126095734.12429: *3* run
    def run(self):
        while 1:
            try:
                res = self.f()
            except StopIteration:
                return
            self.fragment.emit(res)
Ejemplo n.º 26
0
    def __init__(self, c):
        '''Ctor for NbController class.'''
        self.c = c
        self.gnxcache = {}
        self.mw = ModelWrapper(["h", "b", "gnx", "level", "style"])
        #self.add_all_nodes()
        #self.add_subtree(p)
        try:
            # pylint: disable=no-name-in-module
            from PyQt5.QtQuick import QQuickView
            self.view = view = QQuickView()
        except Exception:  #1746.
            self.view = view = QtDeclarative.QDeclarativeView()
        ctx = view.rootContext()

        @g.command("nb-all")
        def nb_all_f(event):
            self.add_all_nodes()
            self.view.show()

        @g.command("nb-subtree")
        def nb_subtree_f(event):
            p = self.c.p
            self.add_subtree(p)
            self.view.show()

        ctx.setContextProperty("nodesModel", self.mw.model)
        path = g.os_path_join(g.computeLeoDir(), 'plugins', 'qmlnb', 'qml',
                              'leonbmain.qml')
        view.setSource(QtCore.QUrl(path))
        if isQt5 or isQt6:
            mode = view.SizeRootObjectToView
        else:
            mode = QtDeclarative.QDeclarativeView.SizeRootObjectToView
        view.setResizeMode(mode)
        # Display the user interface and allow the user to interact with it.
        view.hide()
        view.setGeometry(100, 100, 800, 600)
        #view.show()
        c.dummy = view
Ejemplo n.º 27
0
 def __init__(self, owner):
     '''Ctor for backlinkQtUI class.'''
     self.owner = owner
     QtWidgets.QWidget.__init__(self)
     uiPath = g.os_path_join(g.app.leoDir, 'plugins', 'Backlink.ui')
     form_class, base_class = uic.loadUiType(uiPath)
     self.owner.c.frame.log.createTab('Links', widget = self) 
     self.UI = form_class()
     self.UI.setupUi(self)
     u = self.UI
     o = self.owner
     if 1: # Compatible with PyQt5
         u.markBtn.clicked.connect(o.mark)
         u.swapBtn.clicked.connect(o.swap)
         u.linkBtn.clicked.connect(self.linkClicked)
         u.rescanBtn.clicked.connect(o.loadLinksInt)
         u.dirLeftBtn.clicked.connect(self.dirClicked)
         u.dirRightBtn.clicked.connect( self.dirClicked)
         u.linkList.itemClicked.connect(self.listClicked)
         u.deleteBtn.stateChanged.connect(o.deleteSet)
     else: # old code 
         self.connect(u.markBtn,
             QtCore.SIGNAL("clicked()"), o.mark)
         self.connect(u.swapBtn,
             QtCore.SIGNAL("clicked()"), o.swap)
         self.connect(u.linkBtn,
             QtCore.SIGNAL("clicked()"), self.linkClicked)
         self.connect(u.rescanBtn,
             QtCore.SIGNAL("clicked()"), o.loadLinksInt)
         self.connect(u.dirLeftBtn, 
             QtCore.SIGNAL("clicked()"), self.dirClicked)
         self.connect(u.dirRightBtn, 
             QtCore.SIGNAL("clicked()"), self.dirClicked)
         self.connect(u.linkList,
             QtCore.SIGNAL("itemClicked(QListWidgetItem*)"), self.listClicked)
         self.connect(u.deleteBtn,
             QtCore.SIGNAL("stateChanged(int)"), o.deleteSet)
Ejemplo n.º 28
0
    def start (self,event):

        c = self.c

        # Create the callback to insert the selected completion.
        def completion_callback(completion,self=self):
            # pylint: disable=maybe-no-member
            self.end(completion)

        # Create the completer.
        cpl = c.frame.top.completer = self.completer = QCompleter()
        cpl.setWidget(self.body)
        cpl.connect(cpl,QtCore.SIGNAL("activated(QString)"),completion_callback)

        # Set the flag for the event filter: all keystrokes will go to cc.onKey.
        self.active = True
        self.ev_filter.ctagscompleter_active = True
        self.ev_filter.ctagscompleter_onKey = self.complete
            # EKR: was self.onKey, which does not exist.

        # Show the completions.
        self.complete(event)
Ejemplo n.º 29
0
 def update_svg(self, s, keywords):
     pc = self
     if pc.must_change_widget(pc.svg_class):
         w = pc.svg_class()
         pc.embed_widget(w)
         assert(w == pc.w)
     else:
         w = pc.w
     if s.strip().startswith('<'):
         # Assume it is the svg (xml) source.
         s = g.adjustTripleString(s, pc.c.tab_width).strip() # Sensitive to leading blank lines.
         s = g.toEncodedString(s)
         pc.show()
         w.load(QtCore.QByteArray(s))
         w.show()
     else:
         # Get a filename from the headline or body text.
         ok, path = pc.get_fn(s, '@svg')
         if ok:
             pc.show()
             w.load(path)
             w.show()
Ejemplo n.º 30
0
def rclick_path_importfile(c, p, menu):
    if not p.h.startswith('@path'):
        return

    def importfiles_rclick_cb():
        aList = g.get_directives_dict_list(p)
        path = c.scanAtPathDirectives(aList)
        table = [
            ("All files", "*"),
            ("Python files", "*.py"),
        ]
        # This is incomplete: files is not used.
        # files = g.app.gui.runOpenFileDialog(c,
        g.app.gui.runOpenFileDialog(c,
                                    title="Import files",
                                    filetypes=table,
                                    defaultextension='.notused',
                                    multiple=True)
        print("import files from", path)

    action = menu.addAction("Import files")
    action.connect(action, QtCore.SIGNAL("triggered()"), importfiles_rclick_cb)
Ejemplo n.º 31
0
    def __init__(self, c):

        self.c = c
        self.gnxcache = {}

        self.mw = ModelWrapper(["h", "b", "gnx", "level", "style"])

        #self.add_all_nodes()
        #self.add_subtree(p)
        self.view = view = QtDeclarative.QDeclarativeView()
        ctx = view.rootContext()

        @g.command("nb-all")
        def nb_all_f(event):
            self.add_all_nodes()
            self.view.show()

        @g.command("nb-subtree")
        def nb_subtree_f(event):
            p = self.c.p
            self.add_subtree(p)
            self.view.show()

        ctx.setContextProperty("nodesModel", self.mw.model)

        path = g.os_path_join(g.computeLeoDir(), 'plugins', 'qmlnb', 'qml',
                              'leonbmain.qml')
        view.setSource(QtCore.QUrl(path))
        view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
        # Display the user interface and allow the user to interact with it.
        view.hide()
        view.setGeometry(100, 100, 800, 600)

        #view.show()

        c.dummy = view