<commit_before>"""
.. module:: frames
    :synopsys: Define all the custom frames

.. moduleauthor:: <NAME> <<EMAIL>>
"""
from __future__ import unicode_literals
import os
from collections import OrderedDict as od
import pypandoc as pa
import six  # Used to replace the od iteritems from py2
import io
import traceback  # For failure display
import time  # for sleep

from PySide import QtGui
from PySide import QtCore
from PySide import QtWebKit

from .flowlayout import FlowLayout

from subprocess import Popen

# Local imports
from .popups import NewEntry, NewNotebook, NewFolder
import noteorganiser.text_processing as tp
from .constants import EXTENSION
from .configuration import search_folder_recursively
from .syntax import ModifiedMarkdownHighlighter
from .widgets import PicButton, VerticalScrollArea


class CustomFrame(QtGui.QFrame):
    """
    Base class for all three tabbed frames

    """
    def __init__(self, parent=None):
        """ Create the basic layout """
        QtGui.QFrame.__init__(self, parent)
        # Create a shortcut notation for the main information
        self.parent = parent
        self.info = parent.info
        self.log = parent.log

        # Create the main layout
        self.setLayout(QtGui.QVBoxLayout())

        if hasattr(self, 'initLogic'):
            self.initLogic()

        self.initUI()

    def initUI(self):
        """
        This will be called on creation

        A daughter class should implement this function
        """
        raise NotImplementedError

    def clearUI(self):
        """ Common method for recursively cleaning layouts """
        while self.layout().count():
            item = self.layout().takeAt(0)
            if isinstance(item, QtGui.QLayout):
                self.clearLayout(item)
                item.deleteLater()
            else:
                try:
                    widget = item.widget()
                    if widget is not None:
                        widget.deleteLater()
                except AttributeError:
                    pass

    def clearLayout(self, layout):
        """ Submethod to help cleaning the UI before redrawing """
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.clearLayout(item.layout())

    def zoomIn(self):
        raise NotImplementedError

    def zoomOut(self):
        raise NotImplementedError

    def resetSize(self):
        raise NotImplementedError


class Library(CustomFrame):
    r"""
    The notebooks will be stored and displayed there

    Should ressemble something like this:
     _________  _________  _________
    / Library \/ Editing \/ Preview \
    |          ----------------------------------
    |                              | global tag |
    |   notebook_1     notebook_2  | another tag|
    | ------------------------------ tag taggy  |
    |                              | taggy tag  |
    |   notebook_3                 |            |
    |                              |            |
    | [up] [new N] [new F]         |            |
    --------------------------------------------|
    """
    def initUI(self):
        self.log.info("Starting UI init of %s" % self.__class__.__name__)

        # Create the shelves object
        self.shelves = Shelves(self)
        self.layout().addWidget(self.shelves)

        # Toolbar on top
        if not hasattr(self, 'toolbar'):
            self.toolbar = self.parent.addToolBar('Library')

            # Go up in the directories (disabled if in the root directory)
            self.upAction = QtGui.QAction('&Up', self)
            self.upAction.setShortcut('Alt+U')
            self.upAction.triggered.connect(self.shelves.upFolder)
            if self.info.level == self.info.root:
                self.upAction.setDisabled(True)
            self.toolbar.addAction(self.upAction)

            # Create a new notebook
            self.newNotebookAction = QtGui.QAction('&New Notebook', self)
            self.newNotebookAction.setShortcut('Alt+N')
            self.newNotebookAction.triggered.connect(
                self.shelves.createNotebook)
            self.toolbar.addAction(self.newNotebookAction)

            # Create a new folder
            self.newFolderAction = QtGui.QAction('New &Folder', self)
            self.newFolderAction.setShortcut('Alt+F')
            self.newFolderAction.triggered.connect(self.shelves.createFolder)
            self.toolbar.addAction(self.newFolderAction)

        # update state of UpAction when shelves get refreshed
        self.shelves.refreshSignal.connect(self.updateUpAction)

        self.log.info("Finished UI init of %s" % self.__class__.__name__)

    def refresh(self):
        """ Refresh all elements of the frame """
        self.shelves.refresh()

    def updateUpAction(self):
        """
        update the state of the toolbar action 'Up'
        active if not in root
        """
        self.upAction.setDisabled(self.info.level == self.info.root)


class Editing(CustomFrame):
    r"""
    Direct access to the markup files will be there

    The left hand side will be the text within a tab widget, named as the
    notebook it belongs to.

    Contrary to the Library tab, this one will have an additional state, the
    active state, which will dictate on which file the window is open.

     _________  _________  _________
    / Library \/ Editing \/ Preview \
    |----------           ----------------------------
    |    --------------------------|                  |
    |   /|                         | [+] new entry    |
    |   N|                         | [ ] save document|
    |   1|                         | [ ] preview      |
    |   \|_________________________|                  |
    ---------------------------------------------------
    """
    # Launched when the previewer is desired
    loadNotebook = QtCore.Signal(str)

    def initUI(self):
        self.log.info("Starting UI init of %s" % self.__class__.__name__)

        # Toolbar on top
        if not hasattr(self, 'toolbar'):
            self.toolbar = self.parent.addToolBar('Editing')
            self.toolbar.setVisible(False)

        # Global horizontal layout
        hbox = QtGui.QHBoxLayout()

        # New Entry Button to enter a new field in the current notebook
        self.newEntryButton = QtGui.QPushButton("&New entry", self)
        self.newEntryButton.clicked.connect(self.newEntry)

        # Edit in an exterior editor TODO
        self.editButton = QtGui.QPushButton("Edit (e&xterior editor)", self)
        self.editButton.clicked.connect(self.editExternal)

        # Launch the previewing of the current notebook
        self.previewButton = QtGui.QPushButton("&Preview notebook", self)
        self.previewButton.clicked.connect(self.preview)

        # Create the tabbed widgets containing the text editors. The tabs will
        # appear on the left-hand side
        self.tabs = QtGui.QTabWidget(self)
        self.tabs.setTabPosition(QtGui.QTabWidget.West)

        # The loop is over all the notebooks in the **current** folder
        for notebook in self.info.notebooks:
            editor = TextEditor(self)
            # Set the source of the TextEditor to the desired notebook
            editor.setSource(os.path.join(self.info.level, notebook))
            # Add the text editor to the tabbed area<commit_msg>added buttons in Editing to the toolbar<commit_after>"""
.. module:: frames
    :synopsys: Define all the custom frames

.. moduleauthor:: <NAME> <<EMAIL>>
"""
from __future__ import unicode_literals
import os
from collections import OrderedDict as od
import pypandoc as pa
import six  # Used to replace the od iteritems from py2
import io
import traceback  # For failure display
import time  # for sleep

from PySide import QtGui
from PySide import QtCore
from PySide import QtWebKit

from .flowlayout import FlowLayout

from subprocess import Popen

# Local imports
from .popups import NewEntry, NewNotebook, NewFolder
import noteorganiser.text_processing as tp
from .constants import EXTENSION
from .configuration import search_folder_recursively
from .syntax import ModifiedMarkdownHighlighter
from .widgets import PicButton, VerticalScrollArea


class CustomFrame(QtGui.QFrame):
    """
    Base class for all three tabbed frames

    """
    def __init__(self, parent=None):
        """ Create the basic layout """
        QtGui.QFrame.__init__(self, parent)
        # Create a shortcut notation for the main information
        self.parent = parent
        self.info = parent.info
        self.log = parent.log

        # Create the main layout
        self.setLayout(QtGui.QVBoxLayout())

        if hasattr(self, 'initLogic'):
            self.initLogic()

        self.initUI()

    def initUI(self):
        """
        This will be called on creation

        A daughter class should implement this function
        """
        raise NotImplementedError

    def clearUI(self):
        """ Common method for recursively cleaning layouts """
        while self.layout().count():
            item = self.layout().takeAt(0)
            if isinstance(item, QtGui.QLayout):
                self.clearLayout(item)
                item.deleteLater()
            else:
                try:
                    widget = item.widget()
                    if widget is not None:
                        widget.deleteLater()
                except AttributeError:
                    pass

    def clearLayout(self, layout):
        """ Submethod to help cleaning the UI before redrawing """
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.clearLayout(item.layout())

    def zoomIn(self):
        raise NotImplementedError

    def zoomOut(self):
        raise NotImplementedError

    def resetSize(self):
        raise NotImplementedError


class Library(CustomFrame):
    r"""
    The notebooks will be stored and displayed there

    Should ressemble something like this:
     _________  _________  _________
    / Library \/ Editing \/ Preview \
    |          ----------------------------------
    |                              | global tag |
    |   notebook_1     notebook_2  | another tag|
    | ------------------------------ tag taggy  |
    |                              | taggy tag  |
    |   notebook_3                 |            |
    |                              |            |
    | [up] [new N] [new F]         |            |
    --------------------------------------------|
    """
    def initUI(self):
        self.log.info("Starting UI init of %s" % self.__class__.__name__)

        # Create the shelves object
        self.shelves = Shelves(self)
        self.layout().addWidget(self.shelves)

        # Toolbar on top
        if not hasattr(self, 'toolbar'):
            self.toolbar = self.parent.addToolBar('Library')

            # Go up in the directories (disabled if in the root directory)
            self.upAction = QtGui.QAction('&Up', self)
            self.upAction.setShortcut('Alt+U')
            self.upAction.triggered.connect(self.shelves.upFolder)
            if self.info.level == self.info.root:
                self.upAction.setDisabled(True)
            self.toolbar.addAction(self.upAction)

            # Create a new notebook
            self.newNotebookAction = QtGui.QAction('&New Notebook', self)
            self.newNotebookAction.setShortcut('Alt+N')
            self.newNotebookAction.triggered.connect(
                self.shelves.createNotebook)
            self.toolbar.addAction(self.newNotebookAction)

            # Create a new folder
            self.newFolderAction = QtGui.QAction('New &Folder', self)
            self.newFolderAction.setShortcut('Alt+F')
            self.newFolderAction.triggered.connect(self.shelves.createFolder)
            self.toolbar.addAction(self.newFolderAction)

        # update state of UpAction when shelves get refreshed
        self.shelves.refreshSignal.connect(self.updateUpAction)

        self.log.info("Finished UI init of %s" % self.__class__.__name__)

    def refresh(self):
        """ Refresh all elements of the frame """
        self.shelves.refresh()

    def updateUpAction(self):
        """
        update the state of the toolbar action 'Up'
        active if not in root
        """
        self.upAction.setDisabled(self.info.level == self.info.root)


class Editing(CustomFrame):
    r"""
    Direct access to the markup files will be there

    The left hand side will be the text within a tab widget, named as the
    notebook it belongs to.

    Contrary to the Library tab, this one will have an additional state, the
    active state, which will dictate on which file the window is open.

     _________  _________  _________
    / Library \/ Editing \/ Preview \
    |----------           ----------------------------
    |    --------------------------|                  |
    |   /|                         | [+] new entry    |
    |   N|                         | [ ] save document|
    |   1|                         | [ ] preview      |
    |   \|_________________________|                  |
    ---------------------------------------------------
    """
    # Launched when the previewer is desired
    loadNotebook = QtCore.Signal(str)

    def initUI(self):
        self.log.info("Starting UI init of %s" % self.__class__.__name__)

        # Toolbar on top
        if not hasattr(self, 'toolbar'):
            self.toolbar = self.parent.addToolBar('Editing')
            self.toolbar.setVisible(False)

            # Create a new entry - new field in the current notebook
            self.newEntryAction = QtGui.QAction('&New entry', self)
            self.newEntryAction.setShortcut('Alt+N')
            self.newEntryAction.triggered.connect(self.newEntry)
            self.toolbar.addAction(self.newEntryAction)

            # Edit in an exterior editor
            self.editAction = QtGui.QAction('Edit (e&xterior editor)', self)
            self.editAction.setShortcut('Alt+X')
            self.editAction.triggered.connect(self.editExternal)
            self.toolbar.addAction(self.editAction)

            # Launch the previewing of the current notebook
            self.previewAction = QtGui.QAction('&Preview notebook', self)
            self.previewAction.setShortcut('Alt+P')
            self.previewAction.triggered.connect(self.preview)
            self.toolbar.addAction(self.previewAction)

        # Global horizontal layout
        hbox = QtGui.QHBoxLayout()

        # New Entry Button to enter a new field in the current notebook
        self.newEntryButton = QtGui.QPushButton("&New entry", self)
        self.newEntryButton.clicked.connect(self.newEntry)

        # Edit in an exterior editor TODO
        self.editButton = QtGui.QPushButton("Edit (e&xterior editor)", self)
        self.editButton.clicked.connect(self.editExternal)

        # Launch the previewing of the current notebook
        self.previewButton = QtGui.QPushButton("&Preview notebook", self)
        self.previewButton.clicked.connect(self.preview)

        # Create the tabbed widgets containing the text editors. The tabs will
        # appear on the left-hand side
        self.tabs = QtGui.QTabWidget(self)
        self.tabs.setTabPosition(QtGui.QTabWidget.West)

        # The loop is over all the notebooks in the **current** folder
        for notebook in self.info.notebooks:
            editor = TextEditor(self)
            # Set the source of the TextEditor to the desired notebook
            editor.setSource(os.path.join(self.info.level, notebook))
            # Add the text editor to the tabbed area
{'fraction_non_alphanumeric': 0.1087607637588918, 'fraction_numerical': 0.0008735804317983277, 'mean_word_length': 1.8142230026338895, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 12, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3590247', 'n_tokens_mistral': 4226, 'n_tokens_neox': 4072, 'n_words': 1183}