<commit_before>"""
This module contains the splittable tab widget API
"""
import inspect
import logging
import mimetypes
import os
import uuid
from pyqode.qt import QtCore, QtWidgets, QtGui
from pyqode.core.api import utils, CodeEdit
from pyqode.core.dialogs import DlgUnsavedFiles
from pyqode.core._forms import popup_open_files_ui
from .tab_bar import TabBar
from .code_edits import GenericCodeEdit, TextCodeEdit


def _logger():
    return logging.getLogger(__name__)


class DraggableTabBar(TabBar):
    """
    A draggable tab bar that allow to drag & drop tabs.

    Implementation is based on this qt article:
    http://www.qtcentre.org/wiki/index.php?title=Movable_Tabs
    """
    #: Signal emitted when a tab must be moved to the specified
    #: index (the tab might come from another tab bar (split)).
    tab_move_request = QtCore.Signal(QtWidgets.QWidget, int)

    def __init__(self, parent):
        super(DraggableTabBar, self).__init__(parent)
        self._pos = QtCore.QPoint()
        self.setAcceptDrops(True)
        self.setMouseTracking(True)
        self.setElideMode(QtCore.Qt.ElideNone)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self._pos = event.pos()  # _pos is a QPoint defined in the header
        super(DraggableTabBar, self).mousePressEvent(event)

    def widget_under_mouse(self, event):
        index = self.tabAt(event.pos())
        tab = self.parent().widget(index)
        return tab

    def mouseMoveEvent(self, event):
        # update tooltip with the tooltip of the tab under mouse cursor.
        tab = self.widget_under_mouse(event)
        if tab is not None:
            tooltip = tab.toolTip()
            if not tooltip:
                try:
                    tooltip = tab.file.path
                except AttributeError:
                    pass
            self.setToolTip(tooltip)

        # If the distance is too small then return
        if (event.pos() - self._pos).manhattanLength() < \
                QtWidgets.QApplication.startDragDistance():
            return

        # If the left button isn't pressed anymore then return
        if not event.buttons() & QtCore.Qt.LeftButton:
            return

        drag = QtGui.QDrag(self)
        data = QtCore.QMimeData()
        data.tab = tab
        data.widget = self
        # a crude way to distinguish tab-reodering drags from other drags
        data.setData("action", "tab-reordering")
        drag.setMimeData(data)
        drag.setPixmap(self.tabIcon(self.tabAt(event.pos())).pixmap(32, 32))
        drag.exec_()

    def dragEnterEvent(self, event):
        # Only accept if it's an tab-reordering request
        m = event.mimeData()
        formats = m.formats()
        if "action" in formats and m.data("action") == "tab-reordering":
            event.acceptProposedAction()

    def dropEvent(self, event):
        # drop a tab in a split (may be the same split or another one).
        m = event.mimeData()
        index = self.tabAt(event.pos())
        # Tell interested objects that a tab should be moved.
        if m.tab != self.parent().widget(index):
            self.tab_move_request.emit(m.tab, index)
        event.acceptProposedAction()


class BaseTabWidget(QtWidgets.QTabWidget):
    """
    Base tab widget class used by SplittableTabWidget. This tab widget adds a
    context menu to the tab bar that allow the user to:
        - split the current tab (horizontally or vertically)
        - close the current tab
        - close all tabs
        - close all other tabs
    """
    #: Signal emitted when the last tab has been closed
    last_tab_closed = QtCore.Signal()

    #: Signal emitted when a tab has been closed
    tab_closed = QtCore.Signal(QtWidgets.QWidget)

    #: Signal emitted when the user clicked on split vertical or split
    #: horizontal
    #: **Parameters**:
    #: - widget: the widget to split
    #: - orientation: split orientation (horizontal/vertical)
    split_requested = QtCore.Signal(QtWidgets.QWidget, int)

    def __init__(self, parent):
        super(BaseTabWidget, self).__init__(parent)
        self._current = None
        self.currentChanged.connect(self._on_current_changed)
        self.tabCloseRequested.connect(self._on_tab_close_requested)

        tab_bar = DraggableTabBar(self)
        tab_bar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        tab_bar.customContextMenuRequested.connect(self._show_tab_context_menu)
        tab_bar.tab_move_request.connect(self._on_tab_move_request)
        self.setTabBar(tab_bar)
        self.setAcceptDrops(True)
        self.setUsesScrollButtons(True)

        #: A list of additional context menu actions
        self.context_actions = []

    def tab_under_menu(self):
        """
        Returns the tab that sits under the context menu.
        :return: QWidget
        """
        return self.tabBar().tabAt(self._menu_pos)

    @QtCore.Slot()
    def close(self):
        """
        Closes the active editor
        """
        self.tabCloseRequested.emit(self.tab_under_menu())

    @QtCore.Slot()
    def close_others(self):
        """
        Closes every editors tabs except the current one.
        """
        current_widget = self.widget(self.tab_under_menu())
        self._try_close_dirty_tabs(exept=current_widget)
        i = 0
        while self.count() > 1:
            widget = self.widget(i)
            if widget != current_widget:
                self.remove_tab(i)
            else:
                i = 1

    @QtCore.Slot()
    def close_all(self):
        """
        Closes all editors
        """
        if self._try_close_dirty_tabs():
            while self.count():
                widget = self.widget(0)
                self.remove_tab(0)
                self.tab_closed.emit(widget)
            return True
        return False

    def save_widget(self, editor):
        """
        Saves the widget. The base implementation does nothing.

        The function must return a bool that tells whether the save succeeded
        or not.

        :param editor: editor widget to save.
        """
        return True

    def _create_tab_bar_menu(self):
        context_mnu = QtWidgets.QMenu()
        for action in self.context_actions:
            context_mnu.addAction(action)
        if self.context_actions:
            context_mnu.addSeparator()
        menu = QtWidgets.QMenu('Split', context_mnu)
        menu.setIcon(QtGui.QIcon.fromTheme('split'))
        a = menu.addAction('Split horizontally')
        a.triggered.connect(self._on_split_requested)
        a.setIcon(QtGui.QIcon.fromTheme('view-split-left-right'))
        a = menu.addAction('Split vertically')
        a.setIcon(QtGui.QIcon.fromTheme('view-split-top-bottom'))
        a.triggered.connect(self._on_split_requested)
        context_mnu.addMenu(menu)
        context_mnu.addSeparator()
        for name, slot in [('Close', self.close),
                           ('Close others', self.close_others),
                           ('Close all', self.close_all)]:
            qaction = QtWidgets.QAction(name, self)
            qaction.triggered.connect(slot)
            context_mnu.addAction(qaction)
            self.addAction(qaction)
        self._context_mnu = context_mnu
        return context_mnu

    def _show_tab_context_menu(self, position):
        if self.count():
            self._menu_pos = position
            SplittableTabWidget.tab_under_menu = self.widget(
                self.tab_under_menu())
            self._create_tab_bar_menu().popup(self.tabBar().mapToGlobal(
                position))

    def _collect_dirty_tabs(self, skip=None):
        """
        Collects the list of dirty tabs

        :param skip: Tab to skip (used for close_others).
        """
        widgets = []
        filenames = []
        for i in range(self.count()):
            widget = self.widget(i)
            try:
                if widget.dirty and widget != skip:
                    widgets.append(widget)
                    filenames.append(widget.file.path)
            except AttributeError:
                pass
        return widgets, filenames

    def _try_close_dirty_tabs(self, exept=None):
        """
        Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user
        what he wants to do.
        """
        widgets, filenames = self._collect_dirty_tabs(skip=exept)
        if not len(filenames):
            return True
        dlg = DlgUnsavedFiles(self, files=filenames)
        if dlg.exec_() == dlg.Accepted:
            if not dlg.discarded:
                for item in dlg.listWidget.selectedItems():
                    filename = item.text()
                    widget = None
                    for widget in widgets:
                        if widget.path == filename:
                            break
                    if widget != exept:
                        self.save_widget(widget)
                        self.remove_tab(self.indexOf(widget))
            return True
        return False

    def _get_widget_path(self, widget):
        try:
            return widget.path
        except AttributeError:
            return ''

    def _on_tab_close_requested(self, index):
        widget = self.widget(index)
        dirty = False
        try:
            if widget.original is None:
                dirty = widget.dirty
        except AttributeError:
            pass
        if not dirty:
            self.remove_tab(index)
        else:
            # unsaved widget
            path = self._get_widget_path(widget)
            if not path:
                path = self.tabText(self.indexOf(widget))
            dlg = DlgUnsavedFiles(
                self, files=[path])
            if dlg.exec_() == dlg.Accepted:
                rm = True
                if not dlg.discarded:
                    try:
                        rm = self.save_widget(widget)
                    except OSError:
                        pass
                if rm:
                    self.remove_tab(index)
                    widget.close()
                    widget.setParent(None)
                    del widget

    @staticmethod
    def _close_widget(widget):
        """
        Closes the given widgets and handles cases where the widget has been
        clone or is a clone of another widget
        """
        if widget is None:
            return
        # handled cloned widgets
        clones = []
        if hasattr(widget, 'original') and widget.original:
            # cloned widget needs to be removed from the original
            widget.original.clones.remove(widget)
            try:
                widget.setDocument(None)
            except AttributeError:
                # not a QTextEdit/QPlainTextEdit
                pass
        elif hasattr(widget, 'clones'):
            clones = widget.clones
        try:
            # only clear current editor if it does not have any other clones
            widget.close(clear=len(clones) == 0)
        except (AttributeError, TypeError):
            # not a CodeEdit
            widget.close()
        return clones

    def _restore_original(self, clones):
        try:
            first = clones[0]
        except (IndexError, TypeError):
            # empty or None
            pass
        else:
            first.clones = clones[1:]
            first.original = None
            for c in first.clones:
                c.original = first

    def remove_tab(self, index):
        """
        Overrides removeTab to emit tab_closed and last_tab_closed signals.

        :param index: index of the tab to remove.
        """
        widget = self.widget(index)
        clones = self._close_widget(widget)
        self.tab_closed.emit(widget)
        self.removeTab(index)
        self._restore_original(clones)
        widget._original_tab_widget._tabs.remove(widget)
        if self.count() == 0:
            self.last_tab_closed.emit()

    def _on_split_requested(self):
        """
        Emits the split requested signal with the desired orientation.
        """
        orientation = self.sender().text()
        widget = self.widget(self.tab_under_menu())
        if 'horizontally' in orientation:
            self.split_requested.emit(
                widget, QtCore.Qt.Horizontal)
        else:
            self.split_requested.emit(
                widget, QtCore.Qt.Vertical)

    def _on_current_changed(self, index):
        tab = self.widget(index)
        if tab:
            tab.setFocus()

    def _on_tab_move_request(self, widget, new_index):
        parent = widget.parent_tab_widget
        index = parent.indexOf(widget)
        text = parent.tabText(index)
        icon = parent.tabIcon(index)
        parent.removeTab(index)
        widget.parent_tab_widget = self
        self.insertTab(new_index, widget, icon, text)
        self.setCurrentIndex(new_index)
        widget.setFocus()
        if parent.count() == 0:
            parent.last_tab_closed.emit()

    def dragEnterEvent(self, event):
        # Only accept if it's an tab-reordering request
        m = event.mimeData()
        formats = m.formats()
        if "action" in formats and m.data("action") == "tab-reordering":
            event.acceptProposedAction()

    def dropEvent(self, event):
        m = event.mimeData()
        index = self.tabBar().tabAt(event.pos())
        # Tell interested objects that a tab should be moved.
        if m.tab != self.widget(index):
            self._on_tab_move_request(m.tab, index)
            event.acceptProposedAction()

    def addTab(self, tab, *args):
        """
        Adds a tab to the tab widget, this function set the parent_tab_widget
        attribute on the tab instance.
        """
        tab.parent_tab_widget = self
        super(BaseTabWidget, self).addTab(tab, *args)


class OpenFilesPopup(QtWidgets.QDialog):
    triggered = QtCore.Signal(str)

    def __init__(self, *args):
        super(OpenFilesPopup, self).__init__(*args)
        self.ui = popup_open_files_ui.Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.tableWidget.itemActivated.connect(self._on_item_activated)
        self.ui.tableWidget.itemDoubleClicked.connect(self._on_item_activated)
        settings = QtCore.QSettings('pyQode', 'pyqode.core')
        self.sort_enabled = bool(settings.value(
            'sortOpenFilesAlphabetically', False))
        self.ui.checkBox.setChecked(self.sort_enabled)
        self.ui.checkBox.stateChanged.connect(self._on_sort_changed)

    def set_filenames(self, filenames):
        def clean(filenames):
            ret_val = []
            new_count = 0
            for filename in filenames:
                if not filename:
                    filename = 'New document %d.txt' % (new_count + 1)
                    new_count += 1
                ret_val.append(filename)
            return ret_val

        self._filenames = filenames
        filenames = clean(filenames)
        if self.sort_enabled:
            filenames = sorted(filenames, key=lambda x:
                               QtCore.QFileInfo(x).fileName().lower())
        self.ui.tableWidget.clearContents()
        icon_provider = SplittableCodeEditTabWidget.icon_provider_klass()
        self.ui.tableWidget.setRowCount(len(filenames))
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        for row, path in enumerate(filenames):
            finfo = QtCore.QFileInfo(path)
            filename = finfo.fileName()
            if finfo.exists():
                icon = icon_provider.icon(finfo)
            else:
                icon = icon_provider.icon(icon_provider.File)
            # file name
            item = QtWidgets.QTableWidgetItem()
            item.setText(filename)
            item.setIcon(icon)
            item.setToolTip(path)
            item.setData(QtCore.Qt.UserRole, path)
            self.ui.tableWidget.setItem(row, 0, item)

            # path
            item = QtWidgets.QTableWidgetItem()
            item.setText(path)
            item.setToolTip(path)
            item.setData(QtCore.Qt.UserRole, path)
            self.ui.tableWidget.setItem(row, 1, item)

    def _on_sort_changed(self, *_):
        self.sort_enabled = self.ui.checkBox.isChecked()
        settings = QtCore.QSettings('pyQode', 'pyqode.core')
        settings.setValue(
            'sortOpenFilesAlphabetically', self.sort_enabled)
        self.set_filenames(self._filenames)

    def _on_item_activated(self, item):
        self.hide()
        self.triggered.emit(item.data(QtCore.Qt.UserRole))

    def show(self):
        super(OpenFilesPopup, self).show()
        self.ui.tableWidget.setFocus()
        self.ui.tableWidget.selectRow(0)


class SplittableTabWidget(QtWidgets.QSplitter):
    """
    A splittable tab widget. The widget is implemented as a splitter which
    contains a main tab widget and a collection of child SplittableTabWidget.

    Widgets added to the the tab widget **must** have a ``split`` method which
    returns a clone of the widget instance.
<commit_msg>Fix TypeError: tab drag & drop should work now with PyQt 5.5.0<commit_after>"""
This module contains the splittable tab widget API
"""
import inspect
import logging
import mimetypes
import os
import uuid
from pyqode.qt import QtCore, QtWidgets, QtGui
from pyqode.core.api import utils, CodeEdit
from pyqode.core.dialogs import DlgUnsavedFiles
from pyqode.core._forms import popup_open_files_ui
from .tab_bar import TabBar
from .code_edits import GenericCodeEdit, TextCodeEdit


def _logger():
    return logging.getLogger(__name__)


class DraggableTabBar(TabBar):
    """
    A draggable tab bar that allow to drag & drop tabs.

    Implementation is based on this qt article:
    http://www.qtcentre.org/wiki/index.php?title=Movable_Tabs
    """
    #: Signal emitted when a tab must be moved to the specified
    #: index (the tab might come from another tab bar (split)).
    tab_move_request = QtCore.Signal(QtWidgets.QWidget, int)

    def __init__(self, parent):
        super(DraggableTabBar, self).__init__(parent)
        self._pos = QtCore.QPoint()
        self.setAcceptDrops(True)
        self.setMouseTracking(True)
        self.setElideMode(QtCore.Qt.ElideNone)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self._pos = event.pos()  # _pos is a QPoint defined in the header
        super(DraggableTabBar, self).mousePressEvent(event)

    def widget_under_mouse(self, event):
        index = self.tabAt(event.pos())
        tab = self.parent().widget(index)
        return tab

    def mouseMoveEvent(self, event):
        # update tooltip with the tooltip of the tab under mouse cursor.
        tab = self.widget_under_mouse(event)
        if tab is not None:
            tooltip = tab.toolTip()
            if not tooltip:
                try:
                    tooltip = tab.file.path
                except AttributeError:
                    pass
            self.setToolTip(tooltip)

        # If the distance is too small then return
        if (event.pos() - self._pos).manhattanLength() < \
                QtWidgets.QApplication.startDragDistance():
            return

        # If the left button isn't pressed anymore then return
        if not event.buttons() & QtCore.Qt.LeftButton:
            return

        drag = QtGui.QDrag(self)
        data = QtCore.QMimeData()
        data.tab = tab
        data.widget = self
        # a crude way to distinguish tab-reodering drags from other drags
        data.setData("action", b"tab-reordering")
        drag.setMimeData(data)
        drag.setPixmap(self.tabIcon(self.tabAt(event.pos())).pixmap(32, 32))
        drag.exec_()

    def dragEnterEvent(self, event):
        # Only accept if it's an tab-reordering request
        m = event.mimeData()
        formats = m.formats()
        if "action" in formats and m.data("action") == "tab-reordering":
            event.acceptProposedAction()

    def dropEvent(self, event):
        # drop a tab in a split (may be the same split or another one).
        m = event.mimeData()
        index = self.tabAt(event.pos())
        # Tell interested objects that a tab should be moved.
        if m.tab != self.parent().widget(index):
            self.tab_move_request.emit(m.tab, index)
        event.acceptProposedAction()


class BaseTabWidget(QtWidgets.QTabWidget):
    """
    Base tab widget class used by SplittableTabWidget. This tab widget adds a
    context menu to the tab bar that allow the user to:
        - split the current tab (horizontally or vertically)
        - close the current tab
        - close all tabs
        - close all other tabs
    """
    #: Signal emitted when the last tab has been closed
    last_tab_closed = QtCore.Signal()

    #: Signal emitted when a tab has been closed
    tab_closed = QtCore.Signal(QtWidgets.QWidget)

    #: Signal emitted when the user clicked on split vertical or split
    #: horizontal
    #: **Parameters**:
    #: - widget: the widget to split
    #: - orientation: split orientation (horizontal/vertical)
    split_requested = QtCore.Signal(QtWidgets.QWidget, int)

    def __init__(self, parent):
        super(BaseTabWidget, self).__init__(parent)
        self._current = None
        self.currentChanged.connect(self._on_current_changed)
        self.tabCloseRequested.connect(self._on_tab_close_requested)

        tab_bar = DraggableTabBar(self)
        tab_bar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        tab_bar.customContextMenuRequested.connect(self._show_tab_context_menu)
        tab_bar.tab_move_request.connect(self._on_tab_move_request)
        self.setTabBar(tab_bar)
        self.setAcceptDrops(True)
        self.setUsesScrollButtons(True)

        #: A list of additional context menu actions
        self.context_actions = []

    def tab_under_menu(self):
        """
        Returns the tab that sits under the context menu.
        :return: QWidget
        """
        return self.tabBar().tabAt(self._menu_pos)

    @QtCore.Slot()
    def close(self):
        """
        Closes the active editor
        """
        self.tabCloseRequested.emit(self.tab_under_menu())

    @QtCore.Slot()
    def close_others(self):
        """
        Closes every editors tabs except the current one.
        """
        current_widget = self.widget(self.tab_under_menu())
        self._try_close_dirty_tabs(exept=current_widget)
        i = 0
        while self.count() > 1:
            widget = self.widget(i)
            if widget != current_widget:
                self.remove_tab(i)
            else:
                i = 1

    @QtCore.Slot()
    def close_all(self):
        """
        Closes all editors
        """
        if self._try_close_dirty_tabs():
            while self.count():
                widget = self.widget(0)
                self.remove_tab(0)
                self.tab_closed.emit(widget)
            return True
        return False

    def save_widget(self, editor):
        """
        Saves the widget. The base implementation does nothing.

        The function must return a bool that tells whether the save succeeded
        or not.

        :param editor: editor widget to save.
        """
        return True

    def _create_tab_bar_menu(self):
        context_mnu = QtWidgets.QMenu()
        for action in self.context_actions:
            context_mnu.addAction(action)
        if self.context_actions:
            context_mnu.addSeparator()
        menu = QtWidgets.QMenu('Split', context_mnu)
        menu.setIcon(QtGui.QIcon.fromTheme('split'))
        a = menu.addAction('Split horizontally')
        a.triggered.connect(self._on_split_requested)
        a.setIcon(QtGui.QIcon.fromTheme('view-split-left-right'))
        a = menu.addAction('Split vertically')
        a.setIcon(QtGui.QIcon.fromTheme('view-split-top-bottom'))
        a.triggered.connect(self._on_split_requested)
        context_mnu.addMenu(menu)
        context_mnu.addSeparator()
        for name, slot in [('Close', self.close),
                           ('Close others', self.close_others),
                           ('Close all', self.close_all)]:
            qaction = QtWidgets.QAction(name, self)
            qaction.triggered.connect(slot)
            context_mnu.addAction(qaction)
            self.addAction(qaction)
        self._context_mnu = context_mnu
        return context_mnu

    def _show_tab_context_menu(self, position):
        if self.count():
            self._menu_pos = position
            SplittableTabWidget.tab_under_menu = self.widget(
                self.tab_under_menu())
            self._create_tab_bar_menu().popup(self.tabBar().mapToGlobal(
                position))

    def _collect_dirty_tabs(self, skip=None):
        """
        Collects the list of dirty tabs

        :param skip: Tab to skip (used for close_others).
        """
        widgets = []
        filenames = []
        for i in range(self.count()):
            widget = self.widget(i)
            try:
                if widget.dirty and widget != skip:
                    widgets.append(widget)
                    filenames.append(widget.file.path)
            except AttributeError:
                pass
        return widgets, filenames

    def _try_close_dirty_tabs(self, exept=None):
        """
        Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user
        what he wants to do.
        """
        widgets, filenames = self._collect_dirty_tabs(skip=exept)
        if not len(filenames):
            return True
        dlg = DlgUnsavedFiles(self, files=filenames)
        if dlg.exec_() == dlg.Accepted:
            if not dlg.discarded:
                for item in dlg.listWidget.selectedItems():
                    filename = item.text()
                    widget = None
                    for widget in widgets:
                        if widget.path == filename:
                            break
                    if widget != exept:
                        self.save_widget(widget)
                        self.remove_tab(self.indexOf(widget))
            return True
        return False

    def _get_widget_path(self, widget):
        try:
            return widget.path
        except AttributeError:
            return ''

    def _on_tab_close_requested(self, index):
        widget = self.widget(index)
        dirty = False
        try:
            if widget.original is None:
                dirty = widget.dirty
        except AttributeError:
            pass
        if not dirty:
            self.remove_tab(index)
        else:
            # unsaved widget
            path = self._get_widget_path(widget)
            if not path:
                path = self.tabText(self.indexOf(widget))
            dlg = DlgUnsavedFiles(
                self, files=[path])
            if dlg.exec_() == dlg.Accepted:
                rm = True
                if not dlg.discarded:
                    try:
                        rm = self.save_widget(widget)
                    except OSError:
                        pass
                if rm:
                    self.remove_tab(index)
                    widget.close()
                    widget.setParent(None)
                    del widget

    @staticmethod
    def _close_widget(widget):
        """
        Closes the given widgets and handles cases where the widget has been
        clone or is a clone of another widget
        """
        if widget is None:
            return
        # handled cloned widgets
        clones = []
        if hasattr(widget, 'original') and widget.original:
            # cloned widget needs to be removed from the original
            widget.original.clones.remove(widget)
            try:
                widget.setDocument(None)
            except AttributeError:
                # not a QTextEdit/QPlainTextEdit
                pass
        elif hasattr(widget, 'clones'):
            clones = widget.clones
        try:
            # only clear current editor if it does not have any other clones
            widget.close(clear=len(clones) == 0)
        except (AttributeError, TypeError):
            # not a CodeEdit
            widget.close()
        return clones

    def _restore_original(self, clones):
        try:
            first = clones[0]
        except (IndexError, TypeError):
            # empty or None
            pass
        else:
            first.clones = clones[1:]
            first.original = None
            for c in first.clones:
                c.original = first

    def remove_tab(self, index):
        """
        Overrides removeTab to emit tab_closed and last_tab_closed signals.

        :param index: index of the tab to remove.
        """
        widget = self.widget(index)
        clones = self._close_widget(widget)
        self.tab_closed.emit(widget)
        self.removeTab(index)
        self._restore_original(clones)
        widget._original_tab_widget._tabs.remove(widget)
        if self.count() == 0:
            self.last_tab_closed.emit()

    def _on_split_requested(self):
        """
        Emits the split requested signal with the desired orientation.
        """
        orientation = self.sender().text()
        widget = self.widget(self.tab_under_menu())
        if 'horizontally' in orientation:
            self.split_requested.emit(
                widget, QtCore.Qt.Horizontal)
        else:
            self.split_requested.emit(
                widget, QtCore.Qt.Vertical)

    def _on_current_changed(self, index):
        tab = self.widget(index)
        if tab:
            tab.setFocus()

    def _on_tab_move_request(self, widget, new_index):
        parent = widget.parent_tab_widget
        index = parent.indexOf(widget)
        text = parent.tabText(index)
        icon = parent.tabIcon(index)
        parent.removeTab(index)
        widget.parent_tab_widget = self
        self.insertTab(new_index, widget, icon, text)
        self.setCurrentIndex(new_index)
        widget.setFocus()
        if parent.count() == 0:
            parent.last_tab_closed.emit()

    def dragEnterEvent(self, event):
        # Only accept if it's an tab-reordering request
        m = event.mimeData()
        formats = m.formats()
        if "action" in formats and m.data("action") == "tab-reordering":
            event.acceptProposedAction()

    def dropEvent(self, event):
        m = event.mimeData()
        index = self.tabBar().tabAt(event.pos())
        # Tell interested objects that a tab should be moved.
        if m.tab != self.widget(index):
            self._on_tab_move_request(m.tab, index)
            event.acceptProposedAction()

    def addTab(self, tab, *args):
        """
        Adds a tab to the tab widget, this function set the parent_tab_widget
        attribute on the tab instance.
        """
        tab.parent_tab_widget = self
        super(BaseTabWidget, self).addTab(tab, *args)


class OpenFilesPopup(QtWidgets.QDialog):
    triggered = QtCore.Signal(str)

    def __init__(self, *args):
        super(OpenFilesPopup, self).__init__(*args)
        self.ui = popup_open_files_ui.Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.tableWidget.itemActivated.connect(self._on_item_activated)
        self.ui.tableWidget.itemDoubleClicked.connect(self._on_item_activated)
        settings = QtCore.QSettings('pyQode', 'pyqode.core')
        self.sort_enabled = bool(settings.value(
            'sortOpenFilesAlphabetically', False))
        self.ui.checkBox.setChecked(self.sort_enabled)
        self.ui.checkBox.stateChanged.connect(self._on_sort_changed)

    def set_filenames(self, filenames):
        def clean(filenames):
            ret_val = []
            new_count = 0
            for filename in filenames:
                if not filename:
                    filename = 'New document %d.txt' % (new_count + 1)
                    new_count += 1
                ret_val.append(filename)
            return ret_val

        self._filenames = filenames
        filenames = clean(filenames)
        if self.sort_enabled:
            filenames = sorted(filenames, key=lambda x:
                               QtCore.QFileInfo(x).fileName().lower())
        self.ui.tableWidget.clearContents()
        icon_provider = SplittableCodeEditTabWidget.icon_provider_klass()
        self.ui.tableWidget.setRowCount(len(filenames))
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        for row, path in enumerate(filenames):
            finfo = QtCore.QFileInfo(path)
            filename = finfo.fileName()
            if finfo.exists():
                icon = icon_provider.icon(finfo)
            else:
                icon = icon_provider.icon(icon_provider.File)
            # file name
            item = QtWidgets.QTableWidgetItem()
            item.setText(filename)
            item.setIcon(icon)
            item.setToolTip(path)
            item.setData(QtCore.Qt.UserRole, bytes(path, 'utf-8'))
            self.ui.tableWidget.setItem(row, 0, item)

            # path
            item = QtWidgets.QTableWidgetItem()
            item.setText(path)
            item.setToolTip(path)
            item.setData(QtCore.Qt.UserRole, bytes(path, 'utf-8'))
            self.ui.tableWidget.setItem(row, 1, item)

    def _on_sort_changed(self, *_):
        self.sort_enabled = self.ui.checkBox.isChecked()
        settings = QtCore.QSettings('pyQode', 'pyqode.core')
        settings.setValue(
            'sortOpenFilesAlphabetically', self.sort_enabled)
        self.set_filenames(self._filenames)

    def _on_item_activated(self, item):
        self.hide()
        self.triggered.emit(item.data(QtCore.Qt.UserRole))

    def show(self):
        super(OpenFilesPopup, self).show()
        self.ui.tableWidget.setFocus()
        self.ui.tableWidget.selectRow(0)


class SplittableTabWidget(QtWidgets.QSplitter):
    """
    A splittable tab widget. The widget is implemented as a splitter which
    contains a main tab widget and a collection of child SplittableTabWidget.

    Widgets added to the the tab widget **must** have a ``split`` method which
    returns a clone of the widget instance.

{'fraction_non_alphanumeric': 0.08909853249475891, 'fraction_numerical': 0.001310272536687631, 'mean_word_length': 1.9566976584022038, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1205542', 'n_tokens_mistral': 9865, 'n_tokens_neox': 9509, 'n_words': 2324}