File: ListModel.py

package info (click to toggle)
pyfai 0.20.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,460 kB
  • sloc: python: 49,743; lisp: 7,059; sh: 225; ansic: 165; makefile: 119
file content (251 lines) | stat: -rw-r--r-- 8,329 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# coding: utf-8
# /*##########################################################################
#
# Copyright (C) 2016-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

__authors__ = ["V. Valls"]
__license__ = "MIT"
__date__ = "16/10/2020"

import functools

from silx.gui import qt
from .AbstractModel import AbstractModel


class ChangeEvent(object):

    def __init__(self, index, item, added=False, removed=False, updated=False):
        """
        Define a change done on an item from the :class:`ListModel`.

        :param int index: The location where to put/remove the item (before the
            change) or the current index of the changed item
        :param object item: The item involved in this change
        :param bool updated: True if the item was changed
        :param bool added: True if the item was added
        :param bool removed: True if the item was removed
        """
        self.index = index
        self.item = item
        assert(updated + removed + added == 1)
        self.added = added
        self.removed = removed
        self.updated = updated


class ChangeListEvent(object):
    """A container of consecutive change events"""

    def __init__(self):
        self.__events = []
        self.__structural = 0
        self.__updates = 0

    def _append(self, event):
        """Append a new event to the list.

        :param ChangeEvent event: A new event
        """
        self.__events.append(event)
        if event.added or event.removed:
            self.__structural += 1
        if event.updated:
            self.__updates += 1

    def __len__(self):
        """
        Returns the number of atomic change events applied by this event

        :rtype: int
        """
        return len(self.__events)

    def __iter__(self):
        """
        Iterates throug of the change events.

        :rtype: Iterator[ChangeEvent]
        """
        for event in self.__events:
            yield event

    def __getitem__(self, key):
        """
        Returns an event at a location

        :rtype: ChangeEvent
        """
        return self.__events[key]

    def hasStructuralEvents(self):
        """True if a structural change (`added`, `removed`) is part of the changes

        :rtype: bool
        """
        return self.__structural > 0

    def hasOnlyStructuralEvents(self):
        """True if only structural change (`added`, `removed`) is part of the changes

        :rtype: bool
        """
        return self.__structural > 0 and self.__updates == 0

    def hasUpdateEvents(self):
        """True if an update change (`updated`) is part of the changes

        :rtype: bool
        """
        return self.__updates > 0

    def hasOnlyUpdateEvents(self):
        """True if only updates events (`updated`) is part of the changes

        :rtype: bool
        """
        return self.__structural == 0 and self.__updates > 0


class ListModel(AbstractModel):
    """
    List of `AbstractModel` managing signals when items are eadited, added and
    removed.

    Atomic events for each add/remove of items. To manage it in a better way,
    `structureAboutToChange` and `structureChanged`, in order to compute all
    the atomic events in a single time.

    :param parent: Owner of this model
    """

    changed = qt.Signal([], [ChangeListEvent])
    """Emitted at the end of a structural change."""

    structureChanged = qt.Signal()
    """Emitted at the end of a structural change."""

    contentChanged = qt.Signal()
    """Emitted when the content of the elements changed."""

    def __init__(self, parent=None):
        super(ListModel, self).__init__(parent)
        self.__cacheStructureEvent = None
        self.__cacheContentWasChanged = False
        self.__items = []

    def isValid(self):
        for item, _callback in self.__items:
            if not item.isValid():
                return
        return True

    def __len__(self):
        return len(self.__items)

    def __iter__(self):
        for item, _callback in self.__items:
            yield item

    def __getitem__(self, key):
        """
        Returns an item from it's index.
        """
        return self.__items[key][0]

    def index(self, item):
        """
        Returns the index of the item in the list structure
        """
        for i, (curentItem, _callback) in enumerate(self.__items):
            if item is curentItem:
                return i
        raise IndexError("Item %s is not in list" % item)

    def clear(self):
        """Remove all the items from the list."""
        self.lockSignals()
        # TODO: Could be improved
        for item, _callback in list(self.__items):
            self.remove(item)
        self.unlockSignals()

    def append(self, item):
        """Add a new item to the end of the list."""
        assert(isinstance(item, AbstractModel))
        index = len(self.__items)
        callback = functools.partial(self.__contentWasChanged, item)
        item.changed.connect(callback)
        self.__items.append((item, callback))
        event = ChangeEvent(index=index, item=item, added=True)
        self.__fireStructureChange(event)

    def remove(self, item):
        """Remove an item."""
        assert(isinstance(item, AbstractModel))
        index = self.index(item)
        callback = self.__items[index][1]
        del self.__items[index]
        item.changed.disconnect(callback)
        event = ChangeEvent(index=index, item=item, removed=True)
        self.__fireStructureChange(event)

    def __fireStructureChange(self, event):
        emitted = self.wasChanged()
        if emitted:
            self.structureChanged.emit()
            changeListEvent = ChangeListEvent()
            changeListEvent._append(event)
            self.changed[ChangeListEvent].emit(changeListEvent)
        else:
            if self.__cacheStructureEvent is None:
                self.__cacheStructureEvent = ChangeListEvent()
            self.__cacheStructureEvent._append(event)

    def __contentWasChanged(self, item):
        emitted = self.wasChanged()
        index = self.index(item)
        event = ChangeEvent(index=index, item=item, updated=True)
        if emitted:
            self.contentChanged.emit()
            changeListEvent = ChangeListEvent()
            changeListEvent._append(event)
            self.changed[ChangeListEvent].emit(changeListEvent)
        else:
            self.__cacheContentWasChanged = True
            if self.__cacheStructureEvent is None:
                self.__cacheStructureEvent = ChangeListEvent()
            self.__cacheStructureEvent._append(event)

    def unlockSignals(self):
        unlocked = AbstractModel.unlockSignals(self)
        if unlocked:
            if self.__cacheStructureEvent is not None:
                self.changed[ChangeListEvent].emit(self.__cacheStructureEvent)
                if self.__cacheStructureEvent.hasStructuralEvents():
                    self.structureChanged.emit()
                self.__cacheStructureEvent = None
            if self.__cacheContentWasChanged:
                self.contentChanged.emit()
                self.__cacheContentWasChanged = False
        return unlocked