def readFile(self, fileName): """Reads the text from a file""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: content, self.encoding = readEncodedFile(fileName) self.eol = detectEolString(content) # Copied from enki (enki/core/document.py: _readFile()): # Strip last EOL. Qutepart adds it when saving file if content.endswith('\r\n'): content = content[:-2] elif content.endswith('\n') or content.endswith('\r'): content = content[:-1] self.text = content self.mime, _, xmlSyntaxFile = getFileProperties(fileName) if xmlSyntaxFile: self.detectSyntax(xmlSyntaxFile) self.document().setModified(False) except: QApplication.restoreOverrideCursor() raise QApplication.restoreOverrideCursor()
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))
def writeFile(self, fileName): """Writes the text to a file""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if Settings()['removeTrailingOnSave']: self.removeTrailingWhitespaces() try: encoding = detectWriteEncoding(self, fileName) if encoding is None: QApplication.restoreOverrideCursor() logging.error('Could not detect write encoding for ' + fileName) return False writeEncodedFile(fileName, self.textForSaving(), encoding) except Exception as exc: logging.error(str(exc)) QApplication.restoreOverrideCursor() return False self.encoding = encoding if self.explicitUserEncoding: userEncoding = getFileEncoding(fileName) if userEncoding != self.explicitUserEncoding: setFileEncoding(fileName, self.explicitUserEncoding) self.explicitUserEncoding = None self._parent.updateModificationTime(fileName) self._parent.setReloadDialogShown(False) QApplication.restoreOverrideCursor() return True
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)
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
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()
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 __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()
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)
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()
def activate(self, ideSettings, ideGlobalData): """Activates the plugin. The plugin may override the method to do specific plugin activation handling. ideSettings - reference to the IDE Settings singleton see codimension/src/utils/settings.py ideGlobalData - reference to the IDE global settings see codimension/src/utils/globals.py Note: if overriden do not forget to call the base class activate() """ WizardInterface.activate(self, ideSettings, ideGlobalData) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: self.__where = self.__getConfiguredWhere() mainToolbar = self.ide.mainWindow.getToolbar() beforeWidget = mainToolbar.findChild(QAction, 'debugSpacer') self.__separator = mainToolbar.insertSeparator(beforeWidget) self.__memtopButton = QAction( QIcon(PLUGIN_HOME_DIR + 'memtop.png'), 'memtop report', mainToolbar) self.__memtopButton.triggered.connect(self.__onMemtop) mainToolbar.insertAction(beforeWidget, self.__memtopButton) self.__debuggerButton = QAction( QIcon(PLUGIN_HOME_DIR + 'debugger.png'), 'stop with debugger', mainToolbar) self.__debuggerButton.triggered.connect(self.__onDebugger) mainToolbar.insertAction(beforeWidget, self.__debuggerButton) self.__repeatButton = QAction( QIcon(PLUGIN_HOME_DIR + 'repeat.png'), 'Repeated actions', mainToolbar) self.__repeatButton.triggered.connect(self.__onRepeatedAction) mainToolbar.insertAction(beforeWidget, self.__repeatButton) self.__resetButton = QAction(QIcon(PLUGIN_HOME_DIR + 'reset.png'), 'Reset the heap reference point', mainToolbar) self.__resetButton.triggered.connect(self.__onResetHeap) mainToolbar.insertAction(beforeWidget, self.__resetButton) self.hpy = hpy() self.hpy.setref() except: QApplication.restoreOverrideCursor() raise QApplication.restoreOverrideCursor()
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_()
def __newConnection(self): """Handles new incoming connections""" clientSocket = self.__tcpServer.nextPendingConnection() clientSocket.setSocketOption(QAbstractSocket.KeepAliveOption, 1) clientSocket.setSocketOption(QAbstractSocket.LowDelayOption, 1) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: self.__waitForHandshake(clientSocket) except: QApplication.restoreOverrideCursor() raise QApplication.restoreOverrideCursor()
def onDiff(self, path, status): """Triggered when diff for the path is called""" if not path: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: # Status is one of the following: # IND_ADDED, IND_DELETED, IND_MERGED, IND_MODIFIED_LR, IND_MODIFIED_L, IND_CONFLICTED repositoryContent = "" localContent = "" if status != IND_ADDED: client = self.__plugin.getSVNClient( self.__plugin.getSettings()) repositoryContent = client.cat(path) if status != IND_DELETED: with open(path) as f: localContent = f.read() diff = difflib.unified_diff(repositoryContent.splitlines(), localContent.splitlines()) nodiffMessage = path + " has no difference to the " \ "repository at revision HEAD" if diff is None: QApplication.restoreOverrideCursor() logging.info(nodiffMessage) return # There are changes, so replace the text and tell about the changes diffAsText = '\n'.join(list(diff)) if diffAsText.strip() == '': QApplication.restoreOverrideCursor() logging.info(nodiffMessage) return source = "+++ local " + os.path.basename(path) diffAsText = diffAsText.replace("+++ ", source, 1) diffAsText = diffAsText.replace("--- ", "--- repository at revision HEAD", 1) self.__diffViewer.setHTML( parse_from_memory(diffAsText, False, True)) if not self.__diffViewer.isVisible(): self.__onShowHideDiff() except Exception as exc: logging.error(str(exc)) except: logging.error("Unknown error while calculating difference for " + path) QApplication.restoreOverrideCursor()
def onOccurences(self): """The user requested a list of occurences""" if not self.isPythonBuffer(): return if self._parent.getType() == MainWindowTabWidgetBase.VCSAnnotateViewer: return if not os.path.isabs(self._parent.getFileName()): GlobalData().mainWindow.showStatusBarMessage( "Please save the buffer and try again") return fileName = self._parent.getFileName() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) definitions = getOccurrences(self, fileName) QApplication.restoreOverrideCursor() result = [] for definition in definitions: if definition.line is None or definition.module_path is None: continue fName = definition.module_path if not fName: fName = fileName lineno = definition.line index = getSearchItemIndex(result, fName) if index < 0: widget = GlobalData().mainWindow.getWidgetForFileName(fName) if widget is None: uuid = "" else: uuid = widget.getUUID() newItem = ItemToSearchIn(fName, uuid) result.append(newItem) index = len(result) - 1 result[index].addMatch(definition.name, lineno) if len(result) == 0: GlobalData().mainWindow.showStatusBarMessage('No occurences found') return # There are found items GlobalData().mainWindow.showStatusBarMessage('') GlobalData().mainWindow.displayFindInFiles( OccurrencesSearchProvider().getName(), result, {'name': definitions[0].name, 'filename': fileName, 'line': self.cursorPosition[0] + 1, 'column': self.cursorPosition[1]})
def readProperties(client, path): """Reads properties of the given path""" # Properties are always read locally so a progress dialog is not required QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) properties = None try: properties = client.proplist(path) except pysvn.ClientError as exc: message = exc.args[0] logging.error(message) except Exception as exc: logging.error(str(exc)) except: logging.error("Unknown error while retrieving properties of " + path) QApplication.restoreOverrideCursor() return properties
def onAutoComplete(self): """Triggered when ctrl+space or TAB is clicked""" if self.isReadOnly(): return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.__inCompletion = True self.__completionPrefix = self.getWordBeforeCursor() words = getCompletionList(self, self._parent.getFileName()) QApplication.restoreOverrideCursor() if len(words) == 0: self.setFocus() self.__inCompletion = False return self.__completer.setWordsList(words, self.font()) self.__completer.setPrefix(self.__completionPrefix) count = self.__completer.completionCount() if count == 0: self.setFocus() self.__inCompletion = False return # Make sure the line is visible line, _ = self.cursorPosition self.ensureLineOnScreen(line + 1) # Remove the selection as it could be interpreted not as expected if self.selectedText: self.clearSelection() if count == 1: self.insertCompletion(self.__completer.currentCompletion()) else: cRectangle = self.cursorRect() cRectangle.setLeft(cRectangle.left() + self.viewport().x()) cRectangle.setTop(cRectangle.top() + self.viewport().y() + 2) self.__completer.complete(cRectangle) # If something was selected then the next tab does not need to # bring the completion again. This is covered in the # insertCompletion() method. Here we reset the last tab position # preliminary because it is unknown if something will be inserted. self.__lastTabPosition = None self.__inCompletion = False
def onDiffBetween(self, rev, prevRev): """Called when diff is requested between revisions""" if not rev or not prevRev: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: lhsContent = self.__client.cat(self.__path, prevRev) rhsContent = self.__client.cat(self.__path, rev) except Exception as exc: QApplication.restoreOverrideCursor() logging.error(str(exc)) return except: QApplication.restoreOverrideCursor() logging.error("Unknown error while retrieving " + self.__path + " content from the repository.") return QApplication.restoreOverrideCursor() diff = difflib.unified_diff(lhsContent.splitlines(), rhsContent.splitlines()) nodiffMessage = self.__path + " has no difference from revision " + \ str(prevRev.number) + " to revision " + str(rev.number) if diff is None: logging.info(nodiffMessage) return # There are changes, so replace the text and tell about the changes diffAsText = '\n'.join(list(diff)) if diffAsText.strip() == '': logging.info(nodiffMessage) return lhs = "--- revision " + str(prevRev.number) diffAsText = diffAsText.replace("--- ", lhs, 1) rhs = "+++ revision " + str(rev.number) diffAsText = diffAsText.replace("+++ ", rhs, 1) self.__diffViewer.setHTML(parse_from_memory(diffAsText, False, True)) if not self.__diffViewer.isVisible(): self.__onShowHideDiff()
def onGotoDefinition(self): """The user requested a jump to definition""" if not self.isPythonBuffer(): return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) definitions = getDefinitions(self, self._parent.getFileName()) QApplication.restoreOverrideCursor() if definitions: if len(definitions) == 1: GlobalData().mainWindow.openFile( definitions[0][0], definitions[0][1], definitions[0][2] + 1) else: if hasattr(self._parent, "importsBar"): self._parent.importsBar.showDefinitions(definitions) else: GlobalData().mainWindow.showStatusBarMessage( "Definition is not found")
def __svnStatus(self, path, update): """Called to perform svn status""" settings = self.getSettings() client = self.getSVNClient(settings) dlg = SVNStatusProgress(self, client, path, update) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) res = dlg.exec_() QApplication.restoreOverrideCursor() if res != QDialog.Accepted: logging.info("SVN status for '" + path + "' cancelled") return if len(dlg.statusList) == 0: logging.error("Error getting SVN status for '" + path + "'") return statusDialog = SVNPluginStatusDialog(dlg.statusList) statusDialog.exec_()
def onTagHelp(self): """Provides help for an item if available""" if not self.isPythonBuffer(): return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) definitions = getDefinitions(self, self._parent.getFileName()) QApplication.restoreOverrideCursor() parts = [] for definition in definitions: header = 'Type: ' + definition[3] if definition[5]: header += '\nModule: ' + definition[5] parts.append(header + '\n\n' + definition[4]) if parts: QToolTip.showText(self.mapToGlobal(self.cursorRect().bottomLeft()), '<pre>' + '\n\n'.join(parts) + '</pre>') else: GlobalData().mainWindow.showStatusBarMessage( "Definition is not found")
def __onCalltipTimer(self): """Handles the calltip update timer""" if self.__calltip: if self.absCursorPosition < self.__callPosition: self.__resetCalltip() return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) signatures = getCallSignatures(self, self._parent.getFileName()) QApplication.restoreOverrideCursor() if not signatures: self.__resetCalltip() return line = signatures[0].bracket_start[0] column = signatures[0].bracket_start[1] callPosition = self.mapToAbsPosition(line - 1, column) if callPosition != self.__callPosition: self.__resetCalltip() else: # It is still the same call, check the commas self.__calltip.highlightParameter(signatures[0].index)
def downloadAndShow(self): """Triggered when the user wants to download and see the file""" url = self.selectedText.strip() if url.lower().startswith("www."): url = "http://" + url oldTimeout = socket.getdefaulttimeout() newTimeout = 5 # Otherwise the pause is too long socket.setdefaulttimeout(newTimeout) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: response = urllib.request.urlopen(url) content = decodeURLContent(response.read()) # The content has been read sucessfully mainWindow = GlobalData().mainWindow mainWindow.editorsManager().newTabClicked(content, os.path.basename(url)) except Exception as exc: logging.error("Error downloading '" + url + "'\n" + str(exc)) QApplication.restoreOverrideCursor() socket.setdefaulttimeout(oldTimeout)
def __process(self): """Analysis process""" self.__inProgress = True mainWindow = GlobalData().mainWindow QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # return code gives really nothing. So the error in running the utility # is detected by the stderr content. # Also, there could be a mix of messages for a project. Some files # could have syntax errors - there will be messages on stderr. The # other files are fine so there will be messages on stdout stdout, stderr = self.__run() self.candidates = [] for line in stdout.splitlines(): line = line.strip() if line: # Line is like file.py:2: unused variable 'a' (60% confidence) try: startIndex = line.find(':') if startIndex < 0: continue endIndex = line.find(':', startIndex + 1) if endIndex < 0: continue fileName = line[:startIndex] startIndex = line.find(':') if startIndex < 0: continue endIndex = line.find(':', startIndex + 1) if endIndex < 0: continue fileName = os.path.abspath(line[:startIndex]) lineno = int(line[startIndex + 1:endIndex]) message = line[endIndex + 1:].strip() except: continue index = getSearchItemIndex(self.candidates, fileName) if index < 0: widget = mainWindow.getWidgetForFileName(fileName) if widget is None: uuid = '' else: uuid = widget.getUUID() newItem = ItemToSearchIn(fileName, uuid) self.candidates.append(newItem) index = len(self.candidates) - 1 self.candidates[index].addMatch('', lineno, message) self.__found += 1 self.__updateFoundLabel() QApplication.processEvents() if self.__newSearch: # Do the action only for the new search. # Redo action will handle the results on its own if self.__found == 0: if stderr: logging.error('Error running vulture for ' + self.__path + ':\n' + stderr) else: logging.info('No unused candidates found') else: mainWindow.displayFindInFiles(VultureSearchProvider.getName(), self.candidates, {'path': self.__path}) QApplication.restoreOverrideCursor() self.__infoLabel.setText('Done') self.__inProgress = False self.accept()
def doSVNAdd(plugin, client, path, recursively): """Does SVN add""" pathList = [] def notifyCallback(event, paths=pathList): if 'path' not in event: return if not event['path']: return path = event['path'] if os.path.isdir(path) and not path.endswith(os.path.sep) and \ not os.path.islink(path): path += os.path.sep action = notifyActionToString(event['action']) if action: logging.info(action + " " + path) paths.append(path) needToRestoreCursor = False try: client.callback_notify = notifyCallback if recursively: # This is a dir. It could be under VCS or not dirStatus = plugin.getLocalStatus(path) if dirStatus == plugin.NOT_UNDER_VCS: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) needToRestoreCursor = True client.add(path, recurse=True) QApplication.restoreOverrideCursor() needToRestoreCursor = False else: # Need to build the list manually statuses = plugin.getLocalStatus(path, pysvn.depth.infinity) if type(statuses) != list: logging.error("Error checking local SVN statuses for " + path) return pathsToAdd = [] for item in statuses: if item[1] == plugin.NOT_UNDER_VCS: pathsToAdd.append(item[0]) if not pathsToAdd: logging.info("No paths to add for " + path) return dlg = SVNPluginAddDialog(pathsToAdd) res = dlg.exec_() if res == QDialog.Accepted: if len(dlg.addPaths) == 0: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) needToRestoreCursor = True client.add(dlg.addPaths) QApplication.restoreOverrideCursor() needToRestoreCursor = False else: # It is a single file QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) needToRestoreCursor = True client.add(path) QApplication.restoreOverrideCursor() needToRestoreCursor = False if pathList: logging.info("Finished") except Exception as excpt: if needToRestoreCursor: QApplication.restoreOverrideCursor() logging.error(str(excpt)) for addedPath in pathList: plugin.notifyPathChanged(addedPath)
def doSVNCommit(plugin, client, path): """Performs SVN commit""" # The path could be a single file (buffer or project browser) or # a directory QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: if path.endswith(os.path.sep): # This is a directory. Path lists should be built. statuses = plugin.getLocalStatus(path, pysvn.depth.infinity) if type(statuses) != list: logging.error("Error checking local SVN statuses for " + path) QApplication.restoreOverrideCursor() return pathsToCommit = [] pathsToIgnore = [] for item in statuses: if item[1] in COMMIT_ALLOW_STATUSES: pathsToCommit.append(item) elif item[1] in IGNORE_STATUSES + [plugin.NOT_UNDER_VCS]: pathsToIgnore.append(item) if not pathsToCommit: logging.info("No paths to commit for " + path) QApplication.restoreOverrideCursor() return else: # This is a single file status = plugin.getLocalStatus(path) if status not in COMMIT_ALLOW_STATUSES: logging.error("Cannot commit " + path + " due to unexpected SVN status") QApplication.restoreOverrideCursor() return pathsToCommit = [ (path, status), ] pathsToIgnore = [] except Exception as exc: logging.error(str(exc)) QApplication.restoreOverrideCursor() return QApplication.restoreOverrideCursor() dlg = SVNPluginCommitDialog(plugin, pathsToCommit, pathsToIgnore) res = dlg.exec_() if res == QDialog.Accepted: if len(dlg.commitPaths) == 0: return dlg.commitPaths.sort() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: def getLogMessage(msg=dlg.commitMessage): return True, msg def notifyCallback(event): if event['path']: action = notifyActionToString(event['action']) if action: logging.info("Commit: " + action + " " + event['path']) QApplication.processEvents() return client.callback_get_log_message = getLogMessage client.callback_notify = notifyCallback revision = client.checkin(dlg.commitPaths, log_message=dlg.commitMessage, recurse=False) logging.info("Committed revision " + str(revision.number)) for path in dlg.commitPaths: plugin.notifyPathChanged(path) except pysvn.ClientError as exc: message = exc.args[0] logging.error(message) except Exception as exc: logging.error(str(exc)) except: logging.error("Unknown error") QApplication.restoreOverrideCursor()
def __process(self): """Search process""" self.__updateHistory() self.__inProgress = True numberOfMatches = 0 self.searchResults = [] self.searchRegexp = None # Form the regexp to search regexpText = self.findCombo.currentText() if not self.regexpCheckBox.isChecked(): regexpText = re.escape(regexpText) if self.wordCheckBox.isChecked(): regexpText = "\\b%s\\b" % regexpText flags = re.UNICODE if not self.caseCheckBox.isChecked(): flags |= re.IGNORECASE try: self.searchRegexp = re.compile(regexpText, flags) except Exception as exc: logging.error("Invalid search expression: %s", str(exc)) self.close() return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.fileLabel.setPath('Building list of files to search in...') QApplication.processEvents() try: files = self.__buildFilesList() except Exception as exc: QApplication.restoreOverrideCursor() if 'Cancel request' not in str(exc): logging.error(str(exc)) self.close() return QApplication.restoreOverrideCursor() QApplication.processEvents() if not files: self.fileLabel.setPath('No files to search in') return self.progressBar.setRange(0, len(files)) index = 1 for item in files: if self.__cancelRequest: self.__inProgress = False self.close() return self.fileLabel.setPath('Matches: ' + str(numberOfMatches) + ' Processing: ' + item.fileName) item.search(self.searchRegexp) found = len(item.matches) if found > 0: numberOfMatches += found self.searchResults.append(item) self.progressBar.setValue(index) index += 1 QApplication.processEvents() if numberOfMatches > 0 or self.__newSearch == False: # If it is redo then close the dialog anyway self.close() else: msg = 'No matches in ' + str(len(files)) + ' file' if len(files) > 1: msg += 's' self.fileLabel.setPath(msg) self.__inProgress = False
def __process(self): """Analysis process""" self.__inProgress = True mainWindow = GlobalData().mainWindow editorsManager = mainWindow.editorsManagerWidget.editorsManager # True - only project files modified = editorsManager.getModifiedList(True) if modified: modNames = [modItem[0] for modItem in modified] label = "File" if len(modified) >= 2: label += "s" label += ": " logging.warning("The analisys is performed for the content " "of saved files. The unsaved modifications will " "not be taken into account. " + label + ", ".join(modNames)) self.__updateFoundLabel() self.__progressBar.setRange(0, len(self.__srcModel.rootItem.childItems)) QApplication.processEvents() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) count = 0 candidates = [] for treeItem in self.__srcModel.rootItem.childItems: if self.__cancelRequest: break name = str(treeItem.data(0)).split('(')[0] path = os.path.realpath(treeItem.getPath()) lineNumber = int(treeItem.data(2)) pos = treeItem.sourceObj.pos count += 1 self.__progressBar.setValue(count) self.__infoLabel.setText(self.__formInfoLabel(name)) QApplication.processEvents() # Analyze the name found = False definitions = getOccurrences(None, path, lineNumber, pos) if len(definitions) == 1: found = True index = getSearchItemIndex(candidates, path) if index < 0: widget = mainWindow.getWidgetForFileName(path) if widget is None: uuid = "" else: uuid = widget.getUUID() newItem = ItemToSearchIn(path, uuid) candidates.append(newItem) index = len(candidates) - 1 candidates[index].addMatch(name, lineNumber) if found: self.__found += 1 self.__updateFoundLabel() QApplication.processEvents() if self.__found == 0: # The analysis could be interrupted if not self.__cancelRequest: logging.info("No unused candidates found") else: mainWindow.displayFindInFiles("", candidates) QApplication.restoreOverrideCursor() self.__infoLabel.setText('Done') self.__inProgress = False self.accept()