Example #1
0
 def fileDiff(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     path = str(self.fileParentMenu.menuAction().data().toString())
     with open(path) as f:
         content = f.read()
     self.__svnDiff(path, content, False)
     QApplication.restoreOverrideCursor()
    def onRemoveCustomColors(self):
        """Removing the previously set custom colors"""
        if not self.__actionPrerequisites():
            return

        # Memorize the current selection
        selection = self.serializeSelection()

        editor = self.selectedItems()[0].getEditor()
        with editor:
            for item in self.sortSelectedReverse():
                if item.kind in [
                        CellElement.OPENED_GROUP_BEGIN,
                        CellElement.COLLAPSED_GROUP, CellElement.EMPTY_GROUP
                ]:
                    item.groupBeginCMLRef.removeCustomColors(editor)
                    continue
                if item.isDocstring():
                    cmlComment = CMLVersion.find(
                        item.ref.docstring.leadingCMLComments, CMLcc)
                else:
                    cmlComment = CMLVersion.find(item.ref.leadingCMLComments,
                                                 CMLcc)
                if cmlComment is not None:
                    cmlComment.removeFromText(editor)
        QApplication.processEvents()
        self.parent().redrawNow()
        self.restoreSelectionByID(selection)
Example #3
0
    def __notifyCallback(self, event):
        """Called by pysvn. event is a dictionary"""
        if 'path' not in event:
            return
        if not event['path']:
            return

        message = None
        path = event['path']
        if os.path.isdir(path) and not path.endswith(os.path.sep):
            path += os.path.sep
        if event['action'] == pysvn.wc_notify_action.update_completed:
            message = path + " updated to revision " + str(event['revision'].number)
        elif event['action'] == pysvn.wc_notify_action.update_started:
            message = "updating " + path + ":"
        else:
            self.__updatedPaths.append(path)
            action = notifyActionToString(event['action'])
            if action is not None and action != "unknown":
                message = "  " + action + " " + path
                if event['mime_type'] == "application/octet-stream":
                    message += " (binary)"

        if message:
            self.__infoLabel.setText(message.strip())
            logging.info(message)
        QApplication.processEvents()
Example #4
0
    def __generate(self):
        """[Generates and] opens the pylintrc file"""
        editorWidget = self.ide.currentEditorWidget
        fileName = editorWidget.getFileName()
        if not os.path.isabs(fileName):
            fileName = None
        rcfile = self.__pylintDriver.getPylintrc(self.ide, fileName)
        if not rcfile:
            if fileName is None and not self.ide.project.isLoaded():
                logging.error('Cannot generate pylintrc. '
                              'The current buffer file has not been saved yet '
                              'and there is no project')
                return

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            rcfile = self.__pylintDriver.generateRCFile(self.ide, fileName)
            QApplication.restoreOverrideCursor()

        if rcfile:
            if os.path.exists(rcfile):
                self.ide.mainWindow.openFile(rcfile, 0)
                return

        # It really could be only the rc generating error
        logging.error('Error generating pylintrc file ' + str(rcfile))
Example #5
0
    def onGroupEditTitle(self):
        """Edit (or view) the group title"""
        if not self.__actionPrerequisites():
            return

        # Memorize the current selection
        selection = self.serializeSelection()

        dlg = ReplaceTextDialog('Group title', 'Group title:', self.parent())

        # If it was one item selection and there was a previous text then
        # set it for editing
        if len(self.selectedItems()) == 1:
            title = self.selectedItems()[0].getTitle()
            if title:
                dlg.setText(title)

        if dlg.exec_():
            newTitle = dlg.text()
            editor = self.selectedItems()[0].getEditor()
            with editor:
                for item in self.sortSelectedReverse():
                    item.groupBeginCMLRef.updateTitle(editor, newTitle)
            QApplication.processEvents()
            self.parent().redrawNow()
            self.restoreSelectionByID(selection)
Example #6
0
    def onSwitchIfBranch(self):
        """If primitive should switch the branches"""
        if not self.__actionPrerequisites():
            return

        # Memorize the current selection
        selection = self.serializeSelection()

        # The selected items need to be sorted in the reverse line no oreder
        editor = self.selectedItems()[0].getEditor()
        with editor:
            for item in self.sortSelectedReverse():
                if item.kind == CellElement.IF:
                    cmlComment = CMLVersion.find(item.ref.leadingCMLComments,
                                                 CMLsw)
                    if cmlComment is None:
                        # Did not exist, so needs to be generated
                        line = CMLsw.generate(item.ref.body.beginPos)
                        lineNo = item.getFirstLine()
                        editor.insertLines(line, lineNo)
                    else:
                        # Existed, so it just needs to be deleted
                        cmlComment.removeFromText(editor)
        QApplication.processEvents()
        self.parent().redrawNow()
        self.restoreSelectionByID(selection)
Example #7
0
    def leaveEvent(self, event):
        """Triggered when the cursor leaves the find results tree"""
        searchTooltip.setInside(False)

        QApplication.processEvents()
        hideSearchTooltip()
        QTreeWidget.leaveEvent(self, event)
Example #8
0
 def notifyCallback(event):
     if event['path']:
         action = notifyActionToString(event['action'])
         if action:
             logging.info("Commit: " + action + " " + event['path'])
             QApplication.processEvents()
     return
Example #9
0
    def __onCopy(self):
        """Copy the content as text to clipboard"""
        content = []
        lhsMaxLength = 0
        try:
            item = self.calltraceList.topLevelItem(0)
            while item is not None:
                call = '<-'
                if item.data(0, Qt.UserRole):
                    call = '->'
                lhs = item.text(1)
                lhsLength = len(lhs)
                lhsMaxLength = max(lhsMaxLength, lhsLength)

                content.append([lhs, lhsLength, call + ' ' + item.text(2)])
                item = self.calltraceList.itemBelow(item)

            for index in range(len(content)):
                content[index] = \
                    content[index][0] + \
                    ' ' * (lhsMaxLength - content[index][1] + 1) + \
                    content[index][2]

            QApplication.clipboard().setText('\n'.join(content))
        except Exception as exc:
            logging.error('Error copying the call trace to clipboard: ' +
                          str(exc))
Example #10
0
    def onGroup(self):
        """Groups items into a single one"""
        dlg = ReplaceTextDialog('Group title', 'Group title:', self.parent())

        if dlg.exec_():
            groupTitle = dlg.text()
            selected = self.__extendSelectionForGrouping()
            selected = self.sortSelected(selected)
            editor = selected[0].getEditor()

            firstLine, lastLine, pos = self.__getLineRange(selected)

            groupid = self.parent().generateNewGroupId()
            beginComment = CMLgb.generate(groupid, groupTitle,
                                          None, None, None, pos)
            endComment = CMLge.generate(groupid, pos)

            with editor:
                editor.insertLines(endComment, lastLine + 1)
                editor.insertLines(beginComment, firstLine)

            # Redraw the group collapsed
            fileName = editor._parent.getFileName()
            if not fileName:
                fileName = editor._parent.getShortName()
            addCollapsedGroup(fileName, groupid)

            QApplication.processEvents()
            self.parent().redrawNow()
Example #11
0
def doSVNAnnotate(client, path,
                  revStart=None, revEnd=None, revPeg=None):
    """Performs the SVN annotate for the given path"""
    if revStart is None:
        revStart = pysvn.Revision(pysvn.opt_revision_kind.number, 0)
    if revEnd is None:
        revEnd = pysvn.Revision(pysvn.opt_revision_kind.head)
    if revPeg is None:
        revPeg = pysvn.Revision(pysvn.opt_revision_kind.unspecified)

    progressDialog = SVNAnnotateProgress(client, path,
                                         revStart, revEnd, revPeg)
    QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    res = progressDialog.exec_()
    QApplication.restoreOverrideCursor()

    if res == QDialog.Accepted:
        fullText = "\n".join([lineInfo['line']
                              for lineInfo in progressDialog.annotation])

        revisions = deepcopy(progressDialog.revisionsInfo.keys())
        revisionPerLine = []
        for lineInfo in progressDialog.annotation:
            revNumber = lineInfo['revision'].number
            revisionPerLine.append(revNumber)
            if revNumber in revisions:
                progressDialog.revisionsInfo[revNumber]['date'] = lineInfo['date']
                progressDialog.revisionsInfo[revNumber]['author'] = lineInfo['author']
                revisions.remove(revNumber)

        return fullText, revisionPerLine, progressDialog.revisionsInfo

    return None, None, None
Example #12
0
 def bufferDiff(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     editorWidget = self.ide.currentEditorWidget
     path = editorWidget.getFileName()
     content = self.ide.currentEditorWidget.getEditor().text()
     self.__svnDiff(path, content, editorWidget.isModified())
     QApplication.restoreOverrideCursor()
Example #13
0
def __scanDir(prefix, path, infoLabel=None):
    """Recursive scan for modules"""
    if infoLabel is not None:
        infoLabel.setText("Scanning " + path + "...")
        QApplication.processEvents()

    result = []
    for item in os.listdir(path):
        if item in [".svn", ".cvs", ".git", ".hg"]:
            continue
        if os.path.isdir(path + item):
            result += __scanDir(prefix + item + ".", path + item + os.path.sep,
                                infoLabel)
            continue

        if not isPythonFile(path + item):
            continue
        if item.startswith('__init__.'):
            if prefix != "":
                result.append(prefix[:-1])
            continue

        nameParts = item.split('.')
        result.append(prefix + nameParts[0])
    return result
Example #14
0
    def onShowCalltip(self, showMessage=True):
        """The user requested show calltip"""
        if self.__calltip is not None:
            self.__resetCalltip()
            return
        if not self.isPythonBuffer():
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        signatures = getCallSignatures(self, self._parent.getFileName())
        QApplication.restoreOverrideCursor()

        if not signatures:
            if showMessage:
                GlobalData().mainWindow.showStatusBarMessage(
                    "No calltip found")
            return

        # For the time being let's take only the first signature...
        calltipParams = []
        for param in signatures[0].params:
            calltipParams.append(param.description[len(param.type) + 1:])
        calltip = signatures[0].name + '(' + ', '.join(calltipParams) + ')'

        self.__calltip = Calltip(self)
        self.__calltip.showCalltip(calltip, signatures[0].index)

        line = signatures[0].bracket_start[0]
        column = signatures[0].bracket_start[1]
        self.__callPosition = self.mapToAbsPosition(line - 1, column)
Example #15
0
 def onCtrlC(self):
     """Handles copying"""
     if self.selectedText:
         QApplication.clipboard().setText(self.selectedText)
     else:
         line, _ = self.cursorPosition
         if self.lines[line]:
             QApplication.clipboard().setText(self.lines[line] + '\n')
Example #16
0
 def onCopyFileNameToClipboard(self):
     """Copies the file name of the current file into the clipboard"""
     txt = self.__getPathLabelFilePath()
     if txt.lower():
         try:
             QApplication.clipboard().setText(os.path.basename(txt))
         except:
             pass
Example #17
0
 def __onMemtop(self):
     """mem_top report"""
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     try:
         print(mem_top(limit=100, width=400))
     except Exception as exc:
         logging.error(str(exc))
     QApplication.restoreOverrideCursor()
Example #18
0
 def __switchToIdle(self):
     """Switching to the idle mode"""
     QApplication.restoreOverrideCursor()
     # enable buttons
     for _, _, tabWidget in self.ide.editorsManager.getTextEditors():
         pylintAction = tabWidget.toolbar.findChild(QAction, 'pylint')
         if pylintAction is not None:
             pylintAction.setEnabled(self.__canRun(tabWidget)[0])
Example #19
0
 def show(self):
     """Shows the tooltip at the proper position"""
     QToolTip.hideText()
     QApplication.processEvents()
     if self.__inside:
         self.move(self.__getTooltipPos())
         self.raise_()
         QFrame.show(self)
Example #20
0
 def __switchToRunning(self):
     """Switching to the running mode"""
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     # disable buttons
     for _, _, tabWidget in self.ide.editorsManager.getTextEditors():
         pylintAction = tabWidget.toolbar.findChild(QAction, 'pylint')
         if pylintAction is not None:
             pylintAction.setEnabled(False)
Example #21
0
    def onEditDoc(self):
        """Editing the CML doc comment"""
        if not self.__actionPrerequisites():
            return

        selectedItem = self.selectedItems()[0]  # Exactly one is selected
        editor = selectedItem.getEditor()
        fileName = editor._parent.getFileName()
        if not fileName:
            fileName = editor._parent.getShortName()

        # It could be a CML doc or an item which has a CML doc
        if selectedItem.isComment():
            cmlRef = selectedItem.cmlRef
        else:
            # If not found then it means the doc link needs to be created
            cmlRef = self.__findCMLinItem(selectedItem, CMLdoc)

        dlg = DocLinkAnchorDialog('Add' if cmlRef is None else 'Edit',
                                  cmlRef, fileName, self.parent())
        if dlg.exec_():
            link = dlg.linkEdit.text().strip()
            anchor = dlg.anchorEdit.text().strip()
            title = dlg.title()
            needToCreate = dlg.needToCreate()

            # First create a file if asked
            if needToCreate:
                docFileName = self.__createDocFile(link, fileName)
                if not docFileName:
                    return

            selection = self.serializeSelection()
            with editor:
                # Now insert a new cml comment or update existing
                if cmlRef:
                    # It is editing, the comment exists
                    lineNo = cmlRef.ref.beginLine
                    pos = cmlRef.ref.beginPos
                    cmlRef.removeFromText(editor)
                    bgColor = cmlRef.bgColor
                    fgColor = cmlRef.fgColor
                    border = cmlRef.border
                else:
                    # It is a new doc link
                    lineNo = selectedItem.getFirstLine()
                    pos = selectedItem.ref.body.beginPos
                    bgColor = None
                    fgColor = None
                    border = None

                line = CMLdoc.generate(link, anchor, title,
                                       bgColor, fgColor, border, pos)
                editor.insertLines(line, lineNo)

            QApplication.processEvents()
            self.parent().redrawNow()
            self.restoreSelectionByID(selection)
Example #22
0
 def onCopyDirToClipboard(self):
     """Copies the dir path of the current file into the clipboard"""
     txt = self.__getPathLabelFilePath()
     if txt.lower():
         try:
             QApplication.clipboard().setText(os.path.dirname(txt) +
                                              os.path.sep)
         except:
             pass
Example #23
0
 def closeEvent(self, event):
     """Window close event handler"""
     if self.__inProcess:
         self.__cancelRequest = True
         self.__infoLabel.setText("Cancelling...")
         QApplication.processEvents()
         event.ignore()
     else:
         event.accept()
Example #24
0
 def __svnUpdate(self, path, recursively, rev=None):
     """Does SVN update"""
     client = self.getSVNClient(self.getSettings())
     if rev is None:
         rev = pysvn.Revision(pysvn.opt_revision_kind.head)
     progressDialog = SVNUpdateProgress(self, client, path, recursively, rev)
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     progressDialog.exec_()
     QApplication.restoreOverrideCursor()
Example #25
0
 def __onRepeatedAction(self):
     """Repeated action"""
     for x in range(100):
         self.ide.mainWindow.em.newTabClicked(initialContent=None,
                                              shortName=str(x) + '.py',
                                              mime='text/x-python')
         QApplication.processEvents()
         self.ide.mainWindow.em.onCloseTab()
         QApplication.processEvents()
Example #26
0
 def onShiftDel(self):
     """Triggered when Shift+Del is received"""
     if self.selectedText:
         QApplication.clipboard().setText(self.selectedText)
         self.selectedText = ''
     else:
         line, _ = self.cursorPosition
         if self.lines[line]:
             QApplication.clipboard().setText(self.lines[line] + '\n')
             del self.lines[line]
Example #27
0
    def __svnLog(self, path):
        """Does SVN annotate"""
        client = self.getSVNClient(self.getSettings())
        dlg = SVNLogProgress(client, path)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        res = dlg.exec_()
        QApplication.restoreOverrideCursor()

        if res == QDialog.Accepted:
            dlg = SVNPluginLogDialog(self, client, path, dlg.logInfo)
            dlg.exec_()
Example #28
0
    def onAutoAddDoc(self):
        """Create a doc file, add a link and open for editing"""
        if not self.__actionPrerequisites():
            return

        selectedItem = self.selectedItems()[0]  # Exactly one is selected
        editor = selectedItem.getEditor()
        fileName = editor._parent.getFileName()
        if not fileName:
            logging.error('Save file before invoking auto doc')
            return

        needContent = False
        newAnchor = 'doc' + str(uuid.uuid4().fields[-1])[-6:]

        docFileName = self.__getAutoDocFileName(fileName)
        if not os.path.exists(docFileName):
            # Create file and populate with the default content
            try:
                os.makedirs(os.path.dirname(docFileName), exist_ok=True)
                with open(docFileName, 'w') as f:
                    pass
            except Exception as exc:
                logging.error('Error creating the documentation file ' +
                              docFileName + ': ' + str(exc))
                return
            needContent = True

        project = GlobalData().project
        if project.isProjectFile(docFileName):
            link = project.getRelativePath(docFileName)
        else:
            link = os.path.relpath(docFileName, fileName)

        # Insert a doc link
        with editor:
            lineNo = selectedItem.getFirstLine()
            line = CMLdoc.generate(link, newAnchor, 'See documentation',
                                   None, None, None,
                                   selectedItem.ref.body.beginPos)
            editor.insertLines(line, lineNo)

            QApplication.processEvents()
            self.parent().redrawNow()

        # Open the file
        if GlobalData().mainWindow.openFile(docFileName, -1):
            if needContent:
                widget = GlobalData().mainWindow.em.getWidgetForFileName(docFileName)
                editor = widget.getEditor()
                editor.text = getDefaultFileDoc(fileName, newAnchor)
                editor.document().setModified(False)
Example #29
0
 def __openedFiles(self, filters):
     """Currently opened editor buffers"""
     files = []
     openedFiles = self.editorsManager.getTextEditors()
     for record in openedFiles:
         uuid = record[0]
         fname = record[1]
         if self.__filterMatch(filters, fname):
             files.append(ItemToSearchIn(fname, uuid))
         QApplication.processEvents()
         if self.__cancelRequest:
             raise Exception("Cancel request")
     return files
Example #30
0
    def resize(self, controlItem):
        """Moves the popup to the proper position"""
        # calculate the positions above the group
        # Taken from here:
        # https://stackoverflow.com/questions/9871749/find-screen-position-of-a-qgraphicsitem
        scene = controlItem.ref.scene()
        view = scene.views()[0]
        sceneP = controlItem.mapToScene(controlItem.boundingRect().topLeft())
        viewP = view.mapFromScene(sceneP)
        pos = view.viewport().mapToGlobal(viewP)

        self.move(pos.x(), pos.y() - self.height() - 2)
        QApplication.processEvents()