예제 #1
0
class FileBrowserInputWidget(AbstractListInputWidget, iTansuGroupInput):
    def __init__(self, parent=None):
        super(FileBrowserInputWidget, self).__init__(parent=parent)

        # setup model
        self.model = QFileSystemModel()
        self.model.setRootPath('/home/')
        filters = self.model.filter()
        self.model.setFilter(filters | QDir.Hidden)

        # setup completer
        completer = QCompleter(self.model, self)
        self.setCompleter(completer)
        installCompleterPopup(completer)

        self.setCompleter(completer)
        completer.setCaseSensitivity(Qt.CaseInsensitive)

        self.autoCompleteList = []

    def checkDirectory(self):
        directory = str(self.text())
        if os.path.isdir(directory):
            self.model.setRootPath(str(self.text()))

    def event(self, event, *args, **kwargs):
        # I think this is the / key... lol
        if (event.type() == QEvent.KeyRelease) and event.key() == 47:
            self.checkDirectory()
            #self.completer().popup().show()
            self.completer().complete()

        return AbstractListInputWidget.event(self, event, *args, **kwargs)
예제 #2
0
def create_file_system_tree_dock_widget(view_menu: QMenu) -> DockWidget:
    '''
    Create file system tree dock widget

    Parameters
    ----------
    view_menu : QMenu

    Returns
    -------
    value : DockWidget
    '''
    widget = QTreeView()
    widget.setFrameShape(QFrame.NoFrame)

    m = QFileSystemModel(widget)
    m.setRootPath(QDir.currentPath())
    widget.setModel(m)

    _State.file_system_count += 1
    dock_widget = DockWidget("Filesystem {}".format(_State.file_system_count))
    dock_widget.set_widget(widget)
    view_menu.addAction(dock_widget.toggle_view_action())
    return dock_widget
예제 #3
0
class FileSystemTable(QTableView, TableType):
    if IN_DESIGNER:
        from PyQt5.QtCore import Q_ENUMS
        Q_ENUMS(TableType)

    gcodeFileSelected = Signal(bool)
    filePreviewText = Signal(str)
    fileNamePreviewText = Signal(str)
    transferFileRequest = Signal(str)
    rootChanged = Signal(str)

    def __init__(self, parent=None):
        super(FileSystemTable, self).__init__(parent)

        self._table_type = TableType.Local
        self._hidden_columns = ''

        # This prevents doing unneeded initialization
        # when QtDesginer loads the plugin.
        if parent is None:
            return

        self.parent = parent
        self.path_data = dict()
        self.doubleClicked.connect(self.openSelectedItem)
        self.selected_row = None
        self.clipboard = QApplication.clipboard()

        self.model = QFileSystemModel()
        self.model.setReadOnly(True)
        self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot
                             | QDir.AllEntries)

        self.setModel(self.model)

        self.verticalHeader().hide()
        self.horizontalHeader().setStretchLastSection(True)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.selection_model = self.selectionModel()
        self.selection_model.selectionChanged.connect(self.onSelectionChanged)

        self.info = Info()
        self.editor = self.info.getEditor()
        self._nc_file_dir = self.info.getProgramPrefix()
        self.nc_file_exts = self.info.getProgramExtentions()
        self.setRootPath(self._nc_file_dir)

    def showEvent(self, event=None):
        self.rootChanged.emit(self._nc_file_dir)

    def onSelectionChanged(self, selected, deselected):

        if len(selected) == 0:
            return

        index = selected.indexes()[0]
        path = self.model.filePath(index)

        if os.path.isfile(path):
            self.gcodeFileSelected.emit(True)
            with open(path, 'r') as fh:
                content = fh.read()
            self.filePreviewText.emit(content)
            self.fileNamePreviewText.emit(path)
        else:
            self.gcodeFileSelected.emit(False)
            self.filePreviewText.emit('')
            self.fileNamePreviewText.emit('')

    @Slot()
    def openSelectedItem(self, index=None):
        """If ngc file, opens in LinuxCNC, if dir displays dir."""
        if index is None:
            selection = self.getSelection()
            if selection is None:
                return
            index = selection[0]

        path = self.model.filePath(self.rootIndex())
        name = self.model.filePath(index)

        absolute_path = os.path.join(path, name)

        file_info = QFileInfo(absolute_path)
        if file_info.isDir():
            self.model.setRootPath(absolute_path)
            self.setRootIndex(self.model.index(absolute_path))
            self.rootChanged.emit(absolute_path)

        elif file_info.isFile():
            # if file_info.completeSuffix() not in self.nc_file_exts:
            #     LOG.warn("Unsuported NC program type with extention .%s",
            #              file_info.completeSuffix())
            loadProgram(absolute_path)

    @Slot()
    def editSelectedFile(self):
        """Open the selected file in editor."""
        selection = self.getSelection()
        if selection is not None:
            path = self.model.filePath(selection[0])
            subprocess.Popen([self.editor, path])
        return False

    @Slot()
    def loadSelectedFile(self):
        """Loads the selected file into LinuxCNC."""
        selection = self.getSelection()
        if selection is not None:
            path = self.model.filePath(selection[0])
            loadProgram(path)
            return True
        return False

    @Slot()
    def selectPrevious(self):
        """Select the previous item in the view."""
        selection = self.getSelection()
        if selection is None:
            # select last item in view
            self.selectRow(self.model.rowCount(self.rootIndex()) - 1)
        else:
            self.selectRow(selection[0].row() - 1)
        return True

    @Slot()
    def selectNext(self):
        """Select the next item in the view."""
        selection = self.getSelection()
        if selection is None:
            # select first item in view
            self.selectRow(0)
        else:
            self.selectRow(selection[-1].row() + 1)
        return True

    @Slot()
    def rename(self):
        """renames the selected file or folder"""
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        if path:
            file_info = QFileInfo(path)

            if file_info.isFile():
                filename = self.rename_dialog("file")

                if filename:
                    q_file = QFile(path)
                    file_info.absolutePath()
                    new_path = os.path.join(file_info.absolutePath(),
                                            str(filename))
                    q_file.rename(new_path)

            elif file_info.isDir():
                filename = self.rename_dialog("directory")

                if filename:
                    directory = QDir(path)
                    file_info.absolutePath()
                    new_path = os.path.join(file_info.absolutePath(),
                                            str(filename))
                    directory.rename(path, new_path)

    @Slot()
    def newFile(self):
        """Create a new empty file"""
        path = self.model.filePath(self.rootIndex())
        new_file_path = os.path.join(path, "New File.ngc")

        count = 1
        while os.path.exists(new_file_path):
            new_file_path = os.path.join(path, "New File {}.ngc".format(count))
            count += 1

        new_file = QFile(new_file_path)
        new_file.open(QIODevice.ReadWrite)

    @Slot()
    def newFolder(self):
        path = self.model.filePath(self.rootIndex())

        new_name = 'New Folder'

        count = 1
        while os.path.exists(os.path.join(path, new_name)):
            new_name = "New Folder {}".format(count)
            count += 1

        directory = QDir(path)
        directory.mkpath(new_name)
        directory.setPath(new_name)

    @Slot()
    @deprecated(replaced_by='newFolder',
                reason='for consistency with newFile method name')
    def createDirectory(self):
        self.newFolder()

    @Slot()
    def deleteItem(self):
        """Delete the selected item (either a file or folder)."""
        # ToDo: use Move2Trash, instead of deleting the file
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        if path:
            file_info = QFileInfo(path)
            if file_info.isFile():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected file?"):
                    return
                q_file = QFile(path)
                q_file.remove()

            elif file_info.isDir():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected directory?"):
                    return
                directory = QDir(path)
                directory.removeRecursively()

    @Slot()
    @deprecated(replaced_by='deleteItem',
                reason='because of unclear method name')
    def deleteFile(self):
        self.deleteItem()

    @Slot(str)
    def setRootPath(self, root_path):
        """Sets the currently displayed path."""

        self.rootChanged.emit(root_path)
        self.model.setRootPath(root_path)
        self.setRootIndex(self.model.index(root_path))

        return True

    @Slot()
    def viewParentDirectory(self):
        """View the parent directory of the current view."""

        path = self.model.filePath(self.rootIndex())

        file_info = QFileInfo(path)
        directory = file_info.dir()
        new_path = directory.absolutePath()

        currentRoot = self.rootIndex()

        self.model.setRootPath(new_path)
        self.setRootIndex(currentRoot.parent())
        self.rootChanged.emit(new_path)

    @Slot()
    @deprecated(replaced_by='viewParentDirectory')
    def goUP(self):
        self.viewParentDirecotry()

    @Slot()
    def viewHomeDirectory(self):
        self.setRootPath(os.path.expanduser('~/'))

    @Slot()
    def viewNCFilesDirectory(self):
        # ToDo: Make preset user definable
        path = os.path.expanduser('~/linuxcnc/nc_files')
        self.setRootPath(path)

    @Slot()
    def viewPresetDirectory(self):
        # ToDo: Make preset user definable
        preset = os.path.expanduser('~/linuxcnc/nc_files')
        self.setRootPath(preset)

    @Slot()
    def doFileTransfer(self):
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        self.transferFileRequest.emit(path)

    @Slot(str)
    def transferFile(self, src_path):
        dest_path = self.model.filePath(self.rootIndex())

        src_file = QFile()
        src_file.setFileName(src_path)

        src_file_info = QFileInfo(src_path)

        dst_path = os.path.join(dest_path, src_file_info.fileName())

        src_file.copy(dst_path)

    @Slot()
    def getSelection(self):
        """Returns list of selected indexes, or None."""
        selection = self.selection_model.selectedIndexes()
        if len(selection) == 0:
            return None
        return selection

    @Slot()
    def getCurrentDirectory(self):
        return self.model.rootPath()

    @Property(TableType)
    def tableType(self):
        return self._table_type

    @tableType.setter
    def tableType(self, table_type):
        self._table_type = table_type
        if table_type == TableType.Local:
            self.setRootPath(self._nc_file_dir)
        else:
            self.setRootPath('/media/')

    @Property(str)
    def hiddenColumns(self):
        """String of comma separated column numbers to hide."""
        return self._hidden_columns

    @hiddenColumns.setter
    def hiddenColumns(self, columns):
        try:
            col_list = [int(c) for c in columns.split(',') if c != '']
        except:
            return False

        self._hidden_columns = columns

        header = self.horizontalHeader()
        for col in range(4):
            if col in col_list:
                header.hideSection(col)
            else:
                header.showSection(col)

    def ask_dialog(self, message):
        box = QMessageBox.question(self.parent, 'Are you sure?', message,
                                   QMessageBox.Yes, QMessageBox.No)
        if box == QMessageBox.Yes:
            return True
        else:
            return False

    def rename_dialog(self, data_type):
        text, ok_pressed = QInputDialog.getText(
            self.parent, "Rename", "New {} name:".format(data_type),
            QLineEdit.Normal, "")

        if ok_pressed and text != '':
            return text
        else:
            return False
예제 #4
0
    def __init__(self, settings, path=None):
        super(RootWidget, self).__init__()

        # --- setup the file system model ---
        model = QFileSystemModel()
        model.setRootPath('This PC')
        model.setReadOnly(False)
        model.setIconProvider(
            JSONFileIconProvider('file_view_icons.json')
        )
        model.setFilter(
            QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs | QDir.Hidden
        )

        self._model = FileSystemProxyModel()
        self._model.setSourceModel(model)

        # --- setup the tree view ---
        self._view = QTreeView()
        self._view.setModel(self._model)
        self._view.setSelectionMode(QTreeView.ExtendedSelection)
        self._view.activated.connect(self._handle_activated_index)
        self._view.setSortingEnabled(True)
        self._view.setHeaderHidden(True)
        self._view.setExpandsOnDoubleClick(False)
        self._view.sortByColumn(0, Qt.AscendingOrder)

        # Setup drag and drop.
        self._view.setDragDropMode(QTreeView.DragDrop)
        self._view.setDefaultDropAction(Qt.MoveAction)

        # Setup the columns that show.
        self._view.hideColumn(1)
        self._view.hideColumn(2)
        self._view.hideColumn(3)

        # Note that the double click trigger cannot be in this list, otherwise it flashes in edit
        # mode before opening the file
        self._view.setEditTriggers(
            QTreeView.SelectedClicked | QTreeView.EditKeyPressed)

        # setup the context menu
        self._view.setContextMenuPolicy(Qt.CustomContextMenu)
        self._view.customContextMenuRequested.connect(self._context_menu)

        # Unselect items on collapse.
        self._view.collapsed.connect(self._view.clearSelection)

        # --- setup the current root path label ---
        self._root_edit = PathEdit()
        self._root_edit.new_path.connect(self._set_root_path)

        # --- setup the tool bar ---
        tool_bar = QToolBar()

        new_file_action = QAction('New File', self)
        tool_bar.addAction(new_file_action)
        tool_bar.widgetForAction(new_file_action).setObjectName('new_file')
        new_file_action.triggered.connect(self._create_file)

        new_directory_action = QAction('New Directory', self)
        tool_bar.addAction(new_directory_action)
        tool_bar.widgetForAction(new_directory_action).setObjectName('new_directory')
        new_directory_action.triggered.connect(self._create_directory)

        close_action = QAction('Close', self)
        tool_bar.addAction(close_action)
        self._close_widget = tool_bar.widgetForAction(close_action)
        self._close_widget.setObjectName('close_root')
        close_action.triggered.connect(self.close_request.emit)

        # --- setup the layout ---
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        path_layout = QHBoxLayout()
        path_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        path_layout.addWidget(self._root_edit)
        path_layout.addWidget(tool_bar)
        main_layout.addLayout(path_layout)

        main_layout.addWidget(self._view)

        self.setLayout(main_layout)

        if path is not None:
            self._set_root_path(path)
            self._root_edit.update(path)

        self._settings = None
        self.update_settings(settings)
예제 #5
0
class Q7File(QWidget, Ui_Q7FileWindow):
    def __init__(self, parent, mode=LOADMODE):
        super(Q7File, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("Load/Save")
        self.parent = parent
        self.iconProvider = Q7FileIconProvider()
        self.model = QFileSystemModel()
        self.model.setIconProvider(self.iconProvider)
        self.proxy = Q7FileFilterProxy(self)
        self.proxy.setSourceModel(self.model)
        self.treeview.setModel(self.proxy)
        self.setAttribute(Qt.WA_DeleteOnClose)
        #
        if HAS_PY2:
            self.model.directoryLoaded[unicode].connect(self.expandCols)
        else:
            self.model.directoryLoaded[str].connect(self.expandCols)
        self.treeview.expanded[QModelIndex].connect(self.expandCols)
        self.treeview.clicked[QModelIndex].connect(self.clickedNode)
        self.treeview.doubleClicked[QModelIndex].connect(
            self.clickedNodeAndLoad)
        self.direntries.lineEdit().returnPressed.connect(self.changeDirEdit)
        self.direntries.currentIndexChanged[int].connect(self.changeDirIndex)
        self.fileentries.currentIndexChanged[int].connect(self.changeFile)
        self.fileentries.lineEdit().editingFinished.connect(self.changeFile)
        self.tabs.currentChanged[int].connect(self.currentTabChanged)
        self.cShowAll.stateChanged[int].connect(self.updateView)
        self.cShowDirs.stateChanged[int].connect(self.updateView)
        self.rClearSelectedDirs.toggled[bool].connect(self.updateClearDirs)
        self.rClearSelectedFiles.toggled[bool].connect(self.updateClearFiles)
        self.rClearAllDirs.toggled[bool].connect(self.updateClearNone)
        self.rClearNoHDF.toggled[bool].connect(self.updateClearNoHDF)
        self.rClearNotFound.toggled[bool].connect(self.updateClearNotFound)
        #
        self.bClose.clicked.connect(self.closeUnlock)
        self.bCurrent.clicked.connect(self.currentDir)
        self.bBack.clicked.connect(self.backDir)
        self.bInfo.clicked.connect(self.infoFileView)
        self.bInfo2.clicked.connect(self.infoFileView)
        self.bClearHistory.clicked.connect(self.doClearHistory)
        self.mode = mode
        if self.mode == SAVEMODE:
            self.setMode(False)
        else:
            self.setMode(True)
        self.setBoxes()
        self.parent.getHistory()
        self.updateHistory()
        self.updateClearNotFound()

    def closeUnlock(self):
        self.parent.signals.cancel.emit()
        self.close()

    def closeEvent(self, event):
        self.closeUnlock()

    def infoFileView(self):
        self.parent.helpWindow('File')

    def updateView(self):
        p = self.direntries.currentText()
        self.setCurrentDir(p)
        print('CURRENT', p)
        # self.proxy.reset()
        self.proxy.beginResetModel()
        self.proxy.endResetModel()
        self.setCurrentDir(p)
        self.updateFileIfFound()

    def currentTabChanged(self, tabno):
        self.expandCols()
        self.setBoxes()

    def getOpt(self, name):
        return getattr(self, '_Ui_Q7FileWindow__O_' + name.lower())

    def setBoxes(self):
        ckh = self.getOpt('FilterHDFFiles')
        ckg = self.getOpt('FilterCGNSFiles')
        if self.parent.getOptionValue('FilterHDFFiles'):
            ckh.setCheckState(Qt.Checked)
        else:
            ckh.setCheckState(Qt.Unchecked)
        if self.parent.getOptionValue('FilterCGNSFiles'):
            ckg.setCheckState(Qt.Checked)
        else:
            ckg.setCheckState(Qt.Unchecked)
        if ((ckh.checkState() == Qt.Unchecked)
                and (ckg.checkState() == Qt.Unchecked)):
            self.cShowAll.setCheckState(Qt.Checked)

    def getBoxes(self):
        if self.getOpt('FilterHDFFiles').checkState() == Qt.Unchecked:
            self.parent.setOptionValue('FilterHDFFiles', False)
        else:
            self.parent.setOptionValue('FilterHDFFiles', True)
        if self.getOpt('FilterCGNSFiles').checkState() == Qt.Unchecked:
            self.parent.setOptionValue('FilterCGNSFiles', False)
        else:
            self.parent.setOptionValue('FilterCGNSFiles', True)

    def expandCols(self, *args):
        self.getBoxes()
        for n in range(3):
            self.treeview.resizeColumnToContents(n)

    def currentDir(self, *args):
        # p=os.path.split(self.path())[0]
        p = os.getcwd()
        self.setCurrentDir(p)

    def backDir(self, *args):
        p = os.path.split(self.path())[0]
        self.setCurrentDir(p)

    def changeDirEdit(self, *args):
        self.changeDir(args)

    def changeDirText(self, *args):
        self.changeDir(args)

    def changeDirIndex(self, *args):
        self.changeDir(args)

    def changeDir(self, *args):
        if self.updateMode:
            return
        p = str(self.direntries.currentText())
        if os.path.isdir(p):
            self.updateView()
        else:
            reply = MSG.wQuestion(
                self.parent, 110, 'Directory not found...',
                """The path below doesn't exist, do you want to remove<br>
                                     it from the history?<br>%s""" % p)
            if reply == MSG.OK:
                ix = self.direntries.currentIndex()
                self.direntries.removeItem(ix)

    def changeFile(self, *args):
        self.selectedfile = str(self.fileentries.lineEdit().text())
        d = None
        if self.cAutoDir.checkState() == Qt.Checked:
            d = self.parent.getHistoryFile(self.selectedfile)
        if d is not None:
            self.selecteddir = d[0]
            ix = self.direntries.findText(self.selecteddir)
            if ix != -1:
                self.direntries.setCurrentIndex(ix)
        else:
            self.selecteddir = self.direntries.lineEdit().text()
        self.updateFileIfFound()

    def selectedPath(self):
        return os.path.join(self.selecteddir, self.selectedfile)

    def updateFileIfFound(self):
        filepath = self.selectedPath()
        midx = self.model.index(filepath)
        if midx.row == 1:
            return
        fidx = self.proxy.mapFromSource(midx)
        if fidx.row == 1:
            return
        self.treeview.setCurrentIndex(fidx)
        self.treeview.scrollTo(fidx)

    def setCurrentDir(self, newpath):
        self.model.setRootPath(newpath)
        midx = self.model.index(newpath)
        fidx = self.proxy.mapFromSource(midx)
        self.treeview.setRootIndex(fidx)
        self.treeview.setCurrentIndex(fidx)
        self.direntries.setItemText(self.direntries.currentIndex(), newpath)
        self.selecteddir = newpath

    def setMode(self, load=True):
        if load:
            self.bAction.clicked.connect(self.load)
            self.bAction.setToolTip(LOADBUTTON[1])
            self.bAction.setText(LOADBUTTON[0])
            self.cOverwrite.setEnabled(False)
            self.cReadOnly.setEnabled(True)
            self.cNoLargeData.setEnabled(True)
            self.cFollowLinks.setEnabled(True)
            self.cDeleteMissing.setEnabled(False)
            if OCTXT.DoNotLoadLargeArrays:
                self.cNoLargeData.setCheckState(Qt.Checked)
            else:
                self.cNoLargeData.setCheckState(Qt.Unchecked)
            if OCTXT.FollowLinksAtLoad:
                self.cFollowLinks.setCheckState(Qt.Checked)
            else:
                self.cFollowLinks.setCheckState(Qt.Unchecked)
        else:
            self.bAction.clicked.connect(self.save)
            self.bAction.setToolTip(SAVEBUTTON[1])
            self.bAction.setText(SAVEBUTTON[0])
            self.cOverwrite.setEnabled(True)
            self.cReadOnly.setEnabled(False)
            self.cNoLargeData.setEnabled(False)
            self.cFollowLinks.setEnabled(False)
            self.cDeleteMissing.setEnabled(True)
            if OCTXT.FileUpdateRemovesChildren:
                self.cDeleteMissing.setCheckState(Qt.Checked)
            else:
                self.cDeleteMissing.setCheckState(Qt.Unchecked)

    def updateHistory(self):
        self.updateMode = True
        self.direntries.clear()
        self.fileentries.clear()
        hlist = self.parent.getHistory(fromfile=False)
        flist = []
        self.fileentries.addItem("")
        for i in list(hlist):
            if i != self.parent.getHistoryLastKey():
                self.direntries.addItem(str(i))
                flist = flist + hlist[i]
        for i in flist:
            self.fileentries.addItem(str(i))
        self.historyfiles = flist
        self.historydirs = list(hlist)
        if self.parent.getHistoryLastKey() in list(hlist):
            self.selecteddir = hlist[self.parent.getHistoryLastKey()][0]
            self.selectedfile = hlist[self.parent.getHistoryLastKey()][1]
            # ixd=self.direntries.findText(self.selecteddir)
            self.setCurrentDir(self.selecteddir)
            ixf = self.fileentries.findText(self.selectedfile)
            self.fileentries.setCurrentIndex(ixf)
            self.changeFile()
        else:
            self.selecteddir = os.getcwd()
            self.selectedfile = ""
            self.setCurrentDir(self.selecteddir)
        self.updateMode = False

    def doClearHistory(self):
        if self.rClearNoHDF.isChecked():
            reply = MSG.wQuestion(
                self.parent, 120, 'Clear history',
                """You really want to remove directory entries from history<br>
                                     where no file with defined extensions has been found?<br>"""
            )
            if reply == MSG.OK:
                for d in self.parent.getDirNoHDFFromHistory():
                    self.parent.removeDirFromHistory(d)
                    self.updateHistory()
                    self.lClear.clear()
        if self.rClearNotFound.isChecked():
            reply = MSG.wQuestion(
                self.parent, 121, 'Clear history',
                """You really want to remove <b>NOT FOUND</b> entries from<br>
                                     the history of used directories?<br>""")
            if reply == MSG.OK:
                for d in self.parent.getDirNotFoundFromHistory():
                    self.parent.removeDirFromHistory(d)
                    self.updateHistory()
                    self.lClear.clear()
        if self.rClearAllDirs.isChecked():
            reply = MSG.wQuestion(
                self.parent, 122, 'Clear history',
                """You really want to remove <b>ALL</b> entries from the<br>
                                     the history of used files and directories?<br>"""
            )
            if reply == MSG.OK:
                self.parent.destroyHistory()
                self.updateHistory()
        if self.rClearSelectedDirs.isChecked():
            for it in self.lClear.selectedItems():
                self.parent.removeDirFromHistory(it.text())
            self.updateHistory()
            self.updateClearDirs()
        if self.rClearSelectedFiles.isChecked():
            for it in self.lClear.selectedItems():
                fd = self.parent.getHistoryFile(it.text())
                if fd is not None:
                    self.parent.removeFileFromHistory(*fd)
            self.updateHistory()
            self.updateClearFiles()

    def updateClearNone(self):
        self.lClear.clear()

    def updateClearNoHDF(self):
        self.lClear.clear()
        self.lClear.setSelectionMode(QAbstractItemView.NoSelection)
        for d in self.parent.getDirNoHDFFromHistory():
            self.lClear.addItem(d)

    def updateClearNotFound(self):
        self.lClear.clear()
        self.lClear.setSelectionMode(QAbstractItemView.NoSelection)
        for d in self.parent.getDirNotFoundFromHistory():
            self.lClear.addItem(d)

    def updateClearDirs(self):
        self.lClear.clear()
        self.lClear.setSelectionMode(QAbstractItemView.MultiSelection)
        for d in self.historydirs:
            self.lClear.addItem(d)

    def updateClearFiles(self):
        self.lClear.clear()
        self.lClear.setSelectionMode(QAbstractItemView.MultiSelection)
        for d in self.historyfiles:
            self.lClear.addItem(d)

    def load(self):
        diag = self.checkTarget(self.selectedPath())
        if diag is None:
            self.parent.signals.buffer = self.selectedPath()
            self.hide()
            self.parent.signals.loadFile.emit()
            self.close()
        else:
            MSG.message("Load file: %s" % self.selectedPath(), diag, MSG.INFO)

    def save(self):
        diag = self.checkTarget(self.selectedPath(), write=True)
        if diag is None:
            self.parent.signals.buffer = self.selectedPath()
            self.hide()
            self.parent.signals.saveFile.emit()
            self.close()
        else:
            MSG.message("Save file: %s" % self.selectedPath(), diag, MSG.INFO)

    def checkTarget(self, filename, write=False):
        if os.path.isfile(filename) and not write:
            return None
        if not os.path.isfile(filename) and write:
            return None
        if self.cOverwrite.isChecked():
            sc = "The file is <b>completely replaced</b> by the current tree"
        else:
            sc = "The file is <b>updated</b> with the current tree contents."
            if self.cDeleteMissing.isChecked():
                sc += "The nodes <b>NOT</b> found in the current tree are removed from the updated file"
            else:
                sc += "The nodes <b>NOT</b> found in the current tree are kept unchanged"
        reply = MSG.wQuestion(self,
                              132,
                              'Saving on an already existing file',
                              """You are going to save into an existing file,
                              based on the current options you have and the target tree you want to save,
                              the result would be the following:<p>%s<p>
                              If this not the way you want the save to operate, please <i>abort</b> this
                              file selection and check the <i>Load/Save option</i> tab.
                              You still want to write on this file?""" % sc,
                              buttons=('Continue to save on existing file',
                                       'Abort save'))
        if reply:
            return None
        return 'User Abort'

    def path(self, index=None):
        if index is None:
            idx = self.treeview.currentIndex()
            p = str(self.model.filePath(self.proxy.mapToSource(idx)))
        else:
            p = str(self.model.filePath(self.proxy.mapToSource(index)))
        return p

    def clickedNodeAndLoad(self, index):
        self.clickedNode(index)
        if self.mode == SAVEMODE:
            self.save()
        else:
            self.load()

    def clickedNode(self, index):
        self.treeview.resizeColumnToContents(0)
        p = self.path(index)
        if os.path.isdir(p):
            f = ''
            d = p
            self.setCurrentDir(d)
        else:
            f = os.path.basename(self.path(index))
            d = os.path.dirname(self.path(index))
        ix = self.direntries.findText(d)
        if ix != -1:
            self.direntries.setCurrentIndex(ix)
        else:
            self.direntries.addItem(d)
            self.direntries.setCurrentIndex(self.direntries.findText(d))
        ix = self.fileentries.findText(f)
        if ix != -1:
            self.fileentries.setCurrentIndex(ix)
        else:
            self.fileentries.addItem(f)
            self.fileentries.setCurrentIndex(self.fileentries.findText(f))
        self.selecteddir = self.direntries.lineEdit().text()
        self.selectedfile = self.fileentries.lineEdit().text()