def findMdiChild(self, fileName): canonicalFilePath = QtCore.QFileInfo(fileName).canonicalFilePath() for window in self.mdiarea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None
def mqtt_connection(request): broker_location = os.path.join( request.config.rootdir, "internals/paho.mqtt.testing/interoperability/startbroker.py", ) broker_process = QtCore.QProcess() python_path = sys.executable arguments = [broker_location] configuration = "localhost_testing.conf" broker_dir = QtCore.QFileInfo(broker_location).absoluteDir() if broker_dir.exists(configuration): arguments += [ "-c", QtCore.QDir.toNativeSeparators(broker_dir.absoluteFilePath(configuration)), ] broker_process.setWorkingDirectory(broker_dir.absolutePath()) broker_process.start(python_path, arguments) if not broker_process.waitForStarted(): raise Exception("Could not start MQTT test broker.") max_tries = 6 for try_counter in range(max_tries): socket = QtNetwork.QTcpSocket() socket.connectToHost("localhost", 1883) if socket.waitForConnected(3000): yield "localhost" break loop = QtCore.QEventLoop() QtCore.QTimer.singleShot(5000, loop.quit) loop.exec_() print("Could not launch MQTT test broker.")
def qfileicon(self, path): """ desc: Gets an filetype icon for a file. arguments: path: The full path to the file. The file must exist. returns: type: QIcon """ try: import fileinspector except ImportError: return QtWidgets.QFileIconProvider().icon(QtCore.QFileInfo(path)) filetype = fileinspector.determine_type(path, output='xdg') if filetype is None: filetype = u'text-x-generic' category = fileinspector.determine_category(filetype) if category is None: fallback = u'text-x-generic' else: fallback = category + u'-x-generic' return QtGui.QIcon.fromTheme(filetype, fallback=QtGui.QIcon.fromTheme(fallback))
def save_current(self, path=None): """ Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file. """ try: if not path and not self._current.file.path: path, filter = QtWidgets.QFileDialog.getSaveFileName( self, _('Choose destination path')) if not path: return False old_path = self._current.file.path code_edit = self._current self._save_editor(code_edit, path) path = code_edit.file.path # path (and icon) may have changed if path and old_path != path: self._ensure_unique_name(code_edit, code_edit.file.name) self.setTabText(self.currentIndex(), code_edit._tab_name) ext = os.path.splitext(path)[1] old_ext = os.path.splitext(old_path)[1] if ext != old_ext or not old_path: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(code_edit.file.path)) self.setTabIcon(self.currentIndex(), icon) return True except AttributeError: # not an editor widget pass return False
def update_actions(self): """ Updates the list of actions. """ self.clear() self.recent_files_actions[:] = [] for file in self.manager.get_recent_files(): action = QtWidgets.QAction(self) action.setText(os.path.split(file)[1]) action.setToolTip(file) action.setStatusTip(file) action.setData(file) action.setIcon(self.icon_provider.icon(QtCore.QFileInfo(file))) action.triggered.connect(self._on_action_triggered) self.addAction(action) self.recent_files_actions.append(action) self.addSeparator() action_clear = QtWidgets.QAction(_('Clear list'), self) action_clear.triggered.connect(self.clear_recent_files) if isinstance(self.clear_icon, QtGui.QIcon): action_clear.setIcon(self.clear_icon) elif self.clear_icon: theme = '' if len(self.clear_icon) == 2: theme, path = self.clear_icon else: path = self.clear_icon icons.icon(theme, path, 'fa.times-circle') self.addAction(action_clear)
def accept(self): path = self.selectedFiles()[0] stats = QtCore.QFileInfo(path) if stats.isDir(): self.setDirectory(path) return if not stats.exists(): return loadProgram(path) self.hide()
def get_icon(self, path: (str, Path)): "Path -> QIcon" fileinfo = QtCore.QFileInfo(str(path)) dat = self.file_ico_prov.icon(fileinfo) if fileinfo.isHidden(): pmap = QtGui.QPixmap(*TRANSP_ICON_SIZE) pmap.fill(Qt.transparent) painter = QtGui.QPainter(pmap) painter.setOpacity(0.5) dat.paint(painter, 0, 0, *TRANSP_ICON_SIZE) painter.end() dat = QtGui.QIcon(pmap) return dat
def updateFileMenu(self): current = self.filename menu = self.menus.recentFiles menu.clear() files = [ f for f in self.recentFiles if f != current and self.exists(f) ] for i, f in enumerate(files): icon = utils.newIcon('labels') action = QtWidgets.QAction( icon, '&%d %s' % (i + 1, QtCore.QFileInfo(f).fileName()), self) action.triggered.connect(functools.partial(self.loadRecent, f)) menu.addAction(action)
def list_network_locations(): "List (name, path) locations in Network Shortcuts folder on Windows" HOME = QtCore.QStandardPaths.HomeLocation user_folder = QtCore.QStandardPaths.writableLocation(HOME) network_shortcuts = user_folder + "/AppData/Roaming/Microsoft/Windows/Network Shortcuts" for i in Path(network_shortcuts).iterdir(): if not i.is_dir(): continue link = Path(i) / "target.lnk" if not link.exists(): continue path = QtCore.QFileInfo(str(link)).symLinkTarget() if path: # `symLinkTarget` doesn't read e.g. FTP links yield i.name, path
def addFile(self, fileName, size, mode, state): if fileName: abs = fileName if fileName[0] != ':': abs = QtCore.QFileInfo(fileName).absoluteFilePath() al = abs.lower() if (al.endswith(".svg") or al.endswith(".svgz") or al.endswith(".svg.gz")): renderer = QtSvg.QSvgRenderer(abs) if renderer.isValid(): self._svgFiles[(mode, state)] = abs else: pm = QtGui.QPixmap(abs) if pm is not None: self.addPixmap(pm, mode, state)
def updateRecentFile(self): menu = self.actions.recent_files menu.clear() recentFiles = self.settings.value("recent_files", []) if not recentFiles: recentFiles = [] files = [f for f in recentFiles if osp.exists(f)] for i, f in enumerate(files): icon = util.newIcon("File") action = QtWidgets.QAction( icon, "&【%d】 %s" % (i + 1, QtCore.QFileInfo(f).fileName()), self) action.triggered.connect(partial(self.loadImage, f, True)) menu.addAction(action) if len(files) == 0: menu.addAction("无近期文件") self.settings.setValue("recent_files", files)
def getFileInfo(self, filename): ''' return general information of the given [filename], like it's size ''' f = QtCore.QFileInfo(filename) size = f.size() size_type = ['Byte', 'kB', 'MB', 'GB', 'TB', 'PB'] size_index = 0 while size > 1024: size /= 1024.0 size_index += 1 size = "%.3g %s" % (round(size, 3), size_type[size_index]) n = f.fileName() return '''File name:\t%s Folder:\t%s File type:\t%s File size:\t%s Last changed:\t%s''' % (n, f.filePath()[:-len(n)], f.suffix(), size, f.lastModified().toString())
def add_message(self, msg): """ Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage """ row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem(self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_TYPE, item) # filename item = QtWidgets.QTableWidgetItem( QtCore.QFileInfo(msg.path).fileName()) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_FILE_NAME, item) # line if msg.line < 0: item = QtWidgets.QTableWidgetItem("-") else: item = QtWidgets.QTableWidgetItem(str(msg.line + 1)) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_LINE_NBR, item) # desc item = QtWidgets.QTableWidgetItem(msg.description) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_MSG, item)
def setCurrentFile(self, fileName): self.curFile = QtCore.QFileInfo(fileName).canonicalFilePath() self.isUntitled = False self.document().setModified(False) self.setWindowModified(False) self.setWindowTitle(self.userFriendlyCurrentFile() + '[*]')
def get_icon(self, path): "Internal icon provider" return self.icons.icon(QtCore.QFileInfo(path))
def _get_icon(self): return QtWidgets.QFileIconProvider().icon(QtCore.QFileInfo(self.path))
def _add_file(self, path): icon = QtWidgets.QFileIconProvider().icon(QtCore.QFileInfo(path)) item = QtWidgets.QListWidgetItem(icon, path) self.listWidget.addItem(item)
def open(self, filename): prefs = self.preferences # VARIABLES: buff = prefs.pBuffer.value() step = prefs.pReadEveryNLine.value() stop_at_line = prefs.pHasStopLine.value() stop_n = prefs.pStopLine.value() x_col = prefs.pXColumn.value() has_x_col = prefs.pHasXColumn.value() self.n_line = 0 # number of current line step_len = 0 # number of lines in the read file_part n_defective_lines = 0 # number of corrupted lines i = 0 # current index in data array at_end = False # is file the the end labels = filename # COUNT LINES: if stop_at_line: self.nLines = stop_n else: modified = QtCore.QFileInfo(filename).lastModified().toString() # ONLY OF THIS IS A NEW FILE OR THE FILE WAS MODIFIED: if not (self._lastFilename == filename and self._lastModified == modified): self.nLines = countLines(filename, prefs.pBuffer.value()) self._lastnLines = self.nLines self._lastFilename = filename self._lastModified = modified else: self.nLines = self._lastnLines # GET NUMBER OF COLUMNS: with open(filename, 'r') as f: # FIND SEPARATOR: if prefs.pFindSeparator.value(): prefs.pSeparator.setValue(self._findSeparator(f)) separator = prefs.separators[prefs.pSeparator.value()] # DEFINE NUMBER OF COLUMNS: n_col = f.readline().count(separator) + 1 f.seek(0) # back to begin # FILTER COLUMNS: filter_columns = prefs.pFilterColumns.value() if filter_columns: c = [ch.value() for ch in prefs.pFilterColumns.children()[1:]][:n_col] # ADD X COLUMN TO THE BEGINNING: if has_x_col: if x_col not in c: c.insert(0, x_col) n_col = len(c) col_filter = itemgetter(*c) elif n_col > 1: col_filter = lambda l: l[:n_col] else: col_filter = lambda l: l[0] # GET FIRST LINE NAMES: fline = prefs.pFirstLine.value() if fline != '-': names = col_filter(f.readline().split(separator)) if fline == 'axes names': for n, ax in enumerate(self.display.axes): ax.p.setValue(names[n]) else: # plot names: labels = names if has_x_col: labels.pop(x_col) # JUMP TO START POSITION: startline = prefs.pStartLine.value() if startline: f.readline(startline) self.n_line = startline # PRINT FIRST 10 LINES: if prefs.pPrintFirstLines.value(): startPos = f.tell() print('==========') for line in f.readlines(min(self.nLines, 10)): # TODO: do the check for \n only once # ??? doesn't have every line \n at the end?? # print line[-2:] # if line[-2:] == '\n': # line = line[:-2] print('[%s]: %s' % (self.n_line, line)) print('--> %s\n' % str(col_filter(line.split(separator)))) f.seek(startPos) print('==========') # CREATE DATA ARRAY: shape = self.nLines // step if n_col == 0: raise Exception('no columns given') elif n_col > 1: shape = (shape, n_col) data = np.empty(shape=shape, dtype=prefs.dtypes[prefs.pDType.value()]) # MAIN LOOP: while not self.canceled: # READ PART OF THE FILE: file_piece = f.readlines(buff) l = len(file_piece) if not l: break for n, line in enumerate(file_piece[::step]): #line = line[:-1] # FILTER COLUMNS: line = col_filter(line.split(separator)) self.n_line = n + step_len # ADD LINE TO ARRAY: try: data[i] = line i += 1 except ValueError: n_defective_lines += 1 # CHECK BREAK CRITERIA: if stop_at_line and self.n_line >= stop_n: at_end = True break if at_end: break step_len += l data = data[:i] print('%s lines were corrupted' % n_defective_lines) # SPLIT ARRAY IF NEEDED: if (has_x_col and n_col > 2) or (not has_x_col and n_col > 1): if has_x_col: x = data[:, x_col] # GET Y COLUMNS THROUGH REMOVING THE X COLUMN: y_cols = np.c_[data[:, :x_col], data[:, x_col + 1:]] else: y_cols = data l = [] # CREATE TUPLE OF [y_n] OR [x, y_n] arrays: for n in range(y_cols.shape[1]): y = y_cols[:, n] if has_x_col: y = np.c_[x, y] l.append(y) return tuple(l), labels return [data], labels
def strippedName(self, fullFileName): return QtCore.QFileInfo(fullFileName).fileName()