orange / Orange / OrangeWidgets / OWItemModels.py

  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
from __future__ import with_statement

from xml.sax.saxutils import escape

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from functools import wraps, partial
from collections import defaultdict
from contextlib import contextmanager

class _store(dict):
    pass

def _argsort(seq, cmp=None, key=None, reverse=False):
    if key is not None:
        items = sorted(zip(range(len(seq)), seq), key=lambda i,v: key(v))
    elif cmp is not None:
        items = sorted(zip(range(len(seq)), seq), cmp=lambda a,b: cmp(a[1], b[1]))
    else:
        items = sorted(zip(range(len(seq)), seq), key=seq.__getitem__)
    if reverse:
        items = reversed(items)
    return items


@contextmanager
def signal_blocking(object):
    blocked = object.signalsBlocked()
    object.blockSignals(True)
    yield
    object.blockSignals(blocked)


class PyListModel(QAbstractListModel):
    """ A model for displaying python list like objects in Qt item view classes
    """
    MIME_TYPES = ["application/x-Orange-PyListModelData"]

    def __init__(self, iterable=[], parent=None,
                 flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled,
                 list_item_role=Qt.DisplayRole,
                 supportedDropActions=Qt.MoveAction):
        QAbstractListModel.__init__(self, parent)
        self._list = []
        self._other_data = []
        self._flags = flags
        self.list_item_role = list_item_role

        self._supportedDropActions = supportedDropActions
        self.extend(iterable)

    def _is_index_valid_for(self, index, list_like):
        if isinstance(index, QModelIndex) and index.isValid() :
            row, column = index.row(), index.column()
            return row < len(list_like) and row >= 0 and column == 0
        elif isinstance(index, int):
            return index < len(list_like) and index > -len(self)
        else:
            return False

    def wrap(self, list):
        """ Wrap the list with this model. All changes to the model
        are done in place on the passed list
        """
        self._list = list
        self._other_data = [_store() for _ in list]
        self.reset()

    def index(self, row, column=0, parent=QModelIndex()):
        if self._is_index_valid_for(row, self) and column == 0:
            return QAbstractListModel.createIndex(self, row, column, parent)
        else:
            return QModelIndex()

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return QVariant(str(section))

    def rowCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else len(self)

    def columnCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else 1

    def data(self, index, role=Qt.DisplayRole):
        row = index.row()
        if role in [self.list_item_role, Qt.EditRole] \
                and self._is_index_valid_for(index, self):
            return QVariant(self[row])
        elif self._is_index_valid_for(row, self._other_data):
            return QVariant(self._other_data[row].get(role, QVariant()))
        else:
            return QVariant()

    def itemData(self, index):
        map = QAbstractListModel.itemData(self, index)
        if self._is_index_valid_for(index, self._other_data):
            items = self._other_data[index.row()].items()
        else:
            items = []

        for key, value in items:
            map[key] = QVariant(value)

        return map

    def parent(self, index=QModelIndex()):
        return QModelIndex()

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole and self._is_index_valid_for(index, self):
            obj = value.toPyObject()
            self[index.row()] = obj # Will emit proper dataChanged signal
            return True
        elif self._is_index_valid_for(index, self._other_data):
            self._other_data[index.row()][role] = value
            self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
            return True
        else:
            return False

    def setItemData(self, index, data):
        data = dict(data)
        with signal_blocking(self):
            for role, value in data.items():
                if role == Qt.EditRole and \
                        self._is_index_valid_for(index, self):
                    self[index.row()] = value.toPyObject()
                elif self._is_index_valid_for(index, self._other_data):
                    self._other_data[index.row()][role] = value

        self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
        return True

    def flags(self, index):
        if self._is_index_valid_for(index, self._other_data):
            return self._other_data[index.row()].get("flags", self._flags)
        else:
            return self._flags | Qt.ItemIsDropEnabled

    def insertRows(self, row, count, parent=QModelIndex()):
        """ Insert ``count`` rows at ``row``, the list fill be filled 
        with ``None`` 
        """
        if not parent.isValid():
            self.__setslice__(row, row, [None] * count)
            return True
        else:
            return False

    def removeRows(self, row, count, parent=QModelIndex()):
        """Remove ``count`` rows starting at ``row``
        """
        if not parent.isValid():
            self.__delslice__(row, row + count)
            return True
        else:
            return False

    def extend(self, iterable):
        list_ = list(iterable)
        self.beginInsertRows(QModelIndex(), len(self), len(self) + len(list_) - 1)
        self._list.extend(list_)
        self._other_data.extend([_store() for _ in list_])
        self.endInsertRows()

    def append(self, item):
        self.extend([item])

    def insert(self, i, val):
        self.beginInsertRows(QModelIndex(), i, i)
        self._list.insert(i, val)
        self._other_data.insert(i, _store())
        self.endInsertRows()

    def remove(self, val):
        i = self._list.index(val)
        self.__delitem__(i)

    def pop(self, i):
        item = self._list[i]
        self.__delitem__(i)
        return item

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

    def __iter__(self):
        return iter(self._list)

    def __getitem__(self, i):
        return self._list[i]

    def __getslice__(self, i, j):
        return self._list[i:j]

    def __add__(self, iterable):
        new_list = PyListModel(list(self._list), 
                           self.parent(),
                           flags=self._flags,
                           list_item_role=self.list_item_role,
                           supportedDropActions=self.supportedDropActions()
                           )
        new_list._other_data = list(self._other_data)
        new_list.extend(iterable)
        return new_list

    def __iadd__(self, iterable):
        self.extend(iterable)

    def __delitem__(self, i):
        self.beginRemoveRows(QModelIndex(), i, i)
        del self._list[i]
        del self._other_data[i]
        self.endRemoveRows()

    def __delslice__(self, i, j):
        max_i = len(self)
        i = max(0, min(i, max_i))
        j = max(0, min(j, max_i))

        if j > i and i < max_i:
            self.beginRemoveRows(QModelIndex(), i, j - 1)
            del self._list[i:j]
            del self._other_data[i:j]
            self.endRemoveRows()

    def __setitem__(self, i, value):
        self._list[i] = value
        self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(i), self.index(i))

    def __setslice__(self, i, j, iterable):
        self.__delslice__(i, j)
        all = list(iterable)
        if len(all):
            self.beginInsertRows(QModelIndex(), i, i + len(all) - 1)
            self._list[i:i] = all
            self._other_data[i:i] = [_store() for _ in all]
            self.endInsertRows()

    def reverse(self):
        self._list.reverse()
        self._other_data.reverse()
        self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(0), self.index(len(self) -1))

    def sort(self, *args, **kwargs):
        indices = _argsort(self._list, *args, **kwargs)
        list = [self._list[i] for i in indices]
        other = [self._other_data[i] for i in indices]
        for i, new_l, new_o in enumerate(zip(list, other)):
            self._list[i] = new_l
            self._other_data[i] = new_o
        self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(0), self.index(len(self) -1))

    def __repr__(self):
        return "PyListModel(%s)" % repr(self._list)

    def __nonzero__(self):
        return len(self) != 0

    #for Python 3000
    def __bool__(self):
        return len(self) != 0

    def emitDataChanged(self, indexList):
        if isinstance(indexList, int):
            indexList = [indexList]

        #TODO: group indexes into ranges
        for ind in indexList:
            self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(ind), self.index(ind))

    ###########
    # Drag/drop
    ###########

    def supportedDropActions(self):
        return self._supportedDropActions

    def decode_qt_data(self, data):
        """ Decode internal Qt 'application/x-qabstractitemmodeldatalist'
        mime data 
        """
        stream = QDataStream(data)
        items = []
        while not stream.atEnd():
            row = ds.readInt()
            col = ds.readInt()
            item_count = ds.readInt()
            item = {}
            for i in range(item_count):
                role = ds.readInt()
                value = ds.readQVariant()
                item[role] = value
            items.append((row, column, item))
        return items

    def mimeTypes(self):
        return self.MIME_TYPES + list(QAbstractListModel.mimeTypes(self))

    def mimeData(self, indexlist):
        if len(indexlist) <= 0:
            return None

        items = [self[i.row()] for i in indexlist]
        mime = QAbstractListModel.mimeData(self, indexlist)
        data = cPickle.dumps(vars)
        mime.setData(self.MIME_TYPE, QByteArray(data))
        mime._items = items
        return mime

    def dropMimeData(self, mime, action, row, column, parent):
        if action == Qt.IgnoreAction:
            return True

        if not mime.hasFormat(self.MIME_TYPE):
            return False

        if hasattr(mime, "_vars"):
            vars = mime._vars
        else:
            desc = str(mime.data(self.MIME_TYPE))
            vars = cPickle.loads(desc)

        return QAbstractListModel.dropMimeData(self, mime, action, row, column, parent)


import OWGUI
import orange
import Orange
import cPickle


def feature_tooltip(feature):
    if isinstance(feature, Orange.feature.Discrete):
        return discrete_feature_tooltip(feature)
    elif isinstance(feature, Orange.feature.Continuous):
        return continuous_feature_toltip(feature)
    elif isinstance(feature, Orange.feature.String):
        return string_feature_tooltip(feature)
    elif isinstance(feature, Orange.feature.Python):
        return python_feature_tooltip(feature)
    elif isinstance(feature, Orange.feature.Descriptor):
        return generic_feature_tooltip(feature)
    else:
        raise TypeError("Expected an instance of 'Orange.feature.Descriptor'")


def feature_labels_tooltip(feature):
    text = ""
    if feature.attributes:
        items = feature.attributes.items()
        items = [(escape(key), escape(value)) for key, value in items]
        labels = map("%s = %s".__mod__, items)
        text += "<br/>Feature Labels:<br/>"
        text += "<br/>".join(labels)
    return text


def discrete_feature_tooltip(feature):
    text = ("<b>%s</b><br/>Discrete with %i values: " %
            (escape(feature.name), len(feature.values)))
    text += ", ".join("%r" % escape(v) for v in feature.values)
    text += feature_labels_tooltip(feature)
    return text


def continuous_feature_toltip(feature):
    text = "<b>%s</b><br/>Continuous" % escape(feature.name)
    text += feature_labels_tooltip(feature)
    return text


def string_feature_tooltip(feature):
    text = "<b>%s</b><br/>String" % escape(feature.name)
    text += feature_labels_tooltip(feature)
    return text


def python_feature_tooltip(feature):
    text = "<b>%s</b><br/>Python" % escape(feature.name)
    text += feature_labels_tooltip(feature)
    return text


def generic_feature_tooltip(feature):
    text = "<b>%s</b><br/>%s" % (escape(feature.name), type(feature).__name__)
    text += feature_labels_tooltip(feature)
    return text


class VariableListModel(PyListModel):

    MIME_TYPE = "application/x-Orange-VariableList"

    def data(self, index, role=Qt.DisplayRole):
        if self._is_index_valid_for(index, self):
            i = index.row()
            var = self[i]
            if role == Qt.DisplayRole:
                return QVariant(var.name)
            elif role == Qt.DecorationRole:
                return QVariant(OWGUI.getAttributeIcons().get(var.varType, -1))
            elif role == Qt.ToolTipRole:
                return QVariant(self.variable_tooltip(var))
            else:
                return PyListModel.data(self, index, role)
        else:
            return QVariant()

    def variable_tooltip(self, var):
        if isinstance(var, Orange.feature.Discrete):
            return self.discrete_variable_tooltip(var)
        elif isinstance(var, Orange.feature.Continuous):
            return self.continuous_variable_toltip(var)
        elif isinstance(var, Orange.feature.String):
            return self.string_variable_tooltip(var)

    def variable_labels_tooltip(self, var):
        return feature_labels_tooltip(var)

    def discrete_variable_tooltip(self, var):
        return discrete_feature_tooltip(var)

    def continuous_variable_toltip(self, var):
        return continuous_feature_toltip(var)

    def string_variable_tooltip(self, var):
        return string_feature_tooltip(var)

    def python_variable_tooltip(self, var):
        return python_feature_tooltip(var)


_html_replace = [("<", "&lt;"), (">", "&gt;")]

def safe_text(text):
    for old, new in _html_replace:
        text = text.replace(old, new)
    return text

class VariableEditor(QWidget):
    def __init__(self, var, parent):
        QWidget.__init__(self, parent)
        self.var = var
        layout = QHBoxLayout()
        self._attrs = OWGUI.getAttributeIcons()
        self.type_cb = QComboBox(self)
        for attr, icon in self._attrs.items():
            if attr != -1:
                self.type_cb.addItem(icon, str(attr))
        layout.addWidget(self.type_cb)
        
        self.name_le = QLineEdit(self)
        layout.addWidget(self.name_le)
        
        self.setLayout(layout)
        
        self.connect(self.type_cb, SIGNAL("currentIndexChanged(int)"), self.edited)
        self.connect(self.name_le, SIGNAL("editingFinished()"), self.edited)
    
    def edited(self, *args):
        self.emit(SIGNAL("edited()"))
         
    def setData(self, type, name):
        self.type_cb.setCurrentIndex(self._attr.keys().index(type))
        self.name_le.setText(name)
        
class EnumVariableEditor(VariableEditor):
    def __init__(self, var, parent):
        VariableEditor.__init__(self, var, parent)
        
class FloatVariableEditor(QLineEdit):
    
    def setVariable(self, var):
        self.setText(str(var.name))
        
    def getVariable(self):
        return orange.FloatVariable(str(self.text()))

    
class StringVariableEditor(QLineEdit):
    def setVariable(self, var):
        self.setText(str(var.name))
        
    def getVariable(self):
        return orange.StringVariable(str(self.text()))
        
class VariableDelegate(QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        var = index.data(Qt.EditRole).toPyObject()
        if isinstance(var, orange.EnumVariable):
            return EnumVariableEditor(parent)
        elif isinstance(var, orange.FloatVariable):
            return FloatVariableEditor(parent)
        elif isinstance(var, orange.StringVariable):
            return StringVariableEditor(parent)
#        return VariableEditor(var, parent)
    
    def setEditorData(self, editor, index):
        var = index.data(Qt.EditRole).toPyObject()
        editor.variable = var
        
    def setModelData(self, editor, model, index):
        model.setData(index, QVariant(editor.variable), Qt.EditRole)
        
#    def displayText(self, value, locale):
#        return value.toPyObject().name
        
class ListSingleSelectionModel(QItemSelectionModel):
    """ Item selection model for list item models with single selection.
    
    Defines signal:
        - selectedIndexChanged(QModelIndex)
        
    """
    def __init__(self, model, parent=None):
        QItemSelectionModel.__init__(self, model, parent)
        self.connect(self, SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), self.onSelectionChanged)
        
    def onSelectionChanged(self, new, old):
        index = list(new.indexes())
        if index:
            index = index.pop()
        else:
            index = QModelIndex()
        self.emit(SIGNAL("selectedIndexChanged(QModelIndex)"), index)
        
    def selectedRow(self):
        """ Return QModelIndex of the selected row or invalid if no selection. 
        """
        rows = self.selectedRows()
        if rows:
            return rows[0]
        else:
            return QModelIndex()
        
    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):
        if isinstance(index, int):
            index = self.model().index(index)
        return QItemSelectionModel.select(self, index, flags)
    
        
class ModelActionsWidget(QWidget):
    def __init__(self, actions=[], parent=None, direction=QBoxLayout.LeftToRight):
        QWidget.__init__(self, parent)
        self.actions = []
        self.buttons = []
        layout = QBoxLayout(direction)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        for action in actions:
            self.addAction(action)
        self.setLayout(layout)
            
    def actionButton(self, action):
        if isinstance(action, QAction):
            button = QToolButton(self)
            button.setDefaultAction(action)
            return button
        elif isinstance(action, QAbstractButton):
            return action
            
    def insertAction(self, ind, action, *args):
        button = self.actionButton(action)
        self.layout().insertWidget(ind, button, *args)
        self.buttons.insert(ind, button)
        self.actions.insert(ind, action)
        return button
        
    def addAction(self, action, *args):
        return self.insertAction(-1, action, *args)

    
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.