def clean_generated_folders(self,
                                fsmodel: QFileSystemModel,
                                remove: Dict[int, Set[str]],
                                keep: Optional[Dict[int, Set[str]]] = None,
                                scan_id: Optional[int] = None) -> None:
        """
        Remove preview folders from the file system, if necessary keeping those
        used for the other type of file (e.g. if moving only photos, keep video download
        dirs)

        :param remove: folders to remove
        :param keep: folders to keep
        :param scan_id: if not None, remove preview folders only for that scan_id
        """

        levels = [level for level in remove]
        levels.sort(reverse=True)

        if keep is not None:
            keep = self._flatten_set(keep)
        else:
            keep = set()

        removed_folders = []

        # self.dump()

        for level in levels:
            for subfolder in remove[level]:
                if (subfolder not in keep
                        and subfolder not in self.existing_subfolders
                        and os.path.isdir(subfolder)):
                    key = (level, subfolder)
                    if scan_id is not None:
                        do_rmdir = False
                        scan_ids = self.scan_ids_for_created_subfolders[key]
                        if scan_id in scan_ids:
                            if len(scan_ids) == 1:
                                do_rmdir = True
                                removed_folders.append((level, subfolder))
                            scan_ids.remove(scan_id)
                            if len(scan_ids) == 0:
                                del self.scan_ids_for_created_subfolders[key]
                    else:
                        do_rmdir = True
                        if key in self.scan_ids_for_created_subfolders:
                            del self.scan_ids_for_created_subfolders[key]

                    if do_rmdir:
                        if not os.listdir(subfolder):
                            # logging.debug("Removing subfolder %s", subfolder)
                            index = fsmodel.index(subfolder)
                            if not fsmodel.rmdir(index):
                                logging.debug(
                                    "While cleaning generated folders, did not remove %s. The "
                                    "cause for the error is unknown.",
                                    subfolder)

        if scan_id is not None:
            for level, subfolder in removed_folders:
                remove[level].remove(subfolder)
Esempio n. 2
0
class FileWidget(QWidget):
    def __init__(self):
        super().__init__()
        # QWidget部件是PyQt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
        # 创建一个文件系统模型
        self.file_model = QFileSystemModel()
        # 设置目录为当前工作目录
        self.file_model.setRootPath(QDir.currentPath())
        # 创建树视图,构建文件目录视图
        self.treeview = QTreeView()
        # 绑定此文件模型
        self.treeview.setModel(self.file_model)
        '''
        设置当前勾结点索引为当前工作目录
        如果想从整个文件系统根节点开始浏览视图,
        简单删掉此行即可
        '''
        self.treeview.setRootIndex(self.file_model.index(QDir.currentPath()))
        # 头部显示排序戳
        self.treeview.header().setSortIndicatorShown(True)

        # 创建右键菜单
        self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
        # point = self.treeview.pos()
        self.treeview.customContextMenuRequested.connect(self.generateMenu)
        '''
        # 底部按钮布局
        self.mkdirButton = QPushButton("Make Directory...")
        self.rmButton = QPushButton("Remove")
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.mkdirButton)
        buttonLayout.addWidget(self.rmButton)
        '''
        # 文件管理界面布局
        layout = QVBoxLayout()
        layout.addWidget(self.treeview)
        # layout.addLayout(buttonLayout)

        # resize()方法调整窗口的大小。600px宽300px高
        self.resize(600, 300)
        # move()方法移动窗口在屏幕上的位置到x = 300,y = 300坐标。
        self.move(300, 300)
        # 设置窗口的标题
        self.setWindowTitle('File Manage')
        # 设置窗口的图标
        self.setWindowIcon(QIcon('File-Explorer.png'))
        self.setLayout(layout)

    # 生成右键菜单
    def generateMenu(self, position):
        # 索引默认值
        row_num = -1
        # 遍历确定行号
        for i in self.treeview.selectionModel().selection().indexes():
            row_num = i.row()
        # 保证选中有效项
        if row_num != -1:
            # 创建右键菜单
            menu = QMenu()
            # 提供删除和创建文件/文件夹选项
            item1 = menu.addAction("Delete")
            item2 = menu.addAction("NewDirectory")
            # 在光标处显示执行菜单
            action = menu.exec_(self.treeview.mapToGlobal(position))
            if action == item1:
                #弹出消息框确认此次删除操作
                res = self.msgbox()
                if res:
                    self.delete()
                else:
                    return
            elif action == item2:
                self.mkdirectory()
            else:
                return
        else:
            return

    # 删除选定文件/文件夹
    def delete(self):
        index = self.treeview.currentIndex()
        if index.isValid():
            fileInfo = self.file_model.fileInfo(index)
            if fileInfo.isDir():
                self.file_model.rmdir(index)
            else:
                self.file_model.remove(index)

    # 确认框
    def msgbox(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Warning")
        msgBox.setText("Delete the file/dir you selected?")
        msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msgBox.setDefaultButton(QMessageBox.No)
        # button = QMessageBox.question("Warning", "delete the file/dir?",
        #                               QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        button = msgBox.exec_()
        if button == QMessageBox.No:
            return False
        elif button == QMessageBox.Yes:
            return True

    # 创建文件夹
    def mkdirectory(self):
        index = self.treeview.rootIndex()
        if index.isValid():
            # 弹出输入框录入文件名
            dirname, ok = QInputDialog.getText(self, "File Name",
                                               "Input an unique dir name:")
            if ok:
                self.file_model.mkdir(index, dirname)
            else:
                return

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_F3:
            self.close()