-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
collectionseditor.py
1755 lines (1541 loc) · 65.7 KB
/
collectionseditor.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# ----------------------------------------------------------------------------
"""
Collections (i.e. dictionary, list, set and tuple) editor widget and dialog.
"""
#TODO: Multiple selection: open as many editors (array/dict/...) as necessary,
# at the same time
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
from __future__ import print_function
import datetime
import re
import sys
import warnings
# Third party imports
from qtpy.compat import getsavefilename, to_qvariant
from qtpy.QtCore import (QAbstractTableModel, QModelIndex, Qt,
Signal, Slot)
from qtpy.QtGui import QColor, QKeySequence
from qtpy.QtWidgets import (QAbstractItemView, QApplication, QDialog,
QHBoxLayout, QHeaderView, QInputDialog,
QLineEdit, QMenu, QMessageBox,
QPushButton, QTableView, QVBoxLayout,
QWidget)
from spyder_kernels.utils.misc import fix_reference_name
from spyder_kernels.utils.nsview import (
DataFrame, display_to_value, FakeObject,
get_color_name, get_human_readable_type, get_size, Image,
MaskedArray, ndarray, np_savetxt, Series, sort_against,
try_to_eval, unsorted_unique, value_to_display, get_object_attrs,
get_type_string, NUMERIC_NUMPY_TYPES)
# Local imports
from spyder.api.config.mixins import SpyderConfigurationAccessor
from spyder.config.base import _
from spyder.config.fonts import DEFAULT_SMALL_DELTA
from spyder.config.gui import get_font
from spyder.py3compat import (io, is_binary_string, PY3, to_text_string,
is_type_text_string, NUMERIC_TYPES)
from spyder.utils import icon_manager as ima
from spyder.utils.misc import getcwd_or_home
from spyder.utils.qthelpers import add_actions, create_action, mimedata2url
from spyder.utils.stringmatching import get_search_scores, get_search_regex
from spyder.plugins.variableexplorer.widgets.collectionsdelegate import (
CollectionsDelegate)
from spyder.plugins.variableexplorer.widgets.importwizard import ImportWizard
from spyder.widgets.helperwidgets import CustomSortFilterProxy
from spyder.plugins.variableexplorer.widgets.basedialog import BaseDialog
# Maximum length of a serialized variable to be set in the kernel
MAX_SERIALIZED_LENGHT = 1e6
LARGE_NROWS = 100
ROWS_TO_LOAD = 50
def natsort(s):
"""
Natural sorting, e.g. test3 comes before test100.
Taken from https://stackoverflow.com/a/16090640/3110740
"""
if not isinstance(s, (str, bytes)):
return s
x = [int(t) if t.isdigit() else t.lower() for t in re.split('([0-9]+)', s)]
return x
class ProxyObject(object):
"""Dictionary proxy to an unknown object."""
def __init__(self, obj):
"""Constructor."""
self.__obj__ = obj
def __len__(self):
"""Get len according to detected attributes."""
return len(get_object_attrs(self.__obj__))
def __getitem__(self, key):
"""Get the attribute corresponding to the given key."""
# Catch NotImplementedError to fix spyder-ide/spyder#6284 in pandas
# MultiIndex due to NA checking not being supported on a multiindex.
# Catch AttributeError to fix spyder-ide/spyder#5642 in certain special
# classes like xml when this method is called on certain attributes.
# Catch TypeError to prevent fatal Python crash to desktop after
# modifying certain pandas objects. Fix spyder-ide/spyder#6727.
# Catch ValueError to allow viewing and editing of pandas offsets.
# Fix spyder-ide/spyder#6728-
try:
attribute_toreturn = getattr(self.__obj__, key)
except (NotImplementedError, AttributeError, TypeError, ValueError):
attribute_toreturn = None
return attribute_toreturn
def __setitem__(self, key, value):
"""Set attribute corresponding to key with value."""
# Catch AttributeError to gracefully handle inability to set an
# attribute due to it not being writeable or set-table.
# Fix spyder-ide/spyder#6728.
# Also, catch NotImplementedError for safety.
try:
setattr(self.__obj__, key, value)
except (TypeError, AttributeError, NotImplementedError):
pass
except Exception as e:
if "cannot set values for" not in str(e):
raise
class ReadOnlyCollectionsModel(QAbstractTableModel):
"""CollectionsEditor Read-Only Table Model"""
sig_setting_data = Signal()
def __init__(self, parent, data, title="", names=False,
minmax=False, remote=False):
QAbstractTableModel.__init__(self, parent)
if data is None:
data = {}
self._parent = parent
self.scores = []
self.names = names
self.minmax = minmax
self.remote = remote
self.header0 = None
self._data = None
self.total_rows = None
self.showndata = None
self.keys = None
self.title = to_text_string(title) # in case title is not a string
if self.title:
self.title = self.title + ' - '
self.sizes = []
self.types = []
self.set_data(data)
def get_data(self):
"""Return model data"""
return self._data
def set_data(self, data, coll_filter=None):
"""Set model data"""
self._data = data
data_type = get_type_string(data)
if (coll_filter is not None and not self.remote and
isinstance(data, (tuple, list, dict, set))):
data = coll_filter(data)
self.showndata = data
self.header0 = _("Index")
if self.names:
self.header0 = _("Name")
if isinstance(data, tuple):
self.keys = list(range(len(data)))
self.title += _("Tuple")
elif isinstance(data, list):
self.keys = list(range(len(data)))
self.title += _("List")
elif isinstance(data, set):
self.keys = list(range(len(data)))
self.title += _("Set")
self._data = list(data)
elif isinstance(data, dict):
try:
self.keys = sorted(list(data.keys()), key=natsort)
except TypeError:
# This is necessary to display dictionaries with mixed
# types as keys.
# Fixes spyder-ide/spyder#13481
self.keys = list(data.keys())
self.title += _("Dictionary")
if not self.names:
self.header0 = _("Key")
else:
self.keys = get_object_attrs(data)
self._data = data = self.showndata = ProxyObject(data)
if not self.names:
self.header0 = _("Attribute")
if not isinstance(self._data, ProxyObject):
if len(self.keys) > 1:
elements = _("elements")
else:
elements = _("element")
self.title += (' (' + str(len(self.keys)) + ' ' + elements + ')')
else:
self.title += data_type
self.total_rows = len(self.keys)
if self.total_rows > LARGE_NROWS:
self.rows_loaded = ROWS_TO_LOAD
else:
self.rows_loaded = self.total_rows
self.sig_setting_data.emit()
self.set_size_and_type()
if len(self.keys):
# Needed to update search scores when
# adding values to the namespace
self.update_search_letters()
self.reset()
def set_size_and_type(self, start=None, stop=None):
data = self._data
if start is None and stop is None:
start = 0
stop = self.rows_loaded
fetch_more = False
else:
fetch_more = True
# Ignore pandas warnings that certain attributes are deprecated
# and will be removed, since they will only be accessed if they exist.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message=(r"^\w+\.\w+ is deprecated and "
"will be removed in a future version"))
if self.remote:
sizes = [data[self.keys[index]]['size']
for index in range(start, stop)]
types = [data[self.keys[index]]['type']
for index in range(start, stop)]
else:
sizes = [get_size(data[self.keys[index]])
for index in range(start, stop)]
types = [get_human_readable_type(data[self.keys[index]])
for index in range(start, stop)]
if fetch_more:
self.sizes = self.sizes + sizes
self.types = self.types + types
else:
self.sizes = sizes
self.types = types
def load_all(self):
"""Load all the data."""
self.fetchMore(number_to_fetch=self.total_rows)
def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method"""
def all_string(listlike):
return all([isinstance(x, str) for x in listlike])
reverse = (order == Qt.DescendingOrder)
sort_key = natsort if all_string(self.keys) else None
if column == 0:
self.sizes = sort_against(self.sizes, self.keys,
reverse=reverse,
sort_key=natsort)
self.types = sort_against(self.types, self.keys,
reverse=reverse,
sort_key=natsort)
try:
self.keys.sort(reverse=reverse, key=sort_key)
except:
pass
elif column == 1:
self.keys[:self.rows_loaded] = sort_against(self.keys,
self.types,
reverse=reverse)
self.sizes = sort_against(self.sizes, self.types, reverse=reverse)
try:
self.types.sort(reverse=reverse)
except:
pass
elif column == 2:
self.keys[:self.rows_loaded] = sort_against(self.keys,
self.sizes,
reverse=reverse)
self.types = sort_against(self.types, self.sizes, reverse=reverse)
try:
self.sizes.sort(reverse=reverse)
except:
pass
elif column in [3, 4]:
values = [self._data[key] for key in self.keys]
self.keys = sort_against(self.keys, values, reverse=reverse)
self.sizes = sort_against(self.sizes, values, reverse=reverse)
self.types = sort_against(self.types, values, reverse=reverse)
self.beginResetModel()
self.endResetModel()
def columnCount(self, qindex=QModelIndex()):
"""Array column number"""
if self._parent.proxy_model:
return 5
else:
return 4
def rowCount(self, index=QModelIndex()):
"""Array row number"""
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded
def canFetchMore(self, index=QModelIndex()):
if self.total_rows > self.rows_loaded:
return True
else:
return False
def fetchMore(self, index=QModelIndex(), number_to_fetch=None):
reminder = self.total_rows - self.rows_loaded
if number_to_fetch is not None:
items_to_fetch = min(reminder, number_to_fetch)
else:
items_to_fetch = min(reminder, ROWS_TO_LOAD)
self.set_size_and_type(self.rows_loaded,
self.rows_loaded + items_to_fetch)
self.beginInsertRows(QModelIndex(), self.rows_loaded,
self.rows_loaded + items_to_fetch - 1)
self.rows_loaded += items_to_fetch
self.endInsertRows()
def get_index_from_key(self, key):
try:
return self.createIndex(self.keys.index(key), 0)
except (RuntimeError, ValueError):
return QModelIndex()
def get_key(self, index):
"""Return current key"""
return self.keys[index.row()]
def get_value(self, index):
"""Return current value"""
if index.column() == 0:
return self.keys[ index.row() ]
elif index.column() == 1:
return self.types[ index.row() ]
elif index.column() == 2:
return self.sizes[ index.row() ]
else:
return self._data[ self.keys[index.row()] ]
def get_bgcolor(self, index):
"""Background color depending on value"""
if index.column() == 0:
color = QColor(Qt.lightGray)
color.setAlphaF(.05)
elif index.column() < 3:
color = QColor(Qt.lightGray)
color.setAlphaF(.2)
else:
color = QColor(Qt.lightGray)
color.setAlphaF(.3)
return color
def update_search_letters(self, text=""):
"""Update search letters with text input in search box."""
self.letters = text
names = [str(key) for key in self.keys]
results = get_search_scores(text, names, template='<b>{0}</b>')
if results:
self.normal_text, _, self.scores = zip(*results)
self.reset()
def row_key(self, row_num):
"""
Get row name based on model index.
Needed for the custom proxy model.
"""
return self.keys[row_num]
def row_type(self, row_num):
"""
Get row type based on model index.
Needed for the custom proxy model.
"""
return self.types[row_num]
def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 4 and role == Qt.DisplayRole:
# TODO: Check the effect of not hiding the column
# Treating search scores as a table column simplifies the
# sorting once a score for a specific string in the finder
# has been defined. This column however should always remain
# hidden.
return to_qvariant(self.scores[index.row()])
if index.column() == 3 and self.remote:
value = value['view']
if index.column() == 3:
display = value_to_display(value, minmax=self.minmax)
else:
if is_type_text_string(value):
display = to_text_string(value, encoding="utf-8")
elif not isinstance(value, NUMERIC_TYPES + NUMERIC_NUMPY_TYPES):
display = to_text_string(value)
else:
display = value
if role == Qt.UserRole:
if isinstance(value, NUMERIC_TYPES + NUMERIC_NUMPY_TYPES):
return to_qvariant(value)
else:
return to_qvariant(display)
elif role == Qt.DisplayRole:
return to_qvariant(display)
elif role == Qt.EditRole:
return to_qvariant(value_to_display(value))
elif role == Qt.TextAlignmentRole:
if index.column() == 3:
if len(display.splitlines()) < 3:
return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter))
else:
return to_qvariant(int(Qt.AlignLeft|Qt.AlignTop))
else:
return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter))
elif role == Qt.BackgroundColorRole:
return to_qvariant( self.get_bgcolor(index) )
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
return to_qvariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Overriding method headerData"""
if role != Qt.DisplayRole:
return to_qvariant()
i_column = int(section)
if orientation == Qt.Horizontal:
headers = (self.header0, _("Type"), _("Size"), _("Value"),
_("Score"))
return to_qvariant( headers[i_column] )
else:
return to_qvariant()
def flags(self, index):
"""Overriding method flags"""
# This method was implemented in CollectionsModel only, but to enable
# tuple exploration (even without editing), this method was moved here
if not index.isValid():
return Qt.ItemIsEnabled
return Qt.ItemFlags(int(QAbstractTableModel.flags(self, index) |
Qt.ItemIsEditable))
def reset(self):
self.beginResetModel()
self.endResetModel()
class CollectionsModel(ReadOnlyCollectionsModel):
"""Collections Table Model"""
def set_value(self, index, value):
"""Set value"""
self._data[ self.keys[index.row()] ] = value
self.showndata[ self.keys[index.row()] ] = value
self.sizes[index.row()] = get_size(value)
self.types[index.row()] = get_human_readable_type(value)
self.sig_setting_data.emit()
def get_bgcolor(self, index):
"""Background color depending on value"""
value = self.get_value(index)
if index.column() < 3:
color = ReadOnlyCollectionsModel.get_bgcolor(self, index)
else:
if self.remote:
color_name = value['color']
else:
color_name = get_color_name(value)
color = QColor(color_name)
color.setAlphaF(.2)
return color
def setData(self, index, value, role=Qt.EditRole):
"""Cell content change"""
if not index.isValid():
return False
if index.column() < 3:
return False
value = display_to_value(value, self.get_value(index),
ignore_errors=True)
self.set_value(index, value)
self.dataChanged.emit(index, index)
return True
class BaseHeaderView(QHeaderView):
"""
A header view for the BaseTableView that emits a signal when the width of
one of its sections is resized by the user.
"""
sig_user_resized_section = Signal(int, int, int)
def __init__(self, parent=None):
super(BaseHeaderView, self).__init__(Qt.Horizontal, parent)
self._handle_section_is_pressed = False
self.sectionResized.connect(self.sectionResizeEvent)
# Needed to enable sorting by column
# See spyder-ide/spyder#9835
self.setSectionsClickable(True)
def mousePressEvent(self, e):
super(BaseHeaderView, self).mousePressEvent(e)
self._handle_section_is_pressed = (self.cursor().shape() ==
Qt.SplitHCursor)
def mouseReleaseEvent(self, e):
super(BaseHeaderView, self).mouseReleaseEvent(e)
self._handle_section_is_pressed = False
def sectionResizeEvent(self, logicalIndex, oldSize, newSize):
if self._handle_section_is_pressed:
self.sig_user_resized_section.emit(logicalIndex, oldSize, newSize)
class BaseTableView(QTableView, SpyderConfigurationAccessor):
"""Base collection editor table view"""
CONF_SECTION = 'variable_explorer'
sig_files_dropped = Signal(list)
redirect_stdio = Signal(bool)
sig_free_memory_requested = Signal()
sig_editor_creation_started = Signal()
sig_editor_shown = Signal()
def __init__(self, parent):
super().__init__(parent=parent)
self.array_filename = None
self.menu = None
self.empty_ws_menu = None
self.paste_action = None
self.copy_action = None
self.edit_action = None
self.plot_action = None
self.hist_action = None
self.imshow_action = None
self.save_array_action = None
self.insert_action = None
self.insert_action_above = None
self.insert_action_below = None
self.remove_action = None
self.minmax_action = None
self.rename_action = None
self.duplicate_action = None
self.last_regex = ''
self.view_action = None
self.delegate = None
self.proxy_model = None
self.source_model = None
self.setAcceptDrops(True)
self.automatic_column_width = True
self.setHorizontalHeader(BaseHeaderView(parent=self))
self.horizontalHeader().sig_user_resized_section.connect(
self.user_resize_columns)
def setup_table(self):
"""Setup table"""
self.horizontalHeader().setStretchLastSection(True)
self.adjust_columns()
# Sorting columns
self.setSortingEnabled(True)
self.sortByColumn(0, Qt.AscendingOrder)
def setup_menu(self):
"""Setup context menu"""
resize_action = create_action(self, _("Resize rows to contents"),
triggered=self.resizeRowsToContents)
resize_columns_action = create_action(
self,
_("Resize columns to contents"),
triggered=self.resize_column_contents)
self.paste_action = create_action(self, _("Paste"),
icon=ima.icon('editpaste'),
triggered=self.paste)
self.copy_action = create_action(self, _("Copy"),
icon=ima.icon('editcopy'),
triggered=self.copy)
self.edit_action = create_action(self, _("Edit"),
icon=ima.icon('edit'),
triggered=self.edit_item)
self.plot_action = create_action(self, _("Plot"),
icon=ima.icon('plot'),
triggered=lambda: self.plot_item('plot'))
self.plot_action.setVisible(False)
self.hist_action = create_action(self, _("Histogram"),
icon=ima.icon('hist'),
triggered=lambda: self.plot_item('hist'))
self.hist_action.setVisible(False)
self.imshow_action = create_action(self, _("Show image"),
icon=ima.icon('imshow'),
triggered=self.imshow_item)
self.imshow_action.setVisible(False)
self.save_array_action = create_action(self, _("Save array"),
icon=ima.icon('filesave'),
triggered=self.save_array)
self.save_array_action.setVisible(False)
self.insert_action = create_action(
self, _("Insert"),
icon=ima.icon('insert'),
triggered=lambda: self.insert_item(below=False)
)
self.insert_action_above = create_action(
self, _("Insert above"),
icon=ima.icon('insert'),
triggered=lambda: self.insert_item(below=False)
)
self.insert_action_below = create_action(
self, _("Insert below"),
icon=ima.icon('insert'),
triggered=lambda: self.insert_item(below=True)
)
self.remove_action = create_action(self, _("Remove"),
icon=ima.icon('editdelete'),
triggered=self.remove_item)
self.rename_action = create_action(self, _("Rename"),
icon=ima.icon('rename'),
triggered=self.rename_item)
self.duplicate_action = create_action(self, _("Duplicate"),
icon=ima.icon('edit_add'),
triggered=self.duplicate_item)
self.view_action = create_action(
self,
_("View with the Object Explorer"),
icon=ima.icon('outline_explorer'),
triggered=self.view_item)
menu = QMenu(self)
menu_actions = [self.edit_action, self.plot_action, self.hist_action,
self.imshow_action, self.save_array_action,
self.insert_action,
self.insert_action_above, self.insert_action_below,
self.remove_action, self.copy_action,
self.paste_action, self.view_action,
None, self.rename_action, self.duplicate_action,
None, resize_action, resize_columns_action]
add_actions(menu, menu_actions)
self.empty_ws_menu = QMenu(self)
add_actions(
self.empty_ws_menu,
[self.insert_action, self.paste_action]
)
return menu
# ------ Remote/local API -------------------------------------------------
def remove_values(self, keys):
"""Remove values from data"""
raise NotImplementedError
def copy_value(self, orig_key, new_key):
"""Copy value"""
raise NotImplementedError
def new_value(self, key, value):
"""Create new value in data"""
raise NotImplementedError
def is_list(self, key):
"""Return True if variable is a list, a set or a tuple"""
raise NotImplementedError
def get_len(self, key):
"""Return sequence length"""
raise NotImplementedError
def is_array(self, key):
"""Return True if variable is a numpy array"""
raise NotImplementedError
def is_image(self, key):
"""Return True if variable is a PIL.Image image"""
raise NotImplementedError
def is_dict(self, key):
"""Return True if variable is a dictionary"""
raise NotImplementedError
def get_array_shape(self, key):
"""Return array's shape"""
raise NotImplementedError
def get_array_ndim(self, key):
"""Return array's ndim"""
raise NotImplementedError
def oedit(self, key):
"""Edit item"""
raise NotImplementedError
def plot(self, key, funcname):
"""Plot item"""
raise NotImplementedError
def imshow(self, key):
"""Show item's image"""
raise NotImplementedError
def show_image(self, key):
"""Show image (item is a PIL image)"""
raise NotImplementedError
#--------------------------------------------------------------------------
def refresh_menu(self):
"""Refresh context menu"""
index = self.currentIndex()
condition = index.isValid()
self.edit_action.setEnabled(condition)
self.remove_action.setEnabled(condition)
self.refresh_plot_entries(index)
def refresh_plot_entries(self, index):
if index.isValid():
if self.proxy_model:
key = self.proxy_model.get_key(index)
else:
key = self.source_model.get_key(index)
is_list = self.is_list(key)
is_array = self.is_array(key) and self.get_len(key) != 0
condition_plot = (is_array and len(self.get_array_shape(key)) <= 2)
condition_hist = (is_array and self.get_array_ndim(key) == 1)
condition_imshow = condition_plot and self.get_array_ndim(key) == 2
condition_imshow = condition_imshow or self.is_image(key)
else:
is_array = condition_plot = condition_imshow = is_list \
= condition_hist = False
is_list_instance = isinstance(self.source_model.get_data(), list)
self.plot_action.setVisible(condition_plot or is_list)
self.hist_action.setVisible(condition_hist or is_list)
self.insert_action.setVisible(not is_list_instance)
self.insert_action_above.setVisible(is_list_instance)
self.insert_action_below.setVisible(is_list_instance)
self.imshow_action.setVisible(condition_imshow)
self.save_array_action.setVisible(is_array)
def resize_column_contents(self):
"""Resize columns to contents."""
self.automatic_column_width = True
self.adjust_columns()
def user_resize_columns(self, logical_index, old_size, new_size):
"""Handle the user resize action."""
self.automatic_column_width = False
def adjust_columns(self):
"""Resize two first columns to contents"""
if self.automatic_column_width:
for col in range(3):
self.resizeColumnToContents(col)
def set_data(self, data):
"""Set table data"""
if data is not None:
self.source_model.set_data(data, self.dictfilter)
self.source_model.reset()
self.sortByColumn(0, Qt.AscendingOrder)
def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() != Qt.LeftButton:
QTableView.mousePressEvent(self, event)
return
index_clicked = self.indexAt(event.pos())
if index_clicked.isValid():
if index_clicked == self.currentIndex() \
and index_clicked in self.selectedIndexes():
self.clearSelection()
else:
QTableView.mousePressEvent(self, event)
else:
self.clearSelection()
event.accept()
def mouseDoubleClickEvent(self, event):
"""Reimplement Qt method"""
index_clicked = self.indexAt(event.pos())
if index_clicked.isValid():
row = index_clicked.row()
# TODO: Remove hard coded "Value" column number (3 here)
index_clicked = index_clicked.child(row, 3)
self.edit(index_clicked)
else:
event.accept()
def keyPressEvent(self, event):
"""Reimplement Qt methods"""
if event.key() == Qt.Key_Delete:
self.remove_item()
elif event.key() == Qt.Key_F2:
self.rename_item()
elif event == QKeySequence.Copy:
self.copy()
elif event == QKeySequence.Paste:
self.paste()
else:
QTableView.keyPressEvent(self, event)
def contextMenuEvent(self, event):
"""Reimplement Qt method"""
if self.source_model.showndata:
self.refresh_menu()
self.menu.popup(event.globalPos())
event.accept()
else:
self.empty_ws_menu.popup(event.globalPos())
event.accept()
def dragEnterEvent(self, event):
"""Allow user to drag files"""
if mimedata2url(event.mimeData()):
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
"""Allow user to move files"""
if mimedata2url(event.mimeData()):
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
"""Allow user to drop supported files"""
urls = mimedata2url(event.mimeData())
if urls:
event.setDropAction(Qt.CopyAction)
event.accept()
self.sig_files_dropped.emit(urls)
else:
event.ignore()
@Slot()
def edit_item(self):
"""Edit item"""
index = self.currentIndex()
if not index.isValid():
return
# TODO: Remove hard coded "Value" column number (3 here)
self.edit(index.child(index.row(), 3))
@Slot()
def remove_item(self, force=False):
"""Remove item"""
indexes = self.selectedIndexes()
if not indexes:
return
for index in indexes:
if not index.isValid():
return
if not force:
one = _("Do you want to remove the selected item?")
more = _("Do you want to remove all selected items?")
answer = QMessageBox.question(self, _("Remove"),
one if len(indexes) == 1 else more,
QMessageBox.Yes | QMessageBox.No)
if force or answer == QMessageBox.Yes:
if self.proxy_model:
idx_rows = unsorted_unique(
[self.proxy_model.mapToSource(idx).row()
for idx in indexes])
else:
idx_rows = unsorted_unique([idx.row() for idx in indexes])
keys = [self.source_model.keys[idx_row] for idx_row in idx_rows]
self.remove_values(keys)
def copy_item(self, erase_original=False, new_name=None):
"""Copy item"""
indexes = self.selectedIndexes()
if not indexes:
return
if self.proxy_model:
idx_rows = unsorted_unique(
[self.proxy_model.mapToSource(idx).row() for idx in indexes])
else:
idx_rows = unsorted_unique([idx.row() for idx in indexes])
if len(idx_rows) > 1 or not indexes[0].isValid():
return
orig_key = self.source_model.keys[idx_rows[0]]
if erase_original:
title = _('Rename')
field_text = _('New variable name:')
else:
title = _('Duplicate')
field_text = _('Variable name:')
data = self.source_model.get_data()
if isinstance(data, (list, set)):
new_key, valid = len(data), True
elif new_name is not None:
new_key, valid = new_name, True
else:
new_key, valid = QInputDialog.getText(self, title, field_text,
QLineEdit.Normal, orig_key)
if valid and to_text_string(new_key):
new_key = try_to_eval(to_text_string(new_key))
if new_key == orig_key:
return
self.copy_value(orig_key, new_key)
if erase_original:
self.remove_values([orig_key])
@Slot()
def duplicate_item(self):
"""Duplicate item"""
self.copy_item()
@Slot()
def rename_item(self, new_name=None):
"""Rename item"""
self.copy_item(erase_original=True, new_name=new_name)
@Slot()
def insert_item(self, below=True):
"""Insert item"""
index = self.currentIndex()
if not index.isValid():
row = self.source_model.rowCount()
else:
if self.proxy_model:
if below:
row = self.proxy_model.mapToSource(index).row() + 1
else:
row = self.proxy_model.mapToSource(index).row()
else:
if below:
row = index.row() + 1
else:
row = index.row()
data = self.source_model.get_data()
if isinstance(data, list):
key = row
data.insert(row, '')
elif isinstance(data, dict):
key, valid = QInputDialog.getText(self, _( 'Insert'), _( 'Key:'),
QLineEdit.Normal)
if valid and to_text_string(key):
key = try_to_eval(to_text_string(key))
else:
return
else:
return
value, valid = QInputDialog.getText(self, _('Insert'), _('Value:'),
QLineEdit.Normal)
if valid and to_text_string(value):
self.new_value(key, try_to_eval(to_text_string(value)))
@Slot()
def view_item(self):
"""View item with the Object Explorer"""
index = self.currentIndex()
if not index.isValid():
return
# TODO: Remove hard coded "Value" column number (3 here)
index = index.child(index.row(), 3)
self.delegate.createEditor(self, None, index, object_explorer=True)
def __prepare_plot(self):
try:
import guiqwt.pyplot #analysis:ignore
return True
except:
try:
if 'matplotlib' not in sys.modules:
import matplotlib
matplotlib.use("Qt4Agg")
return True
except:
QMessageBox.warning(self, _("Import error"),
_("Please install <b>matplotlib</b>"
" or <b>guiqwt</b>."))
def plot_item(self, funcname):
"""Plot item"""
index = self.currentIndex()
if self.__prepare_plot():
if self.proxy_model:
key = self.source_model.get_key(
self.proxy_model.mapToSource(index))
else:
key = self.source_model.get_key(index)
try:
self.plot(key, funcname)
except (ValueError, TypeError) as error:
QMessageBox.critical(self, _( "Plot"),
_("<b>Unable to plot data.</b>"
"<br><br>Error message:<br>%s"
) % str(error))
@Slot()
def imshow_item(self):