# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
# Copyright 2014 Spyder Project Contributors.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Files and Directories Explorer."""

# yapf: disable

from __future__ import with_statement

# Standard library imports
import os
import os.path as osp
import re
import shutil

# Third party imports
from qtpy import is_pyqt46
from qtpy.compat import getexistingdirectory, getsavefilename
from qtpy.QtCore import (QDir, QFileInfo, QMimeData, QSortFilterProxyModel, Qt,
                         QTimer, QUrl, Signal, Slot)
from qtpy.QtGui import QDrag, QIcon
from qtpy.QtWidgets import (QFileIconProvider, QFileSystemModel, QHBoxLayout,
                            QLabel, QMenu, QToolButton, QTreeView, QVBoxLayout,
                            QWidget)

# Local imports
from anaconda_navigator.utils import encoding, misc, programs
from anaconda_navigator.utils.py3compat import (getcwd, str_lower,
                                                to_binary_string,
                                                to_text_string)
from anaconda_navigator.utils.qthelpers import (add_actions, create_action,
                                                file_uri)
from anaconda_navigator.widgets.dialogs import (InputDialog, MessageBoxError,
                                                MessageBoxQuestion)

# yapf: enable

try:
    from nbconvert import PythonExporter as nbexporter
except:
    nbexporter = None  # analysis:ignore


def fixpath(path):
    """Normalize path fixing case, making absolute and removing symlinks."""
    norm = osp.normcase if os.name == 'nt' else osp.normpath
    return norm(osp.abspath(osp.realpath(path)))


def create_script(fname):
    """Create a new Python script."""
    text = os.linesep.join(["# -*- coding: utf-8 -*-", "", ""])
    encoding.write(to_text_string(text), fname, 'utf-8')


# exclude=r'\.pyc$|^\.',


def listdir(
    path, include='.', exclude=r'\.pyc$', show_all=True, folders_only=False
):
    """List files and directories."""
    namelist = []
    dirlist = [to_text_string(osp.pardir)]
    for item in os.listdir(to_text_string(path)):
        if re.search(exclude, item) and not show_all:
            continue
        if osp.isdir(osp.join(path, item)):
            dirlist.append(item)
        elif folders_only:
            continue
        elif re.search(include, item) or show_all:
            namelist.append(item)
    return (sorted(dirlist, key=str_lower) + sorted(namelist, key=str_lower))


def has_subdirectories(path, include, exclude, show_all):
    """Return True if path has subdirectories"""
    try:
        # > 1 because of '..'
        return len(
            listdir(
                path, include, exclude, show_all, folders_only=True
            )
        ) > 1
    except (IOError, OSError):
        return False


class IconProvider(QFileIconProvider):
    """Project tree widget icon provider."""

    def __init__(self, treeview):
        super(IconProvider, self).__init__()
        self.treeview = treeview

    @Slot(int)
    @Slot(QFileInfo)
    def icon(self, icontype_or_qfileinfo):
        """Reimplement Qt method"""
        if isinstance(icontype_or_qfileinfo, QFileIconProvider.IconType):
            return super(IconProvider, self).icon(icontype_or_qfileinfo)
        else:
            qfileinfo = icontype_or_qfileinfo
            fname = osp.normpath(to_text_string(qfileinfo.absoluteFilePath()))
            if osp.isdir(fname):
                return QIcon()  # ima.icon('DirOpenIcon')
            else:
                return QIcon()  # ima.icon('FileIcon')


class FileSystemModel(QFileSystemModel):
    """Subclass Filesystem model to define some initial options."""
    FILTERS = (
        QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot |
        QDir.Hidden
    )

    def __init__(self, *args, **kwargs):
        """Subclass Filesystem model to define some initial options."""
        super(FileSystemModel, self).__init__(*args, **kwargs)
        self.setFilter(self.FILTERS)
        self.setNameFilterDisables(False)

    def data(self, model_index, role):
        """Override Qt method to adjust vertical alignment."""
        value = QFileSystemModel.data(self, model_index, role)
        if role == Qt.TextAlignmentRole:
            return Qt.AlignVCenter
        return value


class DirView(QTreeView):
    """Base file/directory tree view."""
    sig_edit = Signal(str)
    sig_removed = Signal(str)
    sig_removed_tree = Signal(str)
    sig_renamed = Signal(str, str)
    sig_create_module = Signal(str)
    sig_run = Signal(str)
    sig_new_file = Signal(str)
    sig_open_terminal = Signal(str)
    sig_open_interpreter = Signal(str)
    redirect_stdio = Signal(bool)
    sig_add_to_project = Signal(str)

    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.project_path = None
        self.name_filters = ['*.py']
        self.parent_widget = parent
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    # --- Model
    def setup_fs_model(self):
        """Setup filesystem model."""
        # On unix added Hidden to display .projectignore
        self.fsmodel = FileSystemModel(self)

    def install_model(self):
        """Install filesystem model."""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view."""
        self.install_model()
        if not is_pyqt46:
            self.fsmodel.directoryLoaded.connect(
                lambda: self.resizeColumnToContents(0)
            )
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)
        self.fsmodel.modelReset.connect(self.reset_icon_provider)
        self.reset_icon_provider()
        # Disable the view of .spyproject.
        self.filter_directories()

    def set_name_filters(self, name_filters):
        """Set name filters."""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state."""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*."""
        if index:
            return osp.normpath(to_text_string(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename."""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames."""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*."""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    # --- Tree view widget
    def setup(self, name_filters=['*.py', '*.pyw'], show_all=False):
        """Setup tree widget."""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    def reset_icon_provider(self):
        """
        Reset file system model icon provider.

        The purpose of this is to refresh files/directories icons.
        """
        self.fsmodel.setIconProvider(IconProvider(self))

    # --- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions."""
        # Filters
        #        filters_action = create_action(
        #            self,
        #            "Edit filename filters...",
        #            None,
        #            QIcon(),  # ima.icon('filter'),
        #            triggered=self.edit_filter
        #        )
        # Show all files
        all_action = create_action(
            self, "Show all files", toggled=self.toggle_all
        )
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        # return [filters_action, all_action]
        return []

    @Slot()
    def edit_filter(self):
        """Edit name filters."""
        dlg = InputDialog(
            title='Edit filename filters',
            text='Name filters:',
        )

        if dlg.exec_():
            filters = dlg.text.text()
            filters = [f.strip() for f in to_text_string(filters).split(',')]
            self.parent_widget.sig_option_changed.emit('name_filters', filters)
            self.set_name_filters(filters)

    @Slot(bool)
    def toggle_all(self, checked):
        """Toggle all files mode."""
        self.parent_widget.sig_option_changed.emit('show_all', checked)
        self.show_all = checked
        self.set_show_all(checked)

    def create_file_new_actions(self, fnames):
        """Return actions for submenu 'New...'."""
        if not fnames:
            return []
        new_file_act = create_action(
            self,
            "File...",
            icon=QIcon(),  # ima.icon('filenew'),
            triggered=lambda: self.new_file(fnames[-1])
        )
        new_folder_act = create_action(
            self,
            "Folder...",
            icon=QIcon(),  # ima.icon('folder_new'),
            triggered=lambda: self.new_folder(fnames[-1])
        )
        return [new_file_act, new_folder_act]

    def create_file_import_actions(self, fnames):
        """Return actions for submenu 'Import...'."""
        return []

    def create_file_manage_actions(self, fnames):
        """Return file management actions."""
        only_files = all(osp.isfile(_fn) for _fn in fnames)
        fname = fnames[0]
        #        only_modules = all(
        #            [
        #                osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy')
        #                for _fn in fnames
        #            ]
        #        )
        #        only_notebooks = all(
        #            [osp.splitext(_fn)[1] == '.ipynb' for _fn in fnames]
        #        )
        #        only_valid = all([encoding.is_text_file(_fn) for _fn in
        #                          fnames])
        #        run_action = create_action(
        #            self,
        #            "Run",
        #            icon=QIcon(),  # ima.icon('run'),
        #            triggered=self.run,
        #        )
        #        edit_action = create_action(
        #            self,
        #            "Edit",
        #            icon=QIcon(),  # ima.icon('edit'),
        #            triggered=self.clicked,
        #        )
        move_action = create_action(
            self,
            "Move...",
            icon=QIcon(),  # "move.png",
            triggered=self.move,
        )
        delete_action = create_action(
            self,
            "Delete...",
            icon=QIcon(),  # ima.icon('editdelete'),
            triggered=self.delete
        )
        add_to_project_action = create_action(
            self,
            "Add to project...",
            icon=QIcon(),  # ima.icon('rename'),
            triggered=lambda x, fname=fname: self.add_to_project(fname),
        )
        rename_action = create_action(
            self,
            "Rename...",
            icon=QIcon(),  # ima.icon('rename'),
            triggered=self.rename
        )
        #        open_action = create_action(self, "Open", triggered=self.open)
        #        ipynb_convert_action = create_action(
        #            self,
        #            "Convert to Python script",
        #            icon=QIcon(),  # ima.icon('python'),
        #            triggered=self.convert_notebooks
        #        )

        actions = []
        #        if only_modules:
        #            actions.append(run_action)
        #        if only_valid and only_files:
        #            actions.append(edit_action)
        #        else:
        #            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all(fixpath(osp.dirname(_fn)) == basedir for _fn in fnames):
            actions.append(move_action)

        if only_files and os.path.dirname(fname) != self.project_path:
            actions += [None, add_to_project_action]

#        if only_notebooks and nbexporter is not None:
#            actions.append(ipynb_convert_action)

        return actions

    def add_to_project(self, fname):
        self.sig_add_to_project.emit(fname)

    def create_folder_manage_actions(self, fnames):
        """Return folder management actions."""
        actions = []
        # if os.name == 'nt':
        #     _title = "Open command prompt here"
        # else:
        #     _title = "Open terminal here"
        # action = create_action(
        #     self,
        #     _title,
        #     icon=QIcon(),  # ima.icon('cmdprompt'),
        #     triggered=lambda: self.open_terminal(fnames)
        # )
        # actions.append(action)
        # _title = "Open Python console here"
        # action = create_action(
        #     self,
        #     _title,
        #     icon=QIcon(),  # ima.icon('python'),
        #     triggered=lambda: self.open_interpreter(fnames)
        # )
        # actions.append(action)
        return actions

    def create_context_menu_actions(self):
        """Create context menu actions."""
        actions = []
        fnames = self.get_selected_filenames()
        new_actions = self.create_file_new_actions(fnames)
        if len(new_actions) > 1:
            # Creating a submenu only if there is more than one entry
            new_act_menu = QMenu('New', self)
            add_actions(new_act_menu, new_actions)
            actions.append(new_act_menu)
        else:
            actions += new_actions
        import_actions = self.create_file_import_actions(fnames)
        if len(import_actions) > 1:
            # Creating a submenu only if there is more than one entry
            import_act_menu = QMenu('Import', self)
            add_actions(import_act_menu, import_actions)
            actions.append(import_act_menu)
        else:
            actions += import_actions
        if actions:
            actions.append(None)
        if fnames:
            actions += self.create_file_manage_actions(fnames)
        if actions:
            actions.append(None)
        if fnames and all(osp.isdir(_fn) for _fn in fnames):
            actions += self.create_folder_manage_actions(fnames)
        if actions:
            actions.append(None)
        actions += self.common_actions
        return actions

    def update_menu(self):
        """Update context menu"""
        self.menu.clear()
        add_actions(self.menu, self.create_context_menu_actions())

    # --- Events
    def viewportEvent(self, event):
        """Reimplement Qt method"""
        # Prevent Qt from crashing or showing warnings like:
        # "QSortFilterProxyModel: index from wrong model passed to
        # mapFromSource", probably due to the fact that the file system model
        # is being built. See Issue 1250.
        #
        # This workaround was inspired by the following KDE bug:
        # https://bugs.kde.org/show_bug.cgi?id=172198
        #
        # Apparently, this is a bug from Qt itself.
        self.executeDelayedItemsLayout()

        return QTreeView.viewportEvent(self, event)

    def contextMenuEvent(self, event):
        """Override Qt method"""
        self.update_menu()
        self.menu.popup(event.globalPos())

    def keyPressEvent(self, event):
        """Reimplement Qt method."""
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.clicked()
        elif event.key() == Qt.Key_F2:
            self.rename()
        elif event.key() == Qt.Key_Delete:
            self.delete()
        elif event.key() == Qt.Key_Backspace:
            self.go_to_parent_directory()
        else:
            QTreeView.keyPressEvent(self, event)

    def mouseDoubleClickEvent(self, event):
        """Reimplement Qt method."""
        QTreeView.mouseDoubleClickEvent(self, event)
        self.clicked()

    @Slot()
    def clicked(self):
        """Selected item was double-clicked or enter/return was pressed."""
        fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isdir(fname):
                self.directory_clicked(fname)
            else:
                self.open([fname])

    def directory_clicked(self, dirname):
        """Directory was just clicked."""
        pass

    # --- Drag
    def dragEnterEvent(self, event):
        """Drag and Drop - Enter event."""
        event.setAccepted(event.mimeData().hasFormat("text/plain"))

    def dragMoveEvent(self, event):
        """Drag and Drop - Move event."""
        if (event.mimeData().hasFormat("text/plain")):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, dropActions):
        """Reimplement Qt Method - handle drag event."""
        data = QMimeData()
        data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
        drag = QDrag(self)
        drag.setMimeData(data)
        drag.exec_()

    # --- File/Directory actions
    @Slot()
    def open(self, fnames=None):
        """Open files with the appropriate application."""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isfile(fname) and encoding.is_text_file(fname):
                self.parent_widget.sig_open_file.emit(fname)
            else:
                self.open_outside_spyder([fname])

    def open_outside_spyder(self, fnames):
        """
        Open file outside Spyder with the appropriate application.

        If this does not work, opening unknown file in Spyder, as text file.
        """
        for path in sorted(fnames):
            path = file_uri(path)
            ok = programs.start_file(path)
            if not ok:
                self.sig_edit.emit(path)

    def open_terminal(self, fnames):
        """Open terminal."""
        for path in sorted(fnames):
            self.sig_open_terminal.emit(path)

    def open_interpreter(self, fnames):
        """Open interpreter."""
        for path in sorted(fnames):
            self.sig_open_interpreter.emit(path)

    @Slot()
    def run(self, fnames=None):
        """Run Python scripts."""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.sig_run.emit(fname)

    def remove_tree(self, dirname):
        """
        Remove whole directory tree.

        Reimplemented in project explorer widget.
        """
        shutil.rmtree(dirname, onerror=misc.onerror)

    def delete_file(self, fname, multiple, yes_to_all):
        """Delete file."""
        # if multiple:
        #     buttons = (
        #         QMessageBox.Yes | QMessageBox.YesAll | QMessageBox.No |
        #         QMessageBox.Cancel
        #        )
        # else:
        #     buttons = QMessageBox.Yes | QMessageBox.No
        msg_box = MessageBoxQuestion(
            title="Delete",
            text="Do you really want to delete "
            "<b>{0}</b>?".format(osp.basename(fname)),
        )

        if msg_box.exec_():
            yes_to_all = True
        else:
            return False

#            if answer == QMessageBox.No:
#                return yes_to_all
#            elif answer == QMessageBox.Cancel:
#                return False
#            elif answer == QMessageBox.YesAll:
#                yes_to_all = True
        try:
            if osp.isfile(fname):
                misc.remove_file(fname)
                self.sig_removed.emit(fname)
            else:
                self.remove_tree(fname)
                self.sig_removed_tree.emit(fname)
            return yes_to_all
        except EnvironmentError as error:
            action_str = 'delete'
            msg_box = MessageBoxError(
                text="<b>Unable to %s <i>%s</i></b>"
                "<br><br>Error message:<br>%s" %
                (action_str, fname, to_text_string(error)),
                title='Project Explorer',
            )
            msg_box.exec_()
        return False

    @Slot()
    def delete(self, fnames=None):
        """Delete files."""
        if fnames is None:
            fnames = self.get_selected_filenames()
        multiple = len(fnames) > 1
        yes_to_all = None
        for fname in fnames:
            yes_to_all = self.delete_file(fname, multiple, yes_to_all)
            if yes_to_all is not None and not yes_to_all:
                # Canceled
                break

    def convert_notebook(self, fname):
        """Convert an IPython notebook to a Python script in editor."""
        try:
            script = nbexporter().from_filename(fname)[0]
        except Exception as e:
            msg_box = MessageBoxError(
                text="It was not possible to convert this "
                "notebook. The error is:\n\n" + to_text_string(e),
                title='Conversion error',
            )
            msg_box.exec_()
            return
        self.sig_new_file.emit(script)

    @Slot()
    def convert_notebooks(self):
        """Convert IPython notebooks to Python scripts in editor."""
        fnames = self.get_selected_filenames()
        if not isinstance(fnames, (tuple, list)):
            fnames = [fnames]
        for fname in fnames:
            self.convert_notebook(fname)

    def rename_file(self, fname):
        """Rename file."""
        dlg = InputDialog(
            title='Rename',
            text='New name:',
            value=osp.basename(fname),
        )
        if dlg.exec_():
            path = dlg.text.text()
            path = osp.join(osp.dirname(fname), to_text_string(path))
            if path == fname:
                return
            if osp.exists(path):
                msg_box = MessageBoxQuestion(
                    self,
                    title="Rename",
                    text="Do you really want to rename <b>%s</b> and "
                    "overwrite the existing file <b>%s</b>?" %
                    (osp.basename(fname), osp.basename(path)),
                )
                if not msg_box.exec_():
                    return
            try:
                misc.rename_file(fname, path)
                self.sig_renamed.emit(fname, path)
                return path
            except EnvironmentError as error:
                msg_box = MessageBoxError(
                    text="<b>Unable to rename file <i>%s</i></b>"
                    "<br><br>Error message:<br>%s" %
                    (osp.basename(fname), to_text_string(error)),
                    title='Rename error',
                )
                msg_box.exec_()

    @Slot()
    def rename(self, fnames=None):
        """Rename files."""
        if fnames is None:
            fnames = self.get_selected_filenames()
        if not isinstance(fnames, (tuple, list)):
            fnames = [fnames]
        for fname in fnames:
            self.rename_file(fname)

    @Slot()
    def move(self, fnames=None):
        """Move files/directories."""
        if fnames is None:
            fnames = self.get_selected_filenames()
        orig = fixpath(osp.dirname(fnames[0]))
        while True:
            self.redirect_stdio.emit(False)
            folder = getexistingdirectory(self, "Select directory", orig)
            self.redirect_stdio.emit(True)
            if folder:
                folder = fixpath(folder)
                if folder != orig:
                    break
            else:
                return
        for fname in fnames:
            basename = osp.basename(fname)
            try:
                misc.move_file(fname, osp.join(folder, basename))
            except EnvironmentError as error:
                msg_box = MessageBoxError(
                    text="<b>Unable to move <i>%s</i></b>"
                    "<br><br>Error message:<br>%s" %
                    (basename, to_text_string(error)),
                    title='Error',
                )
                msg_box.exec_()

    def create_new_folder(self, current_path, title, subtitle, is_package):
        """Create new folder."""
        if current_path is None:
            current_path = ''
        if osp.isfile(current_path):
            current_path = osp.dirname(current_path)

        dlg = InputDialog(title=title, text=subtitle, value='')
        if dlg.exec_():
            name = dlg.text.text()
            dirname = osp.join(current_path, to_text_string(name))
            try:
                os.mkdir(dirname)
            except EnvironmentError as error:
                msg_box = MessageBoxError(
                    text="<b>Unable "
                    "to create folder <i>%s</i></b>"
                    "<br><br>Error message:<br>%s" %
                    (dirname, to_text_string(error)),
                    title=title,
                )
                msg_box.exec_()
            finally:
                if is_package:
                    fname = osp.join(dirname, '__init__.py')
                    try:
                        with open(fname, 'wb') as f:
                            f.write(to_binary_string('#'))
                        return dirname
                    except EnvironmentError as error:
                        msg_box = MessageBoxError(
                            text="<b>Unable "
                            "to create file <i>%s</i></b>"
                            "<br><br>Error message:<br>%s" %
                            (fname, to_text_string(error)),
                            title=title,
                        )
                        msg_box.exec_()

    def new_folder(self, basedir):
        """New folder."""
        title = 'New folder'
        subtitle = 'Folder name:'
        self.create_new_folder(basedir, title, subtitle, is_package=False)

    def new_package(self, basedir):
        """New package."""
        title = 'New package'
        subtitle = 'Package name:'
        self.create_new_folder(basedir, title, subtitle, is_package=True)

    def create_new_file(self, current_path, title, filters, create_func):
        """
        Create new file.

        Returns True if successful.
        """
        if current_path is None:
            current_path = ''
        if osp.isfile(current_path):
            current_path = osp.dirname(current_path)
        self.redirect_stdio.emit(False)
        fname, _selfilter = getsavefilename(self, title, current_path, filters)
        self.redirect_stdio.emit(True)
        if fname:
            try:
                create_func(fname)
                return fname
            except EnvironmentError as error:
                msg_box = MessageBoxError(
                    text="<b>Unable to create file <i>%s</i>"
                    "</b><br><br>Error message:<br>%s" %
                    (fname, to_text_string(error)),
                    title='New file error',
                )
                msg_box.exec_()

    def new_file(self, basedir):
        """New file."""
        title = "New file"
        filters = "All files" + " (*)"

        def create_func(fname):
            """File creation callback."""
            if osp.splitext(fname)[1] in ('.py', '.pyw', '.ipy'):
                create_script(fname)
            else:
                with open(fname, 'wb') as f:
                    f.write(to_binary_string(''))

        fname = self.create_new_file(basedir, title, filters, create_func)
        if fname is not None:
            self.open([fname])

    def new_module(self, basedir):
        """New module."""
        title = "New module"
        filters = "Python scripts" + " (*.py *.pyw *.ipy)"

        def create_func(fname):
            self.sig_create_module.emit(fname)

        self.create_new_file(basedir, title, filters, create_func)

    def go_to_parent_directory(self):
        pass

    # ---- Settings
    def get_scrollbar_position(self):
        """Return scrollbar positions"""
        return (
            self.horizontalScrollBar().value(),
            self.verticalScrollBar().value()
        )

    def set_scrollbar_position(self, position):
        """Set scrollbar positions"""
        # Scrollbars will be restored after the expanded state
        self._scrollbar_positions = position
        if self._to_be_loaded is not None and len(self._to_be_loaded) == 0:
            self.restore_scrollbar_positions()

    def restore_scrollbar_positions(self):
        """Restore scrollbar positions once tree is loaded"""
        hor, ver = self._scrollbar_positions
        self.horizontalScrollBar().setValue(hor)
        self.verticalScrollBar().setValue(ver)

    def get_expanded_state(self):
        """Return expanded state"""
        self.save_expanded_state()
        return self.__expanded_state

    def set_expanded_state(self, state):
        """Set expanded state"""
        self.__expanded_state = state
        self.restore_expanded_state()

    def save_expanded_state(self):
        """Save all items expanded state"""
        model = self.model()
        # If model is not installed, 'model' will be None: this happens when
        # using the Project Explorer without having selected a workspace yet
        if model is not None:
            self.__expanded_state = []
            for idx in model.persistentIndexList():
                if self.isExpanded(idx):
                    self.__expanded_state.append(self.get_filename(idx))

    def restore_directory_state(self, fname):
        """Restore directory expanded state"""
        root = osp.normpath(to_text_string(fname))
        if not osp.exists(root):
            # Directory has been (re)moved outside Spyder
            return
        for basename in os.listdir(root):
            path = osp.normpath(osp.join(root, basename))
            if osp.isdir(path) and path in self.__expanded_state:
                self.__expanded_state.pop(self.__expanded_state.index(path))
                if self._to_be_loaded is None:
                    self._to_be_loaded = []
                self._to_be_loaded.append(path)
                self.setExpanded(self.get_index(path), True)
        if not self.__expanded_state and not is_pyqt46:
            self.fsmodel.directoryLoaded.disconnect(
                self.restore_directory_state
            )

    def follow_directories_loaded(self, fname):
        """Follow directories loaded during startup"""
        if self._to_be_loaded is None:
            return
        path = osp.normpath(to_text_string(fname))
        if path in self._to_be_loaded:
            self._to_be_loaded.remove(path)
        if (self._to_be_loaded is not None and len(self._to_be_loaded) == 0 and
                not is_pyqt46):
            self.fsmodel.directoryLoaded.disconnect(
                self.follow_directories_loaded
            )
            if self._scrollbar_positions is not None:
                # The tree view need some time to render branches:
                QTimer.singleShot(50, self.restore_scrollbar_positions)

    def restore_expanded_state(self):
        """Restore all items expanded state"""
        if self.__expanded_state is not None:
            # In the old explorer, the expanded state was a dictionnary:
            if isinstance(self.__expanded_state, list) and not is_pyqt46:
                self.fsmodel.directoryLoaded.connect(
                    self.restore_directory_state
                )
                self.fsmodel.directoryLoaded.connect(
                    self.follow_directories_loaded
                )

    def filter_directories(self):
        """Filter the directories to show"""
        index = self.get_index('.spyproject')
        if index is not None:
            self.setRowHidden(index.row(), index.parent(), True)


class ProxyModel(QSortFilterProxyModel):
    """Proxy model: filters tree view"""

    def __init__(self, parent):
        super(ProxyModel, self).__init__(parent)
        self.root_path = None
        self.path_list = []
        self.setDynamicSortFilter(True)

    def setup_filter(self, root_path, path_list):
        """Setup proxy model filter parameters"""
        self.root_path = osp.normpath(to_text_string(root_path))
        self.path_list = [osp.normpath(to_text_string(p)) for p in path_list]
        self.invalidateFilter()

    def sort(self, column, order=Qt.AscendingOrder):
        """Reimplement Qt method"""
        self.sourceModel().sort(column, order)

    def filterAcceptsRow(self, row, parent_index):
        """Reimplement Qt method"""
        if self.root_path is None:
            return True
        index = self.sourceModel().index(row, 0, parent_index)
        path = osp.normpath(to_text_string(self.sourceModel().filePath(index)))
        if self.root_path.startswith(path):
            # This is necessary because parent folders need to be scanned
            return True
        else:
            for p in self.path_list:
                if path == p or path.startswith(p + os.sep):
                    return True
            else:
                return False

    def data(self, index, role):
        """Show tooltip with full path only for the root directory"""
        if role == Qt.ToolTipRole:
            root_dir = self.path_list[0].split(osp.sep)[-1]
            if index.data() == root_dir:
                return osp.join(self.root_path, root_dir)
        return QSortFilterProxyModel.data(self, index, role)


class FilteredDirView(DirView):
    """Filtered file/directory tree view"""

    def __init__(self, parent=None):
        super(FilteredDirView, self).__init__(parent)
        self.proxymodel = None
        self.setup_proxy_model()
        self.root_path = None

    # --- Model
    def setup_proxy_model(self):
        """Setup proxy model"""
        self.proxymodel = ProxyModel(self)
        self.proxymodel.setSourceModel(self.fsmodel)

    def install_model(self):
        """Install proxy model"""
        if self.root_path is not None:
            self.setModel(self.proxymodel)

    def set_root_path(self, root_path):
        """Set root path"""
        self.root_path = root_path
        self.install_model()
        index = self.fsmodel.setRootPath(root_path)
        self.setRootIndex(self.proxymodel.mapFromSource(index))

    def get_index(self, filename):
        """Return index associated with filename"""
        index = self.fsmodel.index(filename)
        if index.isValid() and index.model() is self.fsmodel:
            return self.proxymodel.mapFromSource(index)

    def set_folder_names(self, folder_names):
        """Set folder names"""
        assert self.root_path is not None
        path_list = [
            osp.join(self.root_path, dirname) for dirname in folder_names
        ]
        self.proxymodel.setup_filter(self.root_path, path_list)

    def get_filename(self, index):
        """Return filename from index"""
        if index:
            path = self.fsmodel.filePath(self.proxymodel.mapToSource(index))
            return osp.normpath(to_text_string(path))

    def setup_project_view(self):
        """Setup view for projects"""
        for i in [1, 2, 3]:
            self.hideColumn(i)
        self.setHeaderHidden(True)
        # Disable the view of .spyproject.
        self.filter_directories()


class ExplorerTreeWidget(DirView):
    """
    File/directory explorer tree widget.

    show_cd_only: Show current directory only
    (True/False: enable/disable the option
    None: enable the option and do not allow the user to disable it).
    """
    set_previous_enabled = Signal(bool)
    set_next_enabled = Signal(bool)
    sig_open_dir = Signal(str)
    sig_changed_dir = Signal()

    def __init__(self, parent=None, show_cd_only=None):
        DirView.__init__(self, parent)

        self.history = []
        self.histindex = None

        self.show_cd_only = show_cd_only
        self.__original_root_index = None
        self.__last_folder = None

        self.menu = None
        self.common_actions = None

        # Enable drag events
        self.setDragEnabled(True)

    # --- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions."""
        actions = super(ExplorerTreeWidget, self).setup_common_actions()
        if self.show_cd_only is None:
            # Enabling the 'show current directory only' option but do not
            # allow the user to disable it
            self.show_cd_only = True
        else:
            # Show current directory only
            cd_only_action = create_action(
                self,
                "Show current directory only",
                toggled=self.toggle_show_cd_only
            )
            cd_only_action.setChecked(self.show_cd_only)
            self.toggle_show_cd_only(self.show_cd_only)
            actions.append(cd_only_action)
        return actions

    @Slot(bool)
    def toggle_show_cd_only(self, checked):
        """Toggle show current directory only mode."""
        self.parent_widget.sig_option_changed.emit('show_cd_only', checked)
        self.show_cd_only = checked
        if checked:
            if self.__last_folder is not None:
                self.set_current_folder(self.__last_folder)
        elif self.__original_root_index is not None:
            self.setRootIndex(self.__original_root_index)

    # --- Refreshing widget
    def set_current_folder(self, folder):
        """Set current folder and return associated model index."""
        index = self.fsmodel.setRootPath(folder)
        self.__last_folder = folder
        if self.show_cd_only:
            if self.__original_root_index is None:
                self.__original_root_index = self.rootIndex()
            self.setRootIndex(index)
        return index

    def refresh(self, new_path=None, force_current=False):
        """
        Refresh widget.

        force=False: won't refresh widget if path has not changed.
        """
        if new_path is None:
            new_path = getcwd()
        if force_current:
            index = self.set_current_folder(new_path)
            self.expand(index)
            self.setCurrentIndex(index)
        self.set_previous_enabled.emit(
            self.histindex is not None and self.histindex > 0
        )
        self.set_next_enabled.emit(
            self.histindex is not None and
            self.histindex < len(self.history) - 1
        )
        # Disable the view of .spyproject.
        self.filter_directories()

    # --- Events
    def directory_clicked(self, dirname):
        """Directory was just clicked."""
        self.chdir(directory=dirname)

    # --- Files/Directories Actions
    @Slot()
    def go_to_parent_directory(self):
        """Go to parent directory."""
        self.chdir(osp.abspath(osp.join(getcwd(), os.pardir)))

    @Slot()
    def go_to_previous_directory(self):
        """Back to previous directory."""
        self.histindex -= 1
        self.chdir(browsing_history=True)

    @Slot()
    def go_to_next_directory(self):
        """Return to next directory."""
        self.histindex += 1
        self.chdir(browsing_history=True)

    def update_history(self, directory):
        """Update browse history."""
        directory = osp.abspath(to_text_string(directory))
        if directory in self.history:
            self.histindex = self.history.index(directory)

    def chdir(self, directory=None, browsing_history=False):
        """Set directory as working directory."""
        if directory is not None:
            directory = osp.abspath(to_text_string(directory))
        if browsing_history:
            directory = self.history[self.histindex]
        elif directory in self.history:
            self.histindex = self.history.index(directory)
        else:
            if self.histindex is None:
                self.history = []
            else:
                self.history = self.history[:self.histindex + 1]
            if len(self.history) == 0 or \
               (self.history and self.history[-1] != directory):
                self.history.append(directory)
            self.histindex = len(self.history) - 1
        directory = to_text_string(directory)
        #        if PY2:
        #            PermissionError = OSError
        try:
            os.chdir(directory)
            self.sig_open_dir.emit(directory)
            self.refresh(new_path=directory, force_current=True)
        except OSError:
            #        except PermissionError:
            msg_box = MessageBoxError(
                text="You don't have the right permissions to "
                "open this directory",
                title='Error',
            )
            msg_box.exec_()
        self.sig_changed_dir.emit()


class ExplorerWidget(QWidget):
    """Explorer widget."""
    sig_option_changed = Signal(str, object)
    sig_open_file = Signal(str)
    sig_add_to_project = Signal(str)
    open_dir = Signal(str)

    def __init__(
        self,
        parent=None,
        name_filters=['*.py', '*.pyw'],
        show_all=True,
        show_cd_only=None,
        show_icontext=False,
        home=None,
    ):
        """Explorer widget."""
        QWidget.__init__(self, parent)

        self.home = home

        # Widgets
        self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only)
        button_home = QToolButton(self)
        self.label_breadcrumb = QLabel()

        home_action = create_action(
            self,
            text="Home",
            icon=QIcon(),  # ima.icon('ArrowBack'),
            triggered=self.go_home
        )

        # Setup widgets
        self.treewidget.setup(name_filters=name_filters, show_all=show_all)
        self.treewidget.chdir(getcwd())

        button_home.setDefaultAction(home_action)

        # Layouts
        blayout = QHBoxLayout()
        blayout.addWidget(button_home)
        blayout.addWidget(self.label_breadcrumb)
        blayout.addStretch()

        layout = QVBoxLayout()
        layout.addLayout(blayout)
        layout.addWidget(self.treewidget)
        self.setLayout(layout)

        # Signals and slots
        self.treewidget.sig_add_to_project.connect(self.sig_add_to_project)
        self.treewidget.sig_changed_dir.connect(self.update_breadcrumb)
        self.label_breadcrumb.linkActivated.connect(self.go_to)

        self.update_breadcrumb()

    def go_to(self, path):
        """Got to breadcrumb path."""
        self.treewidget.chdir(path)
        self.update_breadcrumb()

    def update_breadcrumb(self, path=None):
        """Update the breadcrumb naviagtion."""
        path = path or getcwd()
        parts = path.split(os.path.sep)
        text = '<style>a{color:#43b02a;}</style>'
        cum_path = ''
        for p in parts:
            cum_path += p + os.path.sep
            text += '<a href="{link}">{p}</a>'.format(p=p, link=cum_path)
            text += '&nbsp;' + os.path.sep + '&nbsp;'
        self.label_breadcrumb.setText(text)

    def set_current_folder(self, path):
        """Set the current folder."""
        self.treewidget.set_current_folder(path)
        self.treewidget.chdir(path)
        self.treewidget.project_path = path
        self.update_breadcrumb()

    def set_home(self, home):
        """Set the editor home."""
        self.home = home

    def go_home(self):
        """Set treewidget to project folder (home)."""
        if self.home and os.path.isdir(self.home):
            self.treewidget.set_current_folder(self.home)
            self.update_breadcrumb(self.home)

    @Slot(bool)
    def toggle_icontext(self, state):
        """Toggle icon text."""
        self.sig_option_changed.emit('show_icontext', state)
        for widget in self.action_widgets:
            if widget is not self.button_menu:
                if state:
                    widget.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
                else:
                    widget.setToolButtonStyle(Qt.ToolButtonIconOnly)


# -----------------------------------------------------------------------------
# --- Tests
# -----------------------------------------------------------------------------
class FileExplorerTest(QWidget):
    """Test widget."""

    def __init__(self):
        """Test widget."""
        QWidget.__init__(self)
        vlayout = QVBoxLayout()
        self.setLayout(vlayout)
        self.explorer = ExplorerWidget(self, show_cd_only=None)
        vlayout.addWidget(self.explorer)

        hlayout1 = QHBoxLayout()
        vlayout.addLayout(hlayout1)
        label = QLabel("<b>Open file:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout1.addWidget(label)
        self.label1 = QLabel()
        hlayout1.addWidget(self.label1)
        self.explorer.sig_open_file.connect(self.label1.setText)

        hlayout2 = QHBoxLayout()
        vlayout.addLayout(hlayout2)
        label = QLabel("<b>Open dir:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout2.addWidget(label)
        self.label2 = QLabel()
        hlayout2.addWidget(self.label2)
        self.explorer.open_dir.connect(self.label2.setText)

        hlayout3 = QHBoxLayout()
        vlayout.addLayout(hlayout3)
        label = QLabel("<b>Option changed:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout3.addWidget(label)
        self.label3 = QLabel()
        hlayout3.addWidget(self.label3)
        self.explorer.sig_option_changed.connect(
            lambda x, y: self.label3.
            setText('option_changed: %r, %r' % (x, y))
        )
        self.explorer.open_dir.connect(
            lambda: self.explorer.treewidget.refresh('..')
        )


class ProjectExplorerTest(QWidget):
    """Test widget."""

    def __init__(self, parent=None):
        """Test widget."""
        QWidget.__init__(self, parent)
        vlayout = QVBoxLayout()
        self.setLayout(vlayout)
        self.treewidget = FilteredDirView(self)
        self.treewidget.setup_view()
        self.treewidget.set_root_path(osp.dirname(osp.abspath(__file__)))
        self.treewidget.set_folder_names(['variableexplorer'])
        self.treewidget.setup_project_view()
        vlayout.addWidget(self.treewidget)


def local_test(file_explorer):
    """Local file explorer test."""
    from spyder.utils.qthelpers import qapplication
    app = qapplication()
    if file_explorer:
        test = FileExplorerTest()
    else:
        test = ProjectExplorerTest()
    test.resize(640, 480)
    test.show()
    app.exec_()


if __name__ == "__main__":
    local_test(file_explorer=True)
    local_test(file_explorer=False)
