summaryrefslogtreecommitdiff
path: root/silx/gui/hdf5/Hdf5TreeModel.py
blob: 41fa91c11fe87a7c822a73d27675d4b2e6b6d929 (plain)
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2017 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__ = "22/09/2017"


import os
import logging
from .. import qt
from .. import icons
from .Hdf5Node import Hdf5Node
from .Hdf5Item import Hdf5Item
from .Hdf5LoadingItem import Hdf5LoadingItem
from . import _utils
from ... import io as silx_io

_logger = logging.getLogger(__name__)

"""Helpers to take care of None objects as signal parameters.
PySide crash if a signal with a None parameter is emitted between threads.
"""
if qt.BINDING == 'PySide':
    class _NoneWraper(object):
        pass
    _NoneWraperInstance = _NoneWraper()

    def _wrapNone(x):
        """Wrap x if it is a None value, else returns x"""
        if x is None:
            return _NoneWraperInstance
        else:
            return x

    def _unwrapNone(x):
        """Unwrap x as a None if a None was stored by `wrapNone`, else returns
        x"""
        if x is _NoneWraperInstance:
            return None
        else:
            return x
else:
    # Allow to fix None event params to avoid PySide crashes
    def _wrapNone(x):
        return x

    def _unwrapNone(x):
        return x


def _createRootLabel(h5obj):
    """
    Create label for the very first npde of the tree.

    :param h5obj: The h5py object to display in the GUI
    :type h5obj: h5py-like object
    :rtpye: str
    """
    if silx_io.is_file(h5obj):
        label = os.path.basename(h5obj.filename)
    else:
        filename = os.path.basename(h5obj.file.filename)
        path = h5obj.name
        if path.startswith("/"):
            path = path[1:]
        label = "%s::%s" % (filename, path)
    return label


class LoadingItemRunnable(qt.QRunnable):
    """Runner to process item loading from a file"""

    class __Signals(qt.QObject):
        """Signal holder"""
        itemReady = qt.Signal(object, object, object)
        runnerFinished = qt.Signal(object)

    def __init__(self, filename, item):
        """Constructor

        :param LoadingItemWorker worker: Object holding data and signals
        """
        super(LoadingItemRunnable, self).__init__()
        self.filename = filename
        self.oldItem = item
        self.signals = self.__Signals()

    def setFile(self, filename, item):
        self.filenames.append((filename, item))

    @property
    def itemReady(self):
        return self.signals.itemReady

    @property
    def runnerFinished(self):
        return self.signals.runnerFinished

    def __loadItemTree(self, oldItem, h5obj):
        """Create an item tree used by the GUI from an h5py object.

        :param Hdf5Node oldItem: The current item displayed the GUI
        :param h5py.File h5obj: The h5py object to display in the GUI
        :rtpye: Hdf5Node
        """
        text = _createRootLabel(h5obj)
        item = Hdf5Item(text=text, obj=h5obj, parent=oldItem.parent, populateAll=True)
        return item

    @qt.Slot()
    def run(self):
        """Process the file loading. The worker is used as holder
        of the data and the signal. The result is sent as a signal.
        """
        h5file = None
        try:
            h5file = silx_io.open(self.filename)
            newItem = self.__loadItemTree(self.oldItem, h5file)
            error = None
        except IOError as e:
            # Should be logged
            error = e
            newItem = None
            if h5file is not None:
                h5file.close()

        # Take care of None value in case of PySide
        newItem = _wrapNone(newItem)
        error = _wrapNone(error)
        self.itemReady.emit(self.oldItem, newItem, error)
        self.runnerFinished.emit(self)

    def autoDelete(self):
        return True


class Hdf5TreeModel(qt.QAbstractItemModel):
    """Tree model storing a list of :class:`h5py.File` like objects.

    The main column display the :class:`h5py.File` list and there hierarchy.
    Other columns display information on node hierarchy.
    """

    H5PY_ITEM_ROLE = qt.Qt.UserRole
    """Role to reach h5py item from an item index"""

    H5PY_OBJECT_ROLE = qt.Qt.UserRole + 1
    """Role to reach h5py object from an item index"""

    USER_ROLE = qt.Qt.UserRole + 2
    """Start of range of available user role for derivative models"""

    NAME_COLUMN = 0
    """Column id containing HDF5 node names"""

    TYPE_COLUMN = 1
    """Column id containing HDF5 dataset types"""

    SHAPE_COLUMN = 2
    """Column id containing HDF5 dataset shapes"""

    VALUE_COLUMN = 3
    """Column id containing HDF5 dataset values"""

    DESCRIPTION_COLUMN = 4
    """Column id containing HDF5 node description/title/message"""

    NODE_COLUMN = 5
    """Column id containing HDF5 node type"""

    LINK_COLUMN = 6
    """Column id containing HDF5 link type"""

    COLUMN_IDS = [
        NAME_COLUMN,
        TYPE_COLUMN,
        SHAPE_COLUMN,
        VALUE_COLUMN,
        DESCRIPTION_COLUMN,
        NODE_COLUMN,
        LINK_COLUMN,
    ]
    """List of logical columns available"""

    def __init__(self, parent=None):
        super(Hdf5TreeModel, self).__init__(parent)

        self.header_labels = [None] * len(self.COLUMN_IDS)
        self.header_labels[self.NAME_COLUMN] = 'Name'
        self.header_labels[self.TYPE_COLUMN] = 'Type'
        self.header_labels[self.SHAPE_COLUMN] = 'Shape'
        self.header_labels[self.VALUE_COLUMN] = 'Value'
        self.header_labels[self.DESCRIPTION_COLUMN] = 'Description'
        self.header_labels[self.NODE_COLUMN] = 'Node'
        self.header_labels[self.LINK_COLUMN] = 'Link'

        # Create items
        self.__root = Hdf5Node()
        self.__fileDropEnabled = True
        self.__fileMoveEnabled = True

        self.__animatedIcon = icons.getWaitIcon()
        self.__animatedIcon.iconChanged.connect(self.__updateLoadingItems)
        self.__runnerSet = set([])

        # store used icons to avoid the cache to release it
        self.__icons = []
        self.__icons.append(icons.getQIcon("item-none"))
        self.__icons.append(icons.getQIcon("item-0dim"))
        self.__icons.append(icons.getQIcon("item-1dim"))
        self.__icons.append(icons.getQIcon("item-2dim"))
        self.__icons.append(icons.getQIcon("item-3dim"))
        self.__icons.append(icons.getQIcon("item-ndim"))

        self.__openedFiles = []
        """Store the list of files opened by the model itself."""
        # FIXME: It should managed one by one by Hdf5Item itself

    def __del__(self):
        self._closeOpened()
        s = super(Hdf5TreeModel, self)
        if hasattr(s, "__del__"):
            # else it fail on Python 3
            s.__del__()

    def _closeOpened(self):
        """Close files which was opened by this model.

        This function may be removed in the future.

        File are opened by the model when it was inserted using
        `insertFileAsync`, `insertFile`, `appendFile`."""
        for h5file in self.__openedFiles:
            h5file.close()
        self.__openedFiles = []

    def __updateLoadingItems(self, icon):
        for i in range(self.__root.childCount()):
            item = self.__root.child(i)
            if isinstance(item, Hdf5LoadingItem):
                index1 = self.index(i, 0, qt.QModelIndex())
                index2 = self.index(i, self.columnCount() - 1, qt.QModelIndex())
                self.dataChanged.emit(index1, index2)

    def __itemReady(self, oldItem, newItem, error):
        """Called at the end of a concurent file loading, when the loading
        item is ready. AN error is defined if an exception occured when
        loading the newItem .

        :param Hdf5Node oldItem: current displayed item
        :param Hdf5Node newItem: item loaded, or None if error is defined
        :param Exception error: An exception, or None if newItem is defined
        """
        # Take care of None value in case of PySide
        newItem = _unwrapNone(newItem)
        error = _unwrapNone(error)
        row = self.__root.indexOfChild(oldItem)
        rootIndex = qt.QModelIndex()
        self.beginRemoveRows(rootIndex, row, row)
        self.__root.removeChildAtIndex(row)
        self.endRemoveRows()
        if newItem is not None:
            self.__openedFiles.append(newItem.obj)
            self.beginInsertRows(rootIndex, row, row)
            self.__root.insertChild(row, newItem)
            self.endInsertRows()
        # FIXME the error must be displayed

    def isFileDropEnabled(self):
        return self.__fileDropEnabled

    def setFileDropEnabled(self, enabled):
        self.__fileDropEnabled = enabled

    fileDropEnabled = qt.Property(bool, isFileDropEnabled, setFileDropEnabled)
    """Property to enable/disable file dropping in the model."""

    def isFileMoveEnabled(self):
        return self.__fileMoveEnabled

    def setFileMoveEnabled(self, enabled):
        self.__fileMoveEnabled = enabled

    fileMoveEnabled = qt.Property(bool, isFileMoveEnabled, setFileMoveEnabled)
    """Property to enable/disable drag-and-drop of files to
    change the ordering in the model."""

    def supportedDropActions(self):
        if self.__fileMoveEnabled or self.__fileDropEnabled:
            return qt.Qt.CopyAction | qt.Qt.MoveAction
        else:
            return 0

    def mimeTypes(self):
        if self.__fileMoveEnabled:
            return [_utils.Hdf5NodeMimeData.MIME_TYPE]
        else:
            return []

    def mimeData(self, indexes):
        """
        Returns an object that contains serialized items of data corresponding
        to the list of indexes specified.

        :param list(qt.QModelIndex) indexes: List of indexes
        :rtype: qt.QMimeData
        """
        if not self.__fileMoveEnabled or len(indexes) == 0:
            return None

        indexes = [i for i in indexes if i.column() == 0]
        if len(indexes) > 1:
            raise NotImplementedError("Drag of multi rows is not implemented")
        if len(indexes) == 0:
            raise NotImplementedError("Drag of cell is not implemented")

        node = self.nodeFromIndex(indexes[0])
        mimeData = _utils.Hdf5NodeMimeData(node)
        return mimeData

    def flags(self, index):
        defaultFlags = qt.QAbstractItemModel.flags(self, index)

        if index.isValid():
            node = self.nodeFromIndex(index)
            if self.__fileMoveEnabled and node.parent is self.__root:
                # that's a root
                return qt.Qt.ItemIsDragEnabled | defaultFlags
            return defaultFlags
        elif self.__fileDropEnabled or self.__fileMoveEnabled:
            return qt.Qt.ItemIsDropEnabled | defaultFlags
        else:
            return defaultFlags

    def dropMimeData(self, mimedata, action, row, column, parentIndex):
        if action == qt.Qt.IgnoreAction:
            return True

        if self.__fileMoveEnabled and mimedata.hasFormat(_utils.Hdf5NodeMimeData.MIME_TYPE):
            dragNode = mimedata.node()
            parentNode = self.nodeFromIndex(parentIndex)
            if parentNode is not dragNode.parent:
                return False

            if row == -1:
                # append to the parent
                row = parentNode.childCount()
            else:
                # insert at row
                pass

            dragNodeParent = dragNode.parent
            sourceRow = dragNodeParent.indexOfChild(dragNode)
            self.moveRow(parentIndex, sourceRow, parentIndex, row)
            return True

        if self.__fileDropEnabled and mimedata.hasFormat("text/uri-list"):

            parentNode = self.nodeFromIndex(parentIndex)
            if parentNode is not self.__root:
                while(parentNode is not self.__root):
                    node = parentNode
                    parentNode = node.parent
                row = parentNode.indexOfChild(node)
            else:
                if row == -1:
                    row = self.__root.childCount()

            messages = []
            for url in mimedata.urls():
                try:
                    self.insertFileAsync(url.toLocalFile(), row)
                    row += 1
                except IOError as e:
                    messages.append(e.args[0])
            if len(messages) > 0:
                title = "Error occurred when loading files"
                message = "<html>%s:<ul><li>%s</li><ul></html>" % (title, "</li><li>".join(messages))
                qt.QMessageBox.critical(None, title, message)
            return True

        return False

    def headerData(self, section, orientation, role=qt.Qt.DisplayRole):
        if orientation == qt.Qt.Horizontal:
            if role in [qt.Qt.DisplayRole, qt.Qt.EditRole]:
                return self.header_labels[section]
        return None

    def insertNode(self, row, node):
        if row == -1:
            row = self.__root.childCount()
        self.beginInsertRows(qt.QModelIndex(), row, row)
        self.__root.insertChild(row, node)
        self.endInsertRows()

    def moveRow(self, sourceParentIndex, sourceRow, destinationParentIndex, destinationRow):
        if sourceRow == destinationRow or sourceRow == destinationRow - 1:
            # abort move, same place
            return
        return self.moveRows(sourceParentIndex, sourceRow, 1, destinationParentIndex, destinationRow)

    def moveRows(self, sourceParentIndex, sourceRow, count, destinationParentIndex, destinationRow):
        self.beginMoveRows(sourceParentIndex, sourceRow, sourceRow, destinationParentIndex, destinationRow)
        sourceNode = self.nodeFromIndex(sourceParentIndex)
        destinationNode = self.nodeFromIndex(destinationParentIndex)

        if sourceNode is destinationNode and sourceRow < destinationRow:
            item = sourceNode.child(sourceRow)
            destinationNode.insertChild(destinationRow, item)
            sourceNode.removeChildAtIndex(sourceRow)
        else:
            item = sourceNode.removeChildAtIndex(sourceRow)
            destinationNode.insertChild(destinationRow, item)

        self.endMoveRows()
        return True

    def index(self, row, column, parent=qt.QModelIndex()):
        try:
            node = self.nodeFromIndex(parent)
            return self.createIndex(row, column, node.child(row))
        except IndexError:
            return qt.QModelIndex()

    def data(self, index, role=qt.Qt.DisplayRole):
        node = self.nodeFromIndex(index)

        if role == self.H5PY_ITEM_ROLE:
            return node

        if role == self.H5PY_OBJECT_ROLE:
            return node.obj

        if index.column() == self.NAME_COLUMN:
            return node.dataName(role)
        elif index.column() == self.TYPE_COLUMN:
            return node.dataType(role)
        elif index.column() == self.SHAPE_COLUMN:
            return node.dataShape(role)
        elif index.column() == self.VALUE_COLUMN:
            return node.dataValue(role)
        elif index.column() == self.DESCRIPTION_COLUMN:
            return node.dataDescription(role)
        elif index.column() == self.NODE_COLUMN:
            return node.dataNode(role)
        elif index.column() == self.LINK_COLUMN:
            return node.dataLink(role)
        else:
            return None

    def columnCount(self, parent=qt.QModelIndex()):
        return len(self.COLUMN_IDS)

    def hasChildren(self, parent=qt.QModelIndex()):
        node = self.nodeFromIndex(parent)
        if node is None:
            return 0
        return node.hasChildren()

    def rowCount(self, parent=qt.QModelIndex()):
        node = self.nodeFromIndex(parent)
        if node is None:
            return 0
        return node.childCount()

    def parent(self, child):
        if not child.isValid():
            return qt.QModelIndex()

        node = self.nodeFromIndex(child)

        if node is None:
            return qt.QModelIndex()

        parent = node.parent

        if parent is None:
            return qt.QModelIndex()

        grandparent = parent.parent
        if grandparent is None:
            return qt.QModelIndex()
        row = grandparent.indexOfChild(parent)

        assert row != - 1
        return self.createIndex(row, 0, parent)

    def nodeFromIndex(self, index):
        return index.internalPointer() if index.isValid() else self.__root

    def synchronizeIndex(self, index):
        """
        Synchronize a file a given its index.

        Basically close it and load it again.

        :param qt.QModelIndex index: Index of the item to update
        """
        node = self.nodeFromIndex(index)
        if node.parent is not self.__root:
            return

        self.removeIndex(index)
        filename = node.obj.filename
        node.obj.close()
        self.insertFileAsync(filename, index.row())

    def synchronizeH5pyObject(self, h5pyObject):
        """
        Synchronize a h5py object in all the tree.

        Basically close it and load it again.

        :param h5py.File h5pyObject: A :class:`h5py.File` object.
        """
        index = 0
        while index < self.__root.childCount():
            item = self.__root.child(index)
            if item.obj is h5pyObject:
                qindex = self.index(index, 0, qt.QModelIndex())
                self.synchronizeIndex(qindex)
            else:
                index += 1

    def removeIndex(self, index):
        """
        Remove an item from the model using its index.

        :param qt.QModelIndex index: Index of the item to remove
        """
        node = self.nodeFromIndex(index)
        if node.parent is not self.__root:
            return
        self.beginRemoveRows(qt.QModelIndex(), index.row(), index.row())
        self.__root.removeChildAtIndex(index.row())
        self.endRemoveRows()

    def removeH5pyObject(self, h5pyObject):
        """
        Remove an item from the model using the holding h5py object.
        It can remove more than one item.

        :param h5py.File h5pyObject: A :class:`h5py.File` object.
        """
        index = 0
        while index < self.__root.childCount():
            item = self.__root.child(index)
            if item.obj is h5pyObject:
                qindex = self.index(index, 0, qt.QModelIndex())
                self.removeIndex(qindex)
            else:
                index += 1

    def insertH5pyObject(self, h5pyObject, text=None, row=-1):
        """Append an HDF5 object from h5py to the tree.

        :param h5pyObject: File handle/descriptor for a :class:`h5py.File`
            or any other class of h5py file structure.
        """
        if text is None:
            text = _createRootLabel(h5pyObject)
        if row == -1:
            row = self.__root.childCount()
        self.insertNode(row, Hdf5Item(text=text, obj=h5pyObject, parent=self.__root))

    def insertFileAsync(self, filename, row=-1):
        if not os.path.isfile(filename):
            raise IOError("Filename '%s' must be a file path" % filename)

        # create temporary item
        text = os.path.basename(filename)
        item = Hdf5LoadingItem(text=text, parent=self.__root, animatedIcon=self.__animatedIcon)
        self.insertNode(row, item)

        # start loading the real one
        runnable = LoadingItemRunnable(filename, item)
        runnable.itemReady.connect(self.__itemReady)
        self.__runnerSet.add(runnable)
        runnable.runnerFinished.connect(self.__releaseRunner)
        qt.QThreadPool.globalInstance().start(runnable)

    def __releaseRunner(self, runner):
        self.__runnerSet.remove(runner)

    def insertFile(self, filename, row=-1):
        """Load a HDF5 file into the data model.

        :param filename: file path.
        """
        try:
            h5file = silx_io.open(filename)
            self.__openedFiles.append(h5file)
            self.insertH5pyObject(h5file, row=row)
        except IOError:
            _logger.debug("File '%s' can't be read.", filename, exc_info=True)
            raise

    def appendFile(self, filename):
        self.insertFile(filename, -1)