def processCommandLineArgs(args): """Checks what is in the command line""" # I cannot import it at the top because the fileutils want # to use the pixmap cache which needs the application to be # created, so the import is deferred from utils.fileutils import (isFileOpenable, getFileProperties, isCDMProjectMime) if not args: return None # Check that all the files exist for fName in args: if not os.path.exists(fName): raise Exception("Cannot open file: " + fName) if not os.path.isfile(fName): raise Exception("The " + fName + " is not a file") if not isFileOpenable(fName): raise Exception("The file " + fName + " could not be opened") if len(args) == 1: mime, _, _ = getFileProperties(args[0]) if isCDMProjectMime(mime): return args[0] return None # There are many files, check that they are python only for fName in args: mime, _, _ = getFileProperties(fName) if isCDMProjectMime(mime): raise Exception("Codimension project file (" + fName + ") must not come " "together with other files") return None
def processCommandLineArgs(self): """Checks what is in the command line""" # I cannot import it at the top because the fileutils want # to use the pixmap cache which needs the application to be # created, so the import is deferred from utils.fileutils import getFileProperties, isCDMProjectMime if self.__args: totalArgs = len(self.__args) goodArgs = [] for fName in self.__args: if self.isOpenable(fName): goodArgs.append(fName) self.__args = goodArgs if totalArgs == 1 and len(self.__args) == 1: mime, _, _ = getFileProperties(self.__args[0]) if isCDMProjectMime(mime): return self.__args[0] # Check that the is no project file because it can only come alone for fName in self.__args: mime, _, _ = getFileProperties(fName) if isCDMProjectMime(mime): raise Exception('A Codimension project file (' + fName + ') must not come ' 'together with other files') return None
def updateLinkStatus(self, path): """Called to update the status to/from broken link""" if not self.isLink: return self.fileType, self.icon, _ = getFileProperties(path) if 'broken-symlink' in self.fileType: self.toolTip = self.__brokenLinkTooltip(path) return self.toolTip = self.__linkTooltip(path) self.icon = getIcon('filelink.png') self.fileType, _, _ = getFileProperties(os.path.realpath(path))
def onFileUpdated(self, fileName, uuid): """Triggered when the file is updated""" del uuid # unused argument mime, icon, _ = getFileProperties(fileName) if isPythonMime(mime): path = os.path.realpath(fileName) info = GlobalData().briefModinfoCache.get(path) if info.isOK: icon = getIcon('filepython.png') else: icon = getIcon('filepythonbroken.png') # For all root items for treeItem in self.model().sourceModel().rootItem.childItems: self.__walkTreeAndUpdate(treeItem, path, mime, icon, info) elif isCDMProjectMime(mime): path = os.path.realpath(fileName) # For all root items for treeItem in self.model().sourceModel().rootItem.childItems: self.__walkTreeAndUpdate(treeItem, path, mime, None, None) elif fileName.endswith(".cgi"): path = os.path.realpath(fileName) # For all root items for treeItem in self.model().sourceModel().rootItem.childItems: self.__walkTreeAndUpdate(treeItem, path, mime, icon, None)
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 _onAnchorClicked(self, link): """Overwritten URL click handler""" if link == 'javascript:history.back()' or link == 'history.back()': if self.__parentWidget.viewerHistory.backAvailable(): self.__parentWidget.onBack() else: logging.warning('No step back avaialable') return if link == 'javascript:history.forward()' or link == 'history.forward()': if self.__parentWidget.viewerHistory.forwardAvailable(): self.__parentWidget.onForward() else: logging.warning('No step forward available') return fileName, anchorOrLine = self._resolveLink(link) if fileName: mime, _, _ = getFileProperties(fileName) if isMarkdownMime(mime): self.__parentWidget.updateCurrentHistoryPosition() self.__parentWidget.setFileName(fileName) else: # It is a resolved link to some kind of non-markdown file GlobalData().mainWindow.openFile(fileName, anchorOrLine)
def showReport(self, regexp, results): """Shows the find in files results""" self.__clear() self.__noneLabel.hide() self.__reportRegexp = regexp self.__reportResults = results # Add the complete information totalMatched = 0 for item in results: matched = len(item.matches) totalMatched += matched if matched == 1: matchText = " (1 match)" else: matchText = " (" + str(matched) + " matches)" columns = [item.fileName, '', matchText] fileItem = MatchTableFileItem(columns, item.bufferUUID) _, icon, _ = getFileProperties(item.fileName) fileItem.setIcon(0, icon) if item.tooltip != "": fileItem.setToolTip(0, item.tooltip) self.__resultsTree.addTopLevelItem(fileItem) # Matches for match in item.matches: columns = [str(match.line), match.text] matchItem = MatchTableItem(columns, match.tooltip) fileItem.addChild(matchItem) fileItem.setExpanded(True) # Update the header with the total number of matches headerLabels = ["File name / line (total files: " + str(len(results)) + ")", '', "Text (total matches: " + str(totalMatched) + ")"] self.__resultsTree.setHeaderLabels(headerLabels) # Resizing the table self.__resultsTree.header().resizeSections( QHeaderView.ResizeToContents) self.__resultsTree.header().setSectionResizeMode(1, QHeaderView.Fixed) self.__resultsTree.header().resizeSection(1, 30) # Show the complete information self.__resultsTree.show() self.__resultsTree.buildCache() self.__reportShown = True self.__updateButtonsStatus() # Connect the buffer change signal if not connected yet if not self.__bufferChangeconnected: self.__bufferChangeconnected = True mainWindow = GlobalData().mainWindow editorsManager = mainWindow.editorsManagerWidget.editorsManager editorsManager.sigBufferModified.connect( self.__resultsTree.onBufferModified)
def onFileTypeChanged(self, fileName, uuid, newMime): """Triggered when the file type is changed""" del uuid # unused argument del newMime # unused argument mime, icon, _ = getFileProperties(fileName) path = os.path.realpath(fileName) for treeItem in self.model().sourceModel().rootItem.childItems: self.__walkTreeAndUpdate(treeItem, path, mime, icon, None)
def __init__(self, parent, path): path = str(path) TreeViewItem.__init__(self, parent, os.path.basename(path)) self.itemType = FileItemType self.parsingErrors = False # Used for python files only self.isLink = False self.fileType, self.icon, _ = getFileProperties(path) if self.fileType is None: if self.icon is None: self.icon = getIcon('filemisc.png') return if 'broken-symlink' in self.fileType: self.isLink = True self.toolTip = self.__brokenLinkTooltip(path) return if os.path.islink(path): self.isLink = True self.toolTip = self.__linkTooltip(path) self.icon = getIcon('filelink.png') self.fileType, _, _ = getFileProperties(os.path.realpath(path)) return # Fine corrections for some file types if isPythonMime(self.fileType): self.populated = False self.lazyPopulation = True return if isCDMProjectMime(self.fileType): # Get the project properties try: self.toolTip = getProjectFileTooltip(path) except: # cannot get project properties self.toolTip = 'Broken project file' return
def __populateModel(self): """Populates the project browser model""" self.clear() project = self.globalData.project cache = self.globalData.briefModinfoCache for fname in project.filesList: mime, _, _ = getFileProperties(fname) if isPythonMime(mime): info = cache.get(fname) for classObj in info.classes: item = TreeViewClassItem(self.rootItem, classObj) item.appendData([basename(fname), classObj.line]) item.setPath(fname) self.rootItem.appendChild(item)
def __openFile(self): """Handles 'open' file menu item""" self.__fileContextItem.updateIconAndTooltip() fName = self.__fileContextItem.getFilename() if not self.__fileContextItem.isValid(): logging.warning("Cannot open " + fName) return mime, _, _ = getFileProperties(fName) if isImageViewable(mime): GlobalData().mainWindow.openPixmapFile(fName) else: GlobalData().mainWindow.openFile(fName, -1)
def __populateFromOpened(self): """Populates the name dialog from the opened files""" mainWindow = GlobalData().mainWindow editorsManager = mainWindow.editorsManagerWidget.editorsManager showTooltips = Settings()['findFileTooltips'] for record in editorsManager.getTextEditors(): # uuid = record[0] fname = record[1] widget = record[2] mime, icon, _ = getFileProperties(fname) tooltip = "" if showTooltips and isPythonMime(mime): content = widget.getEditor().text info = getBriefModuleInfoFromMemory(content) if info.docstring is not None: tooltip = info.docstring.text newItem = FileItem(self.rootItem, icon, fname, tooltip) self.rootItem.appendChild(newItem) self.count += 1
def populate(self, results): """Populates data in the tree widget""" self.clear() self.timestampLabel.setText(getLocaleDateTime()) # Add the complete information totalMatched = 0 for item in results: matched = len(item.matches) totalMatched += matched if matched == 1: matchText = " (1 match)" else: matchText = " (" + str(matched) + " matches)" columns = [item.fileName, '', matchText] fileItem = MatchTableFileItem(columns, item.bufferUUID) _, icon, _ = getFileProperties(item.fileName) fileItem.setIcon(0, icon) if item.tooltip != "": fileItem.setToolTip(0, item.tooltip) self.resultsTree.addTopLevelItem(fileItem) # Matches for match in item.matches: columns = [str(match.line), match.text] matchItem = MatchTableItem(columns, match.tooltip) fileItem.addChild(matchItem) fileItem.setExpanded(True) # Update the header with the total number of matches headerLabels = ["File name / line (total files: " + str(len(results)) + ")", '', "Text (total matches: " + str(totalMatched) + ")"] self.resultsTree.setHeaderLabels(headerLabels) # Resizing the table self.resultsTree.header().resizeSections(QHeaderView.ResizeToContents) self.resultsTree.header().setSectionResizeMode(1, QHeaderView.Fixed) self.resultsTree.header().resizeSection(1, 30) self.resultsTree.buildCache()
def openItem(item): """Handles the case when an item is activated""" if item.itemType in [ GlobalsItemType, ImportsItemType, FunctionsItemType, ClassesItemType, StaticAttributesItemType, InstanceAttributesItemType, DirectoryItemType, SysPathItemType ]: return if item.itemType == FileItemType: if item.fileType is None: return if 'broken-symlink' in item.fileType: return itemPath = item.getPath() if not os.path.exists(itemPath): logging.error("Cannot open " + itemPath) return if os.path.islink(itemPath): # Convert it to the real path and the decide what to do itemPath = os.path.realpath(itemPath) # The type may differ... itemMime, _, _ = getFileProperties(itemPath) else: # The intermediate directory could be a link, so use the real # path itemPath = os.path.realpath(itemPath) itemMime = item.fileType GlobalData().mainWindow.openFileByType(itemMime, itemPath, -1) return if item.itemType in [ CodingItemType, ImportItemType, FunctionItemType, ClassItemType, DecoratorItemType, AttributeItemType, GlobalItemType, ImportWhatItemType ]: GlobalData().mainWindow.openFile(os.path.realpath(item.getPath()), item.sourceObj.line)
def __populateFromProject(self): """Populates find name dialog from the project files""" mainWindow = GlobalData().mainWindow showTooltips = Settings()['findFileTooltips'] for fname in GlobalData().project.filesList: if fname.endswith(os.path.sep): continue mime, icon, _ = getFileProperties(fname) tooltip = "" if showTooltips and isPythonMime(mime): widget = mainWindow.getWidgetForFileName(fname) if widget is None: info = GlobalData().briefModinfoCache.get(fname) else: content = widget.getEditor().text info = getBriefModuleInfoFromMemory(content) if info.docstring is not None: tooltip = info.docstring.text newItem = FileItem(self.rootItem, icon, fname, tooltip) self.rootItem.appendChild(newItem) self.count += 1
def __markOK(self): """Mark the file as OK""" self.__isValid = True fileName = self.getFilename() mime, icon, _ = getFileProperties(fileName) if isPythonMime(mime): # The tooltip could be the file docstring info = GlobalData().briefModinfoCache.get(fileName) if info.docstring and Settings()['recentTooltips']: self.setToolTip(1, info.docstring.text) else: self.setToolTip(1, "") if info.isOK: self.setIcon(0, getIcon('filepython.png')) else: self.setIcon(0, getIcon('filepythonbroken.png')) self.setToolTip(0, "") elif isCDMProjectMime(mime): # Get the project properties try: self.setToolTip(0, "") tooltip = getProjectFileTooltip(fileName) if Settings()['recentTooltips']: self.setToolTip(1, tooltip) else: self.setToolTip(1, "") self.setText(0, "") except: # cannot get project properties. Mark broken. self.__isValid = False self.setToolTip(0, 'Broken project file') self.setToolTip(1, 'Broken project file') self.setIcon(0, icon) else: # Get the other file type icon self.setIcon(0, icon) self.setToolTip(2, self.getFilename())
def __createLayout(self, action, title, files): """Creates the dialog layout""" self.resize(400, 300) self.setSizeGripEnabled(True) # Top level layout layout = QVBoxLayout(self) # Pixmap and the message topLayout = QHBoxLayout() pixmap = QLabel() pixmap.setPixmap(getPixmap('warning.png')) topLayout.addWidget(pixmap) hSpacer = QWidget() hSpacer.setFixedSize(15, 15) topLayout.addWidget(hSpacer) message = QLabel("All the project files must be " "saved before start debugging") message.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) message.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) message.setWordWrap(True) topLayout.addWidget(message) layout.addLayout(topLayout) vSpacer = QWidget() vSpacer.setFixedSize(15, 15) layout.addWidget(vSpacer) layout.addWidget(QLabel(title + ":")) filesList = QTreeWidget() filesList.setRootIsDecorated(False) filesList.setAlternatingRowColors(True) filesList.setUniformRowHeights(True) filesList.setItemsExpandable(False) filesList.setItemDelegate(NoOutlineHeightDelegate(4)) filesList.setSelectionMode(QAbstractItemView.NoSelection) filesList.setHeaderHidden(True) for item in files: fileName = item[0] fileItem = QTreeWidgetItem([fileName]) fileType, icon, _ = getFileProperties(fileName) fileItem.setIcon(0, icon) if isPythonMime(fileType): info = GlobalData().briefModinfoCache.get(fileName) fileItem.setToolTip( 0, info.docstring.text if info.docstring else '') filesList.addTopLevelItem(fileItem) layout.addWidget(filesList) # Buttons at the bottom buttonBox = QDialogButtonBox() buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel) continueButton = buttonBox.addButton(action, QDialogButtonBox.ActionRole) continueButton.setDefault(True) layout.addWidget(buttonBox) continueButton.clicked.connect(self.accept) buttonBox.rejected.connect(self.close) continueButton.setFocus()