def selectFile(self, new, old): if (self.resetting): self.resetting = False return if len(new.indexes()) == 0: self.clearSelection() self.currentFile = "" self.readOnly(True) return newSelection = self.files.filePath(new.indexes()[0]) self.settings.setValue("ui/snippeteditor/selected", newSelection) if QFileInfo(newSelection).isDir(): self.readOnly(True) self.clearSelection() self.currentFile = "" return if old and old.length() > 0: oldSelection = self.files.filePath(old.indexes()[0]) if not QFileInfo(oldSelection).isDir() and self.snippetChanged(): question = QMessageBox.question( self, self.tr("Discard"), self.tr("Snippet changed. Discard changes?")) if question != QMessageBox.StandardButton.Yes: self.resetting = True self.tree.selectionModel().select( old, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) return False self.currentFile = newSelection self.loadSnippet()
def selectFile(self, new, old): if (self.resetting): self.resetting = False return if len(new.indexes()) == 0: self.clearSelection() self.currentFile = "" self.readOnly(True) return newSelection = self.files.filePath(new.indexes()[0]) self.settings.setValue("ui/snippeteditor/selected", newSelection) if QFileInfo(newSelection).isDir(): self.readOnly(True) self.clearSelection() self.currentFile = "" return if old and old.length() > 0: oldSelection = self.files.filePath(old.indexes()[0]) if not QFileInfo(oldSelection).isDir() and self.snippetChanged(): save = self.askSave() if save == QMessageBox.Yes: self.save() elif save == QMessageBox.No: pass elif save == QMessageBox.Cancel: self.resetting = True self.tree.selectionModel().select( old, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) return False self.currentFile = newSelection self.loadSnippet()
def file_is_x(file_path: str, mime_prefix: str): info = QFileInfo(file_path) if not info.isReadable(): logging.info("File {} is not readable".format(info.filePath())) return False db = QMimeDatabase() mime_type = db.mimeTypeForFile(info) return mime_type.name().startswith(mime_prefix)
def __init__(self, file_path, *args): super().__init__(*args) self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) self.setData(TreeWidgetType.SONG, CustomDataRole.ITEMTYPE) info = QFileInfo(file_path) self.setData( TreeWidgetItemData(TreeWidgetType.SONG, song_path=file_path, song_dir=info.path(), song_file=info.fileName()), CustomDataRole.ITEMDATA)
def run(self): """ Main logic. Extracts the archive to a directory with the same name. """ self.signals.started.emit() # define target directory target_dir = QFileInfo(self.archive_path) target_dir = os.path.join(target_dir.path(), target_dir.baseName()) while (os.path.isdir(target_dir)): target_dir += '_' if tarfile.is_tarfile(self.archive_path): with tarfile.TarFile(self.archive_path, 'r') as archive: self.maximum = len(archive.getnames()) self.signals.ready.emit(self.maximum) file_count = 0 self.signals.progress.emit(file_count) self.signals.progress_message.emit(self.progress_str( file_count)) for file in archive.get_members(): if self.is_canceled: break archive.extract(file, target_dir) file_count += 1 self.signals.progress.emit(file_count) self.signals.progress_message.emit(self.progress_str( file_count)) elif zipfile.is_zipfile(self.archive_path): with zipfile.ZipFile(self.archive_path, 'r') as archive: self.maximum = len(archive.namelist()) self.signals.ready.emit(self.maximum) file_count = 0 self.signals.progress.emit(file_count) self.signals.progress_message.emit(self.progress_str( file_count)) for file in archive.infolist(): if self.is_canceled: break archive.extract(file, target_dir) file_count += 1 self.signals.progress.emit(file_count) self.signals.progress_message.emit(self.progress_str( file_count)) self.signals.finished.emit()
def addSong(self, path: str): if not file_is_audio(path): logging.info("File {} is not audio".format(path)) return item = self._create_song_item(path) item.setText(QFileInfo(path).fileName()) self.addTopLevelItem(item)
def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None
def loadSnippet(self): self.currentFileLabel.setText(QFileInfo(self.currentFile).baseName()) (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(self.currentFile) self.snippetDescription.setText(snippetDescription) if snippetDescription else self.snippetDescription.setText("") self.keySequenceEdit.setKeySequence(snippetKeys) if snippetKeys else self.keySequenceEdit.setKeySequence(QKeySequence("")) self.edit.setPlainText(snippetCode) if snippetCode else self.edit.setPlainText("") self.readOnly(False)
def addAlbum(self, dir_path: str): songs = [] for file_path in files_in_directory(dir_path): info = QFileInfo(file_path) if not info.isReadable(): logging.warning("File {} is not readable".format(file_path)) continue if info.isDir(): self.addAlbum(file_path) elif file_is_audio(file_path): item = self._create_song_item(file_path) item.setText(info.fileName()) songs.append(item) if len(songs) > 0: album_item = self._create_album_item(dir_path, songs) album_item.setText(dir_path) self.addTopLevelItem(album_item)
def write_bookmarks(self): if not self._modified: return dir_path = _config_dir() native_dir_path = QDir.toNativeSeparators(dir_path) dir = QFileInfo(dir_path) if not dir.isDir(): print('Creating {}...'.format(native_dir_path)) if not QDir(dir.absolutePath()).mkpath(dir.fileName()): warnings.warn('Cannot create {}.'.format(native_dir_path), RuntimeWarning) return serialized_model = _serialize_model(self._model, dir_path) bookmark_file_name = os.path.join(native_dir_path, _bookmark_file) print('Writing {}...'.format(bookmark_file_name)) with open(bookmark_file_name, 'w') as bookmark_file: jsons.dump(serialized_model, bookmark_file, indent=4)
def __init__(self, file_path, *args): super().__init__(*args) self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) self.setData(TreeWidgetType.SONG, CustomDataRole.ITEMTYPE) info = QFileInfo(file_path) self.setData( TreeWidgetItemData( TreeWidgetType.SONG, song_path=file_path, song_dir=info.path(), song_file=info.fileName(), ), CustomDataRole.ITEMDATA, ) # set acodec to copy by default, # overridden when concatenating self.set("audioCodec", "copy")
def newFolder(self): (folderName, ok) = QInputDialog.getText(self, self.tr("Folder Name"), self.tr("Folder Name: ")) if ok and folderName: index = self.tree.selectionModel().currentIndex() selection = self.files.filePath(index) if QFileInfo(selection).isDir(): QDir(selection).mkdir(folderName) else: QDir(snippetPath).mkdir(folderName)
def snippetChanged(self): if (self.currentFile == "" or QFileInfo(self.currentFile).isDir()): return False (snippetDescription, snippetKeys, snippetCode) = loadSnippetFromFile(self.currentFile) if snippetKeys == None and not self.keySequenceEdit.keySequence().isEmpty(): return True if snippetKeys != None and snippetKeys != self.keySequenceEdit.keySequence().toString(): return True return self.edit.toPlainText() != snippetCode or \ self.snippetDescription.text() != snippetDescription
def newFileDialog(self): (snippetName, ok) = QInputDialog.getText(self, self.tr("Snippet Name"), self.tr("Snippet Name: "), flags=self.windowFlags()) if ok and snippetName: if not snippetName.endswith(".py"): snippetName += ".py" index = self.tree.selectionModel().currentIndex() selection = self.files.filePath(index) if QFileInfo(selection).isDir(): path = os.path.join(selection, snippetName) else: path = os.path.join(snippetPath, snippetName) self.readOnly(False) open(path, "w").close() self.tree.setCurrentIndex(self.files.index(path)) log_debug("Snippet %s created." % snippetName)
def item_open_event(self): """ Opens the selected files using xdg-open, runs it, if it is executable or changes the current dir if it's dir. """ selected_items = [] for index in self.table_view.selectedIndexes(): if index.column() == 0: selected_items.append(QFileInfo(os.path.join(self.current_path, index.siblingAtColumn(0).data()))) # warn before accidentally open a bunch of files open = True if len(selected_items) > 3: dialog = utility.question_dialog('Do you really want to open ' + str(len(selected_items)) + ' files?') button = dialog.exec() if button == QMessageBox.Cancel: open = False if open: for item in selected_items: if (item.isDir()): next_path = item.absoluteFilePath() self.update_current_path(next_path) elif (item.isFile()): if (item.isExecutable()): QProcess().startDetached(item.absoluteFilePath(), [], self.current_path) else: QProcess().startDetached('xdg-open', [item.absoluteFilePath()], self.current_path) else: dialog = utility.message_dialog('The type of the selected' + ' file can not be' + ' detected.', QMessageBox.Warning) dialog.exec()
def contextMenuEvent(self, event): state = self.state() context_menu = QMenu() launch_action = context_menu.addAction("Launch") launch_action.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) show_in_folder_action = context_menu.addAction("Show in Folder") show_in_folder_action.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) cancel_action = context_menu.addAction("Cancel") cancel_action.setEnabled(state == QWebEngineDownloadItem.DownloadInProgress) remove_action = context_menu.addAction("Remove") remove_action.setEnabled(state != QWebEngineDownloadItem.DownloadInProgress) chosen_action = context_menu.exec_(event.globalPos()) if chosen_action == launch_action: self._launch() elif chosen_action == show_in_folder_action: path = QFileInfo(self._download_item.path()).absolutePath() DownloadWidget.open_file(path) elif chosen_action == cancel_action: self._download_item.cancel() elif chosen_action == remove_action: self.remove_requested.emit()
def dropEvent(self, event: QDropEvent): if event.source(): super().dropEvent(event) else: for url in event.mimeData().urls(): info = QFileInfo(url.toLocalFile()) if not info.isReadable(): logging.warning("File {} is not readable".format( info.filePath())) continue if info.isDir(): if get_setting("dragAndDropBehavior" ) == SETTINGS_VALUES.DragAndDrop.ALBUM_MODE: self.addAlbum(url.toLocalFile()) else: for file_path in files_in_directory_and_subdirectories( info.filePath()): self.addSong(file_path) else: self.addSong(info.filePath())
def __init__(self, download_item): super(DownloadWidget, self).__init__() self._download_item = download_item download_item.finished.connect(self._finished) download_item.downloadProgress.connect(self._download_progress) download_item.stateChanged.connect(self._update_tool_tip()) path = download_item.path() self.setMaximumWidth(300) # Shorten 'PySide6-5.11.0a1-5.11.0-cp36-cp36m-linux_x86_64.whl'... description = QFileInfo(path).fileName() description_length = len(description) if description_length > 30: description = '{}...{}'.format(description[0:10], description[description_length - 10:]) self.setFormat('{} %p%'.format(description)) self.setOrientation(Qt.Horizontal) self.setMinimum(0) self.setValue(0) self.setMaximum(100) self._update_tool_tip() # Force progress bar text to be shown on macoS by using 'fusion' style if sys.platform == 'darwin': self.setStyle(QStyleFactory.create('fusion'))
def file_info(paths: List[str]) -> str: """ Retrieves information about the given files. :param path: Path to the files. :type path: List[str] :return: Information of the file. :rtype: str """ size = 0 for path in paths: file = QFileInfo(path) if (file.isFile()): size += file.size() elif (len(paths) > 1): return str(len(paths)) + ' items selected' size = '{:!.2j}B'.format(Float(size)) if (len(paths) > 1): return str(len(paths)) + ' files selected, using ' + size file = QFileInfo(paths[0]) if (file.isFile()): return (os.path.basename(path) + ': ' + size) return (os.path.basename(path))
from PySide6.QtCore import (QFile, QFileInfo, QUrl) from PySide6.QtWebChannel import QWebChannel from PySide6.QtWebSockets import QWebSocketServer from dialog import Dialog from core import Core from websocketclientwrapper import WebSocketClientWrapper if __name__ == '__main__': app = QApplication(sys.argv) if not QSslSocket.supportsSsl(): print('The example requires SSL support.') sys.exit(-1) cur_dir = os.path.dirname(os.path.abspath(__file__)) jsFileInfo = QFileInfo(cur_dir + "/qwebchannel.js") if not jsFileInfo.exists(): QFile.copy(":/qtwebchannel/qwebchannel.js", jsFileInfo.absoluteFilePath()) # setup the QWebSocketServer server = QWebSocketServer("QWebChannel Standalone Example Server", QWebSocketServer.NonSecureMode) if not server.listen(QHostAddress.LocalHost, 12345): print("Failed to open web socket server.") sys.exit(-1) # wrap WebSocket clients in QWebChannelAbstractTransport objects clientWrapper = WebSocketClientWrapper(server) # setup the channel
def setCurrentFile(self, fileName): self.curFile = QFileInfo(fileName).canonicalFilePath() self.isUntitled = False self.document().setModified(False) self.setWindowModified(False) self.setWindowTitle(self.userFriendlyCurrentFile() + "[*]")
def strippedName(self, fullFileName): return QFileInfo(fullFileName).fileName()