diff -r 1ae73306422a -r 725eaca7bc4b RadonMetrics/MaintainabilityIndexDialog.py --- a/RadonMetrics/MaintainabilityIndexDialog.py Mon Sep 19 17:43:37 2022 +0200 +++ b/RadonMetrics/MaintainabilityIndexDialog.py Mon Sep 19 17:54:33 2022 +0200 @@ -13,8 +13,12 @@ from PyQt6.QtCore import pyqtSlot, Qt, QTimer, QLocale from PyQt6.QtGui import QColor from PyQt6.QtWidgets import ( - QDialog, QDialogButtonBox, QAbstractButton, QHeaderView, QTreeWidgetItem, - QApplication + QDialog, + QDialogButtonBox, + QAbstractButton, + QHeaderView, + QTreeWidgetItem, + QApplication, ) from .Ui_MaintainabilityIndexDialog import Ui_MaintainabilityIndexDialog @@ -28,12 +32,13 @@ """ Class implementing a dialog to show maintainability indexes. """ + FilePathRole = Qt.ItemDataRole.UserRole + 1 - + def __init__(self, radonService, parent=None): """ Constructor - + @param radonService reference to the service @type RadonMetricsPlugin @param parent reference to the parent widget @@ -42,44 +47,44 @@ super().__init__(parent) self.setupUi(self) self.setWindowFlags(Qt.WindowType.Window) - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setDefault(True) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(True) + self.resultList.headerItem().setText(self.resultList.columnCount(), "") - + self.radonService = radonService - self.radonService.maintainabilityIndexDone.connect( - self.__processResult) + self.radonService.maintainabilityIndexDone.connect(self.__processResult) self.radonService.error.connect(self.__processError) self.radonService.batchFinished.connect(self.__batchFinished) - + self.cancelled = False - + self.__project = ericApp().getObject("Project") self.__locale = QLocale() self.__finished = True self.__errorItem = None - + self.__fileList = [] self.filterFrame.setVisible(False) - - self.explanationLabel.setText(self.tr( - "<table>" - "<tr><td><b>Rank</b></td><td><b>MI Score</b></td>" - "<td><b>Maintainability</b></td></tr>" - "<tr><td><b>A</b></td><td>100 - 20</td><td>very high</td></tr>" - "<tr><td><b>B</b></td><td>19 - 10</td><td>medium</td></tr>" - "<tr><td><b>C</b></td><td>9 - 0</td><td>extremely low</td></tr>" - "</table>" - )) - + + self.explanationLabel.setText( + self.tr( + "<table>" + "<tr><td><b>Rank</b></td><td><b>MI Score</b></td>" + "<td><b>Maintainability</b></td></tr>" + "<tr><td><b>A</b></td><td>100 - 20</td><td>very high</td></tr>" + "<tr><td><b>B</b></td><td>19 - 10</td><td>medium</td></tr>" + "<tr><td><b>C</b></td><td>9 - 0</td><td>extremely low</td></tr>" + "</table>" + ) + ) + try: usesDarkPalette = ericApp().usesDarkPalette() except AttributeError: from PyQt6.QtGui import QPalette + palette = ericApp().palette() lightness = palette.color(QPalette.Window).lightness() usesDarkPalette = lightness <= 128 @@ -95,19 +100,20 @@ "B": QColor("#ffff00"), "C": QColor("#ff0000"), } - + def __resizeResultColumns(self): """ Private method to resize the list columns. """ self.resultList.header().resizeSections( - QHeaderView.ResizeMode.ResizeMode.ResizeToContents) + QHeaderView.ResizeMode.ResizeMode.ResizeToContents + ) self.resultList.header().setStretchLastSection(True) - + def __createResultItem(self, filename, values): """ Private slot to create a new item in the result list. - + @param filename name of the file @type str @param values values to be displayed @@ -115,8 +121,9 @@ """ data = [self.__project.getRelativePath(filename)] try: - data.append("{0:>6}".format( - self.__locale.toString(float(values["mi"]), "f", 2))) + data.append( + "{0:>6}".format(self.__locale.toString(float(values["mi"]), "f", 2)) + ) except ValueError: data.append(values["mi"]) data.append(values["rank"]) @@ -126,36 +133,34 @@ if values["rank"] in self.__rankColors: itm.setBackground(2, self.__rankColors[values["rank"]]) itm.setData(0, self.FilePathRole, filename) - + if values["rank"] in self.__summary: self.__summary[values["rank"]] += 1 - + def __createErrorItem(self, filename, message): """ Private slot to create a new error item in the result list. - + @param filename name of the file @type str @param message error message @type str """ if self.__errorItem is None: - self.__errorItem = QTreeWidgetItem(self.resultList, [ - self.tr("Errors")]) + self.__errorItem = QTreeWidgetItem(self.resultList, [self.tr("Errors")]) self.__errorItem.setExpanded(True) self.__errorItem.setForeground(0, Qt.GlobalColor.red) - - msg = "{0} ({1})".format(self.__project.getRelativePath(filename), - message) + + msg = "{0} ({1})".format(self.__project.getRelativePath(filename), message) if not self.resultList.findItems(msg, Qt.MatchFlag.MatchExactly): itm = QTreeWidgetItem(self.__errorItem, [msg]) itm.setForeground(0, Qt.GlobalColor.red) itm.setFirstColumnSpanned(True) - + def prepare(self, fileList, project): """ Public method to prepare the dialog with a list of filenames. - + @param fileList list of filenames @type list of str @param project reference to the project object @@ -163,26 +168,22 @@ """ self.__fileList = fileList[:] self.__project = project - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setDefault(True) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setDefault(True) + self.filterFrame.setVisible(True) - - self.__data = self.__project.getData( - "OTHERTOOLSPARMS", "RadonCodeMetrics") + + self.__data = self.__project.getData("OTHERTOOLSPARMS", "RadonCodeMetrics") if self.__data is None or "ExcludeFiles" not in self.__data: self.__data = {"ExcludeFiles": ""} self.excludeFilesEdit.setText(self.__data["ExcludeFiles"]) - + def start(self, fn): """ Public slot to start the maintainability index determination. - + @param fn file or list of files or directory to show the maintainability index for @type str or list of str @@ -192,23 +193,19 @@ self.summaryLabel.clear() self.cancelled = False QApplication.processEvents() - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setDefault(True) + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(True) QApplication.processEvents() - + if isinstance(fn, list): self.files = fn elif os.path.isdir(fn): self.files = [] extensions = set(Preferences.getPython("Python3Extensions")) for ext in extensions: - self.files.extend( - Utilities.direntries(fn, True, '*{0}'.format(ext), 0)) + self.files.extend(Utilities.direntries(fn, True, "*{0}".format(ext), 0)) else: self.files = [fn] self.files.sort() @@ -216,22 +213,22 @@ for f in self.files[:]: if not os.path.exists(f): self.files.remove(f) - + self.__summary = { "A": 0, "B": 0, "C": 0, } - + if len(self.files) > 0: # disable updates of the list for speed self.resultList.setUpdatesEnabled(False) self.resultList.setSortingEnabled(False) - + self.checkProgress.setMaximum(len(self.files)) self.checkProgress.setVisible(len(self.files) > 1) QApplication.processEvents() - + # now go through all the files self.progress = 0 if len(self.files) == 1: @@ -240,14 +237,14 @@ else: self.__batch = True self.maintainabilityIndexBatch() - - def maintainabilityIndex(self, codestring=''): + + def maintainabilityIndex(self, codestring=""): """ Public method to start a maintainability index calculation for one Python file. - + The results are reported to the __processResult slot. - + @param codestring optional sourcestring @type str """ @@ -256,14 +253,14 @@ self.checkProgress.setValue(1) self.__finish() return - + self.filename = self.files.pop(0) self.checkProgress.setValue(self.progress) QApplication.processEvents() - + if self.cancelled: return - + try: self.source = Utilities.readEncodedFile(self.filename)[0] self.source = Utilities.normalizeCode(self.source) @@ -275,42 +272,41 @@ return self.__finished = False - self.radonService.maintainabilityIndex( - None, self.filename, self.source) + self.radonService.maintainabilityIndex(None, self.filename, self.source) def maintainabilityIndexBatch(self): """ Public method to start a maintainability index calculation batch job. - + The results are reported to the __processResult slot. """ self.__lastFileItem = None - + argumentsList = [] for progress, filename in enumerate(self.files, start=1): self.checkProgress.setValue(progress) QApplication.processEvents() - + try: source = Utilities.readEncodedFile(filename)[0] source = Utilities.normalizeCode(source) except (UnicodeError, OSError) as msg: self.__createErrorItem(filename, str(msg).rstrip()) continue - + argumentsList.append((filename, source)) - + # reset the progress bar to the checked files self.checkProgress.setValue(self.progress) QApplication.processEvents() - + self.__finished = False self.radonService.maintainabilityIndexBatch(argumentsList) - + def __batchFinished(self, type_): """ Private slot handling the completion of a batch job. - + @param type_ type of the calculated metrics @type str, one of ["raw", "mi", "cc"] """ @@ -318,11 +314,11 @@ self.checkProgress.setMaximum(1) self.checkProgress.setValue(1) self.__finish() - + def __processError(self, type_, fn, msg): """ Private slot to process an error indication from the service. - + @param type_ type of the calculated metrics @type str, one of ["raw", "mi", "cc"] @param fn filename of the file @@ -332,12 +328,12 @@ """ if type_ == "mi": self.__createErrorItem(fn, msg) - + def __processResult(self, fn, result): """ Private slot called after perfoming a maintainability index calculation on one file. - + @param fn filename of the file @type str @param result result dict @@ -345,124 +341,125 @@ """ if self.__finished: return - + # Check if it's the requested file, otherwise ignore signal if not # in batch mode if not self.__batch and fn != self.filename: return - + QApplication.processEvents() - + if "error" in result: self.__createErrorItem(fn, result["error"]) else: self.__createResultItem(fn, result) - + self.progress += 1 - + self.checkProgress.setValue(self.progress) QApplication.processEvents() - + if not self.__batch: self.maintainabilityIndex() - + def __finish(self): """ Private slot called when the action or the user pressed the button. """ if not self.__finished: self.__finished = True - + # reenable updates of the list self.resultList.setSortingEnabled(True) self.resultList.sortItems(0, Qt.SortOrder.AscendingOrder) self.resultList.setUpdatesEnabled(True) - + self.cancelled = True - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setDefault(True) - + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled( + True + ) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled( + False + ) + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setDefault( + True + ) + self.resultList.header().resizeSections( - QHeaderView.ResizeMode.ResizeToContents) + QHeaderView.ResizeMode.ResizeToContents + ) self.resultList.header().setStretchLastSection(True) self.resultList.header().setSectionResizeMode( - QHeaderView.ResizeMode.Interactive) - - self.summaryLabel.setText(self.tr( - "<table>" - "<tr><td colspan=2><b>Summary:</b></td></tr>" - "<tr><td><b>A</b></td><td align='right'>{0} files</td></tr>" - "<tr><td><b>B</b></td><td align='right'>{1} files</td></tr>" - "<tr><td><b>C</b></td><td align='right'>{2} files</td></tr>" - "</table>" - ).format(self.__locale.toString(self.__summary["A"]), - self.__locale.toString(self.__summary["B"]), - self.__locale.toString(self.__summary["C"])) + QHeaderView.ResizeMode.Interactive ) - + + self.summaryLabel.setText( + self.tr( + "<table>" + "<tr><td colspan=2><b>Summary:</b></td></tr>" + "<tr><td><b>A</b></td><td align='right'>{0} files</td></tr>" + "<tr><td><b>B</b></td><td align='right'>{1} files</td></tr>" + "<tr><td><b>C</b></td><td align='right'>{2} files</td></tr>" + "</table>" + ).format( + self.__locale.toString(self.__summary["A"]), + self.__locale.toString(self.__summary["B"]), + self.__locale.toString(self.__summary["C"]), + ) + ) + self.checkProgress.setVisible(False) - + @pyqtSlot(QAbstractButton) def on_buttonBox_clicked(self, button): """ Private slot called by a button of the button box clicked. - + @param button button that was clicked @type QAbstractButton """ - if button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Close - ): + if button == self.buttonBox.button(QDialogButtonBox.StandardButton.Close): self.close() - elif button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel - ): + elif button == self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel): if self.__batch: self.radonService.cancelMaintainabilityIndexBatch() QTimer.singleShot(1000, self.__finish) else: self.__finish() - + @pyqtSlot() def on_startButton_clicked(self): """ Private slot to start a maintainability index run. """ fileList = self.__fileList[:] - + filterString = self.excludeFilesEdit.text() if ( - "ExcludeFiles" not in self.__data or - filterString != self.__data["ExcludeFiles"] + "ExcludeFiles" not in self.__data + or filterString != self.__data["ExcludeFiles"] ): self.__data["ExcludeFiles"] = filterString - self.__project.setData( - "OTHERTOOLSPARMS", "RadonCodeMetrics", self.__data) - filterList = [f.strip() for f in filterString.split(",") - if f.strip()] + self.__project.setData("OTHERTOOLSPARMS", "RadonCodeMetrics", self.__data) + filterList = [f.strip() for f in filterString.split(",") if f.strip()] if filterList: for fileFilter in filterList: - fileList = [f for f in fileList - if not fnmatch.fnmatch(f, fileFilter)] - + fileList = [f for f in fileList if not fnmatch.fnmatch(f, fileFilter)] + self.start(fileList) - + def clear(self): """ Public method to clear all results. """ self.resultList.clear() self.summaryLabel.clear() - + @pyqtSlot(QTreeWidgetItem, int) def on_resultList_itemActivated(self, item, column): """ Private slot to handle the activation of a result item. - + @param item reference to the activated item @type QTreeWidgetItem @param column activated column