<commit_before>#!/usr/bin/env python
"""
Name :          qconcurrency.widgets._updaterwidgets_._updaterlist_.py
Created :       May 24, 2017
Author :        <NAME>
Contact :       <EMAIL>
________________________________________________________________________________
Description :   List that manages creation,updates,deletion in a consistent
                manner.
________________________________________________________________________________
"""
#builtin
from   __future__    import unicode_literals
from   __future__    import absolute_import
from   __future__    import division
from   __future__    import print_function
import uuid
import sys
import os
import copy
#package
from qconcurrency.widgets._sessionwidgets_._basewidgets_ import (
    SessionWidgetBase, SessionWidgetItemBase
)
#external
from Qt import QtWidgets, QtCore, QtGui
#internal


#!TODO: flag to allow deselect in empty-space
#!TODO: Enter toggles confirm/edit selected item

class SessionList( SessionWidgetBase, QtWidgets.QWidget ):
    def __init__(self, colours=None):
        """
        Args:
            colours (dict, optional):
                An optional dictionary, indicating colours to use
                for QListWidgetItems based on their status.

                Any key that is not set in the dictionary
                uses the stylesheet's default colours for
                :py:obj:`QListWidgetItems`

                .. code-block:: python

                    {
                        'normal':  {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'changed': {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'new':     {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'editable': {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                    }

        """
        SessionWidgetBase.__init__(self)
        QtWidgets.QWidget.__init__(self)

        # Attributes
        if not colours:   self._colours = {}
        else:             self._colours = colours

        self._default_palette  = copy.copy( self.palette() )  #: the default QlistWidget palette
        self._editable_widgets = set() #: every widget that is currently editable


        # Widgets
        self._list = None  # the QListWidget managed by this class

        self._initui()

    def _initui(self):

        # Create Widgets
        layout     = QtWidgets.QVBoxLayout()
        self._list = _DeselectableListWidget()

        # Position Widgets
        self.setLayout( layout )
        layout.addWidget( self._list )

        # Widget Attrs
        layout.setContentsMargins(0,0,0,0)

        # Connections
        self._list.itemChanged.connect( self._handle_item_changed )
        self._list.itemDoubleClicked.connect( self._handle_itemDoubleClicked )
        self._list.itemSelectionChanged.connect( self._handle_itemSelectionChanged )


    def clear(self):
        """
        Clears the list, and all internal data.
        """
        self._list.clear()

        self._items        = {}
        self._newitems     = set()
        self._delitems     = set()
        self._changeditems = set()

        self._last_selected = None

    def add_item(self, val, _id=None, saved_val=None ):
        """
        Adds a new item to the list.

        Args:
            val (object): ``(ex:  'itemA' )``
                The item you'd like to add to the widget

            _id (object, optional):
                If the item exists and has already been assigned an Id
                provide it here.

                Or, if the item is new, but you want to assign a specific
                Id, you may also provide an Id here.

            saved_val (object, optional):
                If this argument is assigned a value, the item
                will tracked as being an item that is already saved
                to the database (or other long-term-storage).

                You can test whether or not a widget's current value
                is different from this saved value using the method
                :py:meth:`SessionListItem.is_changed`
        """

        if _id in self._items:
            raise KeyError(
                'Another item with the _id(%s) already exists in ``self._items``'
            )

        # Create/Colour/Add Widget
        # ========================
        widget = SessionListItem( val, _id, saved_val )

        # if no normal-colour is set, create it based on default
        if 'default_brush' not in self._colours:
            self._colours['default_brush'] = {
                'fg': widget.foreground(),
                'bg': widget.background(),
            }

        self._list.addItem( widget )

        # set colour
        self._handle_item_statuschanged(
            widget,
            widget.is_new(),
            widget.is_changed(),
            widget.is_editable()
        )


        # internal data
        # =============
        if widget.is_new():
            self._newitems.add( widget.id() )
        elif val != saved_val:
            self._changeditems.add( widget.id() )

        self._items[ widget.id() ] = widget

        # connections
        widget.status_changed.connect( self._handle_item_statuschanged )

    def remove_item(self, _id ):
        """
        Removes a single item from the list.

        Args:
            _id (object, optional):
                The `_id` of the item that you want to delete.
        """

        if _id not in self._items:
            return

        # manage internal data
        widget = self._items[_id]

        if widget.is_new():
            self._newitems.remove(_id)

        elif widget.is_changed():
            self._changeditems.remove(_id)
            self._delitems.add(_id)
        else:
            self._delitems.add(_id)

        # remove widget from list
        row  = self._list.row(widget)
        item = self._list.takeItem(row)

        # remove item from tracked items
        self._items.pop(_id)


    def selectedItems(self):
        """
        Wraps :py:meth:`QtWidgets.QListWidget.selectedItems` , and returns
        all selected :py:obj:`SessionListItems` .
        """
        return self._list.selectedItems()

    def keyPressEvent(self, event):
        """
        If an item is selected in the list, the last-item in the selection
        is toggled between editable and normal modes.
        """
        selected_items = self._list.selectedItems()
        if selected_items:
<commit_msg>enter toggles editable on listitems<commit_after>#!/usr/bin/env python
"""
Name :          qconcurrency.widgets._updaterwidgets_._updaterlist_.py
Created :       May 24, 2017
Author :        <NAME>
Contact :       <EMAIL>
________________________________________________________________________________
Description :   List that manages creation,updates,deletion in a consistent
                manner.
________________________________________________________________________________
"""
#builtin
from   __future__    import unicode_literals
from   __future__    import absolute_import
from   __future__    import division
from   __future__    import print_function
import uuid
import sys
import os
import copy
#package
from qconcurrency.widgets._sessionwidgets_._basewidgets_ import (
    SessionWidgetBase, SessionWidgetItemBase
)
#external
from Qt import QtWidgets, QtCore, QtGui
#internal


#!TODO: flag to allow deselect in empty-space
#!TODO: Enter toggles confirm/edit selected item

class SessionList( SessionWidgetBase, QtWidgets.QWidget ):
    def __init__(self, colours=None):
        """
        Args:
            colours (dict, optional):
                An optional dictionary, indicating colours to use
                for QListWidgetItems based on their status.

                Any key that is not set in the dictionary
                uses the stylesheet's default colours for
                :py:obj:`QListWidgetItems`

                .. code-block:: python

                    {
                        'normal':  {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'changed': {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'new':     {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                        'editable': {'fg':QColor(255,255,255), 'bg':QColor(255,255,255)},
                    }

        """
        SessionWidgetBase.__init__(self)
        QtWidgets.QWidget.__init__(self)

        # Attributes
        if not colours:   self._colours = {}
        else:             self._colours = colours

        self._default_palette  = copy.copy( self.palette() )  #: the default QlistWidget palette
        self._editable_widgets = set() #: every widget that is currently editable


        # Widgets
        self._list = None  # the QListWidget managed by this class

        self._initui()

    def _initui(self):

        # Create Widgets
        layout     = QtWidgets.QVBoxLayout()
        self._list = _DeselectableListWidget()

        # Position Widgets
        self.setLayout( layout )
        layout.addWidget( self._list )

        # Widget Attrs
        layout.setContentsMargins(0,0,0,0)

        # Connections
        self._list.itemChanged.connect( self._handle_item_changed )
        self._list.itemDoubleClicked.connect( self._handle_itemDoubleClicked )
        self._list.itemSelectionChanged.connect( self._handle_itemSelectionChanged )


    def clear(self):
        """
        Clears the list, and all internal data.
        """
        self._list.clear()

        self._items        = {}
        self._newitems     = set()
        self._delitems     = set()
        self._changeditems = set()

        self._last_selected = None

    def add_item(self, val, _id=None, saved_val=None ):
        """
        Adds a new item to the list.

        Args:
            val (object): ``(ex:  'itemA' )``
                The item you'd like to add to the widget

            _id (object, optional):
                If the item exists and has already been assigned an Id
                provide it here.

                Or, if the item is new, but you want to assign a specific
                Id, you may also provide an Id here.

            saved_val (object, optional):
                If this argument is assigned a value, the item
                will tracked as being an item that is already saved
                to the database (or other long-term-storage).

                You can test whether or not a widget's current value
                is different from this saved value using the method
                :py:meth:`SessionListItem.is_changed`
        """

        if _id in self._items:
            raise KeyError(
                'Another item with the _id(%s) already exists in ``self._items``'
            )

        # Create/Colour/Add Widget
        # ========================
        widget = SessionListItem( val, _id, saved_val )

        # if no normal-colour is set, create it based on default
        if 'default_brush' not in self._colours:
            self._colours['default_brush'] = {
                'fg': widget.foreground(),
                'bg': widget.background(),
            }

        self._list.addItem( widget )

        # set colour
        self._handle_item_statuschanged(
            widget,
            widget.is_new(),
            widget.is_changed(),
            widget.is_editable()
        )


        # internal data
        # =============
        if widget.is_new():
            self._newitems.add( widget.id() )
        elif val != saved_val:
            self._changeditems.add( widget.id() )

        self._items[ widget.id() ] = widget

        # connections
        widget.status_changed.connect( self._handle_item_statuschanged )

    def remove_item(self, _id ):
        """
        Removes a single item from the list.

        Args:
            _id (object, optional):
                The `_id` of the item that you want to delete.
        """

        if _id not in self._items:
            return

        # manage internal data
        widget = self._items[_id]

        if widget.is_new():
            self._newitems.remove(_id)

        elif widget.is_changed():
            self._changeditems.remove(_id)
            self._delitems.add(_id)
        else:
            self._delitems.add(_id)

        # remove widget from list
        row  = self._list.row(widget)
        item = self._list.takeItem(row)

        # remove item from tracked items
        self._items.pop(_id)


    def setSelectionMode(self, selectionMode):
        """
        Wraps :py:meth:`QListWidget.setSelectionMode`
        """
        return self._list.setSelectionMode( selectionMode )

    def setSelectionModel(self, selectionModel):
        """
        Wraps :py:meth:`QListWidget.setSelectionModel`
        """
        return self._list.setSelectionModel( selectionModel )

    def selectedItems(self):
        """
        Wraps :py:meth:`QtWidgets.QListWidget.selectedItems` , and returns
        all selected :py:obj:`SessionListItems` .
        """
        return self._list.selectedItems()

    def keyPressEvent(self, event):
        """
        If an item is selected in the list, the last-item in the selection
        is toggled between editable and normal modes.
        """
        selected_items = self._list.selectedItems()
        if selected_items:

{'fraction_non_alphanumeric': 0.09262154716700172, 'fraction_numerical': 0.01221055766510312, 'mean_word_length': 1.9308313331878681, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2648169', 'n_tokens_mistral': 3754, 'n_tokens_neox': 3472, 'n_words': 982}