-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharraywidget.py
More file actions
2499 lines (2204 loc) · 116 KB
/
Copy patharraywidget.py
File metadata and controls
2499 lines (2204 loc) · 116 KB
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 © 2009-2012 Pierre Raybaut
# Copyright © 2015-2025 Gaëtan de Menten
# Licensed under the terms of the MIT License
# based on
# github.com/spyder-ide/spyder/blob/master/spyderlib/widgets/arrayeditor.py
"""
Array Editor Dialog based on Qt
"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Note that the canonical way to implement filters in a TableView would
# be to use a QSortFilterProxyModel. In this case, we would need to reimplement
# its filterAcceptsColumn and filterAcceptsRow methods. The problem is that
# it does not seem to be really designed for very large arrays and it would
# probably be too slow on those (I have read quite a few people complaining
# about speed issues with those) possibly because it suppose you have the whole
# array in your model. It would also probably not play well with the
# partial/progressive load we have currently implemented.
# TODO:
# * make it more obvious one can drag & drop axes names to reorder axes
# http://ux.stackexchange.com/questions/34158/
# how-to-make-it-obvious-that-you-can-drag-things-that-you-normally-cant
# * document paint speed experiments
# * filter on headers. In fact this is not a good idea, because that prevents
# selecting whole columns, which is handy. So a separate row for headers,
# like in Excel seems better.
# * tooltip on header with current filter
# * selection change -> select headers too
# * nicer error on plot with more than one row/column
# OR
# * plotting a subset should probably (to think) go via LArray/pandas objects
# so that I have the headers info in the plots (and do not have to deal with
# them manually)
# > ideally, I would like to keep this generic (not LArray-specific)
# ? automatic change digits on resize column
# => different format per column, which is problematic UI-wise
# * keyboard shortcut for filter each dim
# * tab in a filter combo, brings up next filter combo
# ? custom delegates for each type (spinner for int, checkbox for bool, ...)
# ? "light" headers (do not repeat the same header several times (on the screen)
# it would be nicer but I am not sure it is a good idea because with many
# dimensions, you can no longer see the current label for the first
# dimension(s) if you scroll down a bit. This is solvable if, instead
# of only the first line ever corresponding to the label displaying it,
# I could make it so that it is the first line displayable on the screen
# which gets it. It would be a bit less nice because of strange artifacts
# when scrolling, but would be more useful. The beauty problem could be
# solved later too via fading or something like that, but probably not
# worth it for a while.
import math
from pathlib import Path
import numpy as np
from qtpy import QtCore
from qtpy.QtCore import (Qt, QPoint, QItemSelection, QItemSelectionModel,
Signal, QSize, QModelIndex, QTimer)
from qtpy.QtGui import (QDoubleValidator, QIntValidator, QKeySequence, QFontMetrics, QCursor, QPixmap, QPainter, QIcon,
QWheelEvent, QMouseEvent)
from qtpy.QtWidgets import (QApplication, QTableView, QItemDelegate, QLineEdit, QCheckBox,
QMessageBox, QMenu, QLabel, QSpinBox, QWidget, QToolTip, QShortcut, QScrollBar,
QHBoxLayout, QVBoxLayout, QGridLayout, QSizePolicy, QFrame, QComboBox,
QStyleOptionViewItem, QPushButton)
from larray_editor.utils import (keybinding, create_action, clear_layout, get_default_font,
is_number_dtype, is_float_dtype, _,
LinearGradient, logger, cached_property, data_frac_digits,
num_int_digits)
from larray_editor.arrayadapter import (get_adapter, get_adapter_creator,
AbstractAdapter, MAX_FILTER_OPTIONS)
from larray_editor.arraymodel import (HLabelsArrayModel, VLabelsArrayModel, LabelsArrayModel,
AxesArrayModel, DataArrayModel)
from larray_editor.combo import FilterComboBox, CombinedSortFilterMenu
MORE_OPTIONS_NOT_SHOWN = "<more options not shown>"
# mime-type we use when drag and dropping axes (x- prefix is for unregistered
# types)
LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE = "application/x-larray-axis-index"
def display_selection(selection: QtCore.QItemSelection):
return ', '.join(f"<{idx.row()}, {idx.column()}>" for idx in selection.indexes())
def clip(value, minimum, maximum):
if value < minimum:
return minimum
elif value > maximum:
return maximum
else:
return value
# XXX: define Enum instead ?
TOP, BOTTOM = 0, 1
LEFT, RIGHT = 0, 1
MIN_COLUMN_WIDTH = 30
MAX_COLUMN_WIDTH = 800
DEFAULT_COLUMN_WIDTH = 64
DEFAULT_ROW_HEIGHT = 20
class FilterBar(QWidget):
def __init__(self, array_widget):
super().__init__()
# we are not passing array_widget as parent for QHBoxLayout because
# we could have the filterbar outside the widget
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
self.array_widget = array_widget
# See https://www.pythonguis.com/faq/pyqt-drag-drop-widgets/
# and https://zetcode.com/pyqt6/dragdrop/
self.setAcceptDrops(True)
self.drag_label = None
self.drag_start_pos = None
def reset_to_defaults(self):
layout = self.layout()
clear_layout(layout)
data_adapter = self.array_widget.data_adapter
if data_adapter is None:
return
assert isinstance(data_adapter, AbstractAdapter), \
f"unexpected data_adapter type: {type(data_adapter)}"
filter_names = data_adapter.get_filter_names()
# size > 0 to avoid arrays with length 0 axes and len(axes) > 0 to avoid scalars (scalar.size == 1)
if filter_names: #self.data_adapter.size > 0 and len(filters) > 0:
layout.addWidget(QLabel(_("Filters")))
for filter_idx, filter_name in enumerate(filter_names):
layout.addWidget(QLabel(filter_name))
filter_labels = data_adapter.get_filter_options(filter_idx)
# FIXME: on very large axes, this is getting too slow. Ideally the combobox should use a model which
# only fetch labels when they are needed to be displayed
# this needs a whole new widget though
if len(filter_labels) < 10000:
layout.addWidget(self.create_filter_combo(filter_idx, filter_labels))
else:
layout.addWidget(QLabel("too big to be filtered"))
layout.addStretch()
def create_filter_combo(self, filter_idx, filter_labels):
def filter_changed(checked_items):
self.change_filter(filter_idx, checked_items)
combo = FilterComboBox(self)
# TODO: mandate/assert that get_filter_options returns
# a sequence of strings instead of doing the conversion here.
# we use indices/positions to filter anyway
if (isinstance(filter_labels, np.ndarray) and
filter_labels.dtype.kind == 'M'):
# for datetime labels str(label) returns the integer
filter_labels = filter_labels.astype(str).tolist()
else:
filter_labels = [str(label) for label in filter_labels]
combo.addItems(filter_labels)
combo.checked_items_changed.connect(filter_changed)
return combo
def change_filter(self, filter_idx, indices):
logger.debug(f"FilterBar.change_filter({filter_idx}, {indices})")
# FIXME: the method can be called from the outside, and in that case
# the combos checked items need be synchronized too
array_widget = self.array_widget
data_adapter = array_widget.data_adapter
vscrollbar: ScrollBar = array_widget.vscrollbar
hscrollbar: ScrollBar = array_widget.hscrollbar
old_v_pos = vscrollbar.value()
old_h_pos = hscrollbar.value()
old_nrows, old_ncols = data_adapter.shape2d()
data_adapter.update_filter(filter_idx, indices)
data_adapter._current_sort = []
# TODO: this does too much work (it sets the adapters even
# if those do not change and sets v_offset/h_offset to 0 when we
# do not *always* want to do so) and maybe too little
# (update_range should probably be done elsewhere)
# this also reset() each model.
# For DataArrayModel it causes an extra (compared to the one
# below) update_range (via the modelReset signal)
array_widget._set_models_adapter()
new_nrows, new_ncols = data_adapter.shape2d()
hscrollbar.update_range()
vscrollbar.update_range()
array_widget.update_cell_sizes_from_content()
if old_v_pos == 0 and old_h_pos == 0:
# if the old values were already 0, visible_v/hscroll_changed will
# not be triggered and update_*_column_widths has no chance to run
# unless we call them explicitly
assert isinstance(array_widget, ArrayEditorWidget)
array_widget.update_cell_sizes_from_content()
else:
# TODO: would be nice to implement some clever positioning algorithm
# here when new_X != old_X so that the visible rows stay visible.
# Currently, this does not change the scrollbar value at all if
# the old value fits in the new range. When changing from one
# specific label to another of an larray, this does not change
# the shape of the result and is thus what we want but there
# are cases where we could do better.
# TODO: the setValue(0) should not be necessary in the case of
# new_nrows == old_nrows but it is currently because
# v/h_offset is set to 0 by the call to _set_models_adapter
# above but the scrollbar values do not change, so
# setValue(old_v_pos) does not trigger a valueChanged signal,
# and thus the v/h_offset is not set back to its old value
# if we don't first change the scrollbar values
vscrollbar.setValue(0)
hscrollbar.setValue(0)
# if the old value was already at 0, we do not need to set it again
if new_nrows == old_nrows and old_v_pos != 0:
vscrollbar.setValue(old_v_pos)
if new_ncols == old_ncols and old_h_pos != 0:
hscrollbar.setValue(old_h_pos)
# Check for left button mouse press events on axis labels
def mousePressEvent(self, event):
if event.button() != Qt.LeftButton:
return
click_pos = event.pos()
child = self.childAt(click_pos)
assert self.drag_label is None
if isinstance(child, QLabel) and child.text() != "Filters":
self.drag_label = child
self.drag_start_pos = click_pos
# If we release the left button before we moved the mouse enough to
# trigger the "real" dragging sequence (see mouveMoveEvent), we need to
# forget the drag_label and drag_start_pos
def mouseReleaseEvent(self, event):
if event.button() != Qt.LeftButton:
return
self.drag_label = None
self.drag_start_pos = None
# Mouse move events will occur only when a mouse button is pressed down,
# unless mouse tracking has been enabled with QWidget.setMouseTracking()
def mouseMoveEvent(self, event):
# We did not click on an axis label yet
drag_label = self.drag_label
if drag_label is None:
return
# We do not check the event button. The left button should still be
# pressed but event.button() will always be NoButton: "If the event type
# is MouseMove, the appropriate button for this event is Qt::NoButton"
# We are too close to where we initially clicked
drag_delta = event.pos() - self.drag_start_pos
if drag_delta.manhattanLength() < QApplication.startDragDistance():
return
from qtpy.QtCore import QMimeData, QByteArray
from qtpy.QtGui import QDrag
axis_index = self.layout().indexOf(drag_label) // 2
mimeData = QMimeData()
mimeData.setData(LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE,
QByteArray.number(axis_index))
pixmap = QPixmap(drag_label.size())
drag_label.render(pixmap)
# We will initiate a real dragging sequence, we don't need these anymore
self.drag_label = None
self.drag_start_pos = None
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
drag.setHotSpot(drag_delta)
drag.exec_(Qt.MoveAction)
# Tell whether the filter bar is an acceptable target for a particular
# dragging event (which could come from another app)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat(LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE):
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
# Inside the filter bar, inform Qt whether some particular position
# is a good final target or not
def dragMoveEvent(self, event):
if event.mimeData().hasFormat(LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE):
child = self.childAt(event.pos())
if isinstance(child, QLabel) and child.text() != "Filters":
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
else:
event.ignore()
# If the user dropped on a valid target, we need to handle the event
def dropEvent(self, event):
mime_data = event.mimeData()
if mime_data.hasFormat(LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE):
old_index_byte_array = mime_data.data(LARRAY_AXIS_INDEX_DRAG_AND_DROP_MIMETYPE)
old_index, success = old_index_byte_array.toInt()
child = self.childAt(event.pos())
new_index = self.layout().indexOf(child) // 2
data_adapter = self.array_widget.data_adapter
data, attributes = data_adapter.move_axis(data_adapter.data,
data_adapter.attributes,
old_index,
new_index)
self.array_widget.set_data(data, attributes)
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
class BackButtonBar(QWidget):
def __init__(self, array_widget):
super().__init__()
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
button = QPushButton('Back')
button.clicked.connect(self.on_clicked)
layout.addWidget(button)
self.array_widget = array_widget
self._back_data = []
self._back_data_adapters = []
layout.addStretch()
self.hide()
def add_back(self, data, data_adapter):
self._back_data.append(data)
# We need to keep the data_adapter around because some resource
# are created in the adapter (e.g. duckdb connection when viewing a
# .ddb file) and if the adapter is garbage collected, the resource
# is deleted (e.g. the duckdb connection dies - contrary to other libs,
# a duckdb table object does not keep the connection alive)
self._back_data_adapters.append(data_adapter)
if not self.isVisible():
self.show()
def clear(self):
for adapter in self._back_data_adapters[::-1]:
self._close_adapter(adapter)
self._back_data_adapters = []
self._back_data = []
self.hide()
@staticmethod
def _close_adapter(adapter):
clsname = type(adapter).__name__
logger.debug(f"closing data adapter ({clsname})")
adapter.close()
def on_clicked(self):
if not len(self._back_data):
logger.warning("Back button has no target to go to")
return
target_data = self._back_data.pop()
data_adapter = self._back_data_adapters.pop()
if not len(self._back_data):
self.hide()
array_widget: ArrayEditorWidget = self.array_widget
# We are not using array_widget.set_data(target_data) so that we can
# reuse the same data_adapter instead of recreating a new one
array_widget.data = target_data
array_widget.set_data_adapter(data_adapter, frac_digits=None)
class AbstractView(QTableView):
"""Abstract view class"""
def __init__(self, parent, model, hpos, vpos):
assert isinstance(parent, ArrayEditorWidget)
QTableView.__init__(self, parent)
# set model
self.setModel(model)
# set position
if hpos not in {LEFT, RIGHT}:
raise TypeError(f"Value of hpos must be {LEFT} or {RIGHT}")
self.hpos = hpos
if vpos not in {TOP, BOTTOM}:
raise TypeError(f"Value of vpos must be {TOP} or {BOTTOM}")
self.vpos = vpos
self.first_selection_corner = None
# handling a second selection corner is necessary to implement the
# "select entire row/column" functionality because in that case the
# second corner is not necessarily in the viewport, but it is a real
# cell (i.e. the coordinates are inclusive)
self.second_selection_corner = None
# set selection mode
self.setSelectionMode(QTableView.ContiguousSelection)
# prepare headers + cells size
self.horizontalHeader().setFrameStyle(QFrame.NoFrame)
self.verticalHeader().setFrameStyle(QFrame.NoFrame)
self.set_default_size()
# hide horizontal/vertical headers
if hpos == RIGHT:
self.verticalHeader().hide()
if vpos == BOTTOM:
self.horizontalHeader().hide()
# XXX: this might help if we want the widget to be focusable using "tab"
# self.setFocusPolicy(Qt.StrongFocus)
# These 4 lines are only useful for debugging
# hscrollbar = self.horizontalScrollBar()
# hscrollbar.valueChanged.connect(self.on_horizontal_scroll_changed)
# vscrollbar = self.verticalScrollBar()
# vscrollbar.valueChanged.connect(self.on_vertical_scroll_changed)
# Hide scrollbars
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# update geometry
if not (hpos == RIGHT and vpos == BOTTOM):
self.model().modelReset.connect(self.updateGeometry)
self.horizontalHeader().sectionResized.connect(self.updateGeometry)
self.verticalHeader().sectionResized.connect(self.updateGeometry)
# def on_vertical_scroll_changed(self, value):
# log_caller()
# print(f"hidden vscroll on {self.__class__.__name__} changed to {value}")
# def on_horizontal_scroll_changed(self, value):
# log_caller()
# print(f"hidden hscroll on {self.__class__.__name__} changed to {value}")
# def selectionChanged(self, selected: QtCore.QItemSelection, deselected: QtCore.QItemSelection) -> None:
# super().selectionChanged(selected, deselected)
# print(f"selectionChanged:\n"
# f" -> selected({display_selection(selected)}),\n"
# f" -> deselected({display_selection(deselected)})")
def reset_to_defaults(self):
"""
reset widget to initial state (when the ArrayEditorWidget is switching
from one object to another)
"""
self.set_default_size()
self.first_selection_corner = None
self.second_selection_corner = None
def set_default_size(self):
# logger.debug(f"{self.__class__.__name__}.set_default_size()")
# make the grid a bit more compact
horizontal_header = self.horizontalHeader()
horizontal_header.blockSignals(True)
horizontal_header.setDefaultSectionSize(DEFAULT_COLUMN_WIDTH)
if horizontal_header.sectionSize(0) != DEFAULT_COLUMN_WIDTH:
# Explicitly set all columns to the default width to override any
# custom sizes
for col in range(self.model().columnCount()):
self.setColumnWidth(col, DEFAULT_COLUMN_WIDTH)
horizontal_header.blockSignals(False)
self.verticalHeader().setDefaultSectionSize(DEFAULT_ROW_HEIGHT)
if self.vpos == TOP:
horizontal_header.setFixedHeight(10)
if self.hpos == LEFT:
self.verticalHeader().setFixedWidth(10)
# We need to have this here (in AbstractView) and not only on DataView, so that we
# catch them for vlabels too. For axes and hlabels, it is a bit of a weird
# behavior since they are not affected themselves but that is really a nitpick
# Also, overriding the general event() method for this does not work as it is
# handled behind us (by the ScrollArea I assume) and we do not even see the event
# unless we are at the buffer boundary.
def wheelEvent(self, event: QWheelEvent):
"""Catch wheel events and send them to the corresponding visible scrollbar"""
delta = event.angleDelta()
logger.debug(f"wheelEvent on {self.__class__.__name__} ({delta})")
editor_widget = self.parent().parent()
if delta.x() != 0:
editor_widget.hscrollbar.wheelEvent(event)
if delta.y() != 0:
editor_widget.vscrollbar.wheelEvent(event)
event.accept()
def keyPressEvent(self, event):
key = event.key()
if key in {Qt.Key_Home, Qt.Key_End, Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right,
Qt.Key_PageUp, Qt.Key_PageDown}:
event.accept()
self.navigate_key_event(event)
else:
QTableView.keyPressEvent(self, event)
def navigate_key_event(self, event):
logger.debug("")
logger.debug("navigate")
logger.debug("========")
model = self.model()
widget = self.parent().parent()
assert isinstance(widget, ArrayEditorWidget)
event_modifiers = event.modifiers()
event_key = event.key()
if event_modifiers & Qt.ShiftModifier:
# remove shift from modifiers so the Ctrl+Key combos are still detected
event_modifiers ^= Qt.ShiftModifier
shift = True
else:
shift = False
try:
# qt6
modifiers_value = event_modifiers.value
except AttributeError:
# qt5
modifiers_value = event_modifiers
keyseq = QKeySequence(modifiers_value | event_key)
page_step = self.verticalScrollBar().pageStep()
cursor_global_pos = self.get_cursor_global_pos()
if cursor_global_pos is None:
cursor_global_v_pos, cursor_global_h_pos = 0, 0
logger.debug("No previous cursor position: using 0, 0")
else:
cursor_global_v_pos, cursor_global_h_pos = cursor_global_pos
logger.debug(f"old global cursor {cursor_global_v_pos} {cursor_global_h_pos}")
# TODO: for some adapter shape2 is not reliable (it is a best guess), we should make sure we gracefully handle
# wrong info
total_v_size, total_h_size = model.adapter.shape2d()
key2delta = {
Qt.Key_Home: (0, -cursor_global_h_pos),
Qt.Key_End: (0, total_h_size - cursor_global_h_pos - 1),
Qt.Key_Up: (-1, 0),
Qt.Key_Down: (1, 0),
Qt.Key_Left: (0, -1),
Qt.Key_Right: (0, 1),
Qt.Key_PageUp: (-page_step, 0),
Qt.Key_PageDown: (page_step, 0),
}
# Ctrl+arrow does not mean anything by default, so dispatching does not help
# TODO: use another dict for this. dict[keyseq] does not work even if keyseq == key works.
# Using a different dict and checking the modifier explicitly should work.
# Or maybe getting the string representation of the keyseq is possible too.
# TODO: it might be simpler to set the cursor_global_pos values directly rather than using delta
if keyseq == "Ctrl+Home":
v_delta, h_delta = (-cursor_global_v_pos, -cursor_global_h_pos)
elif keyseq == "Ctrl+End":
v_delta, h_delta = (total_v_size - cursor_global_v_pos - 1, total_h_size - cursor_global_h_pos - 1)
elif keyseq == "Ctrl+Left":
v_delta, h_delta = (0, -cursor_global_h_pos)
elif keyseq == "Ctrl+Right":
v_delta, h_delta = (0, total_h_size - cursor_global_h_pos - 1)
elif keyseq == "Ctrl+Up":
v_delta, h_delta = (-cursor_global_v_pos, 0)
elif keyseq == "Ctrl+Down":
v_delta, h_delta = (total_v_size - cursor_global_v_pos - 1, 0)
else:
v_delta, h_delta = key2delta[event_key]
# TODO: internal scroll => change value of visible scrollbar (or avoid internal scroll)
cursor_new_global_v_pos = clip(cursor_global_v_pos + v_delta, 0, total_v_size - 1)
cursor_new_global_h_pos = clip(cursor_global_h_pos + h_delta, 0, total_h_size - 1)
logger.debug(f"new global cursor {cursor_new_global_v_pos} {cursor_new_global_h_pos}")
self.scroll_to_global_pos(cursor_new_global_v_pos, cursor_new_global_h_pos)
new_v_posinbuffer = cursor_new_global_v_pos - model.v_offset
new_h_posinbuffer = cursor_new_global_h_pos - model.h_offset
local_cursor_index = model.index(new_v_posinbuffer, new_h_posinbuffer)
if shift:
if self.first_selection_corner is None:
# This can happen when using navigation keys before
# selecting any cell using the mouse (but after getting focus
# on the widget which can be done at least by clicking inside
# the widget area but outside "valid" cells)
self.first_selection_corner = (cursor_global_v_pos, cursor_global_h_pos)
self.second_selection_corner = cursor_new_global_v_pos, cursor_new_global_h_pos
selection_v_pos1, selection_h_pos1 = self.first_selection_corner
selection_v_pos2, selection_h_pos2 = self.second_selection_corner
row_min = min(selection_v_pos1, selection_v_pos2)
row_max = max(selection_v_pos1, selection_v_pos2)
col_min = min(selection_h_pos1, selection_h_pos2)
col_max = max(selection_h_pos1, selection_h_pos2)
selection_model = self.selectionModel()
selection_model.setCurrentIndex(local_cursor_index, QItemSelectionModel.Current)
# we need to clip local coordinates in case the selection corners are outside the viewport
local_top = max(row_min - model.v_offset, 0)
local_left = max(col_min - model.h_offset, 0)
local_bottom = min(row_max - model.v_offset, model.nrows - 1)
local_right = min(col_max - model.h_offset, model.ncols - 1)
selection = QItemSelection(model.index(local_top, local_left),
model.index(local_bottom, local_right))
selection_model.select(selection, QItemSelectionModel.ClearAndSelect)
else:
self.first_selection_corner = cursor_new_global_v_pos, cursor_new_global_h_pos
self.second_selection_corner = cursor_new_global_v_pos, cursor_new_global_h_pos
self.setCurrentIndex(local_cursor_index)
logger.debug(f"after navigate_key_event: {self.first_selection_corner=} "
f"{self.second_selection_corner=}")
# after we drop support for Python < 3.10, we should use:
# def get_cursor_global_pos(self) -> tuple[int, int] | None:
def get_cursor_global_pos(self):
model = self.model()
current_index = self.currentIndex()
if not current_index.isValid():
return None
v_posinbuffer = current_index.row()
h_posinbuffer = current_index.column()
assert v_posinbuffer >= 0
assert h_posinbuffer >= 0
cursor_global_v_pos = model.v_offset + v_posinbuffer
cursor_global_h_pos = model.h_offset + h_posinbuffer
return cursor_global_v_pos, cursor_global_h_pos
def scroll_to_global_pos(self, global_v_pos, global_h_pos):
"""
Change visible scrollbars value so that vpos/hpos is visible
without changing the cursor position
"""
model = self.model()
widget = self.parent().parent()
assert isinstance(widget, ArrayEditorWidget)
visible_cols = widget.visible_cols()
visible_rows = widget.visible_rows()
hidden_v_offset = self.verticalScrollBar().value()
hidden_h_offset = self.horizontalScrollBar().value()
total_v_offset = model.v_offset + hidden_v_offset
total_h_offset = model.h_offset + hidden_h_offset
if global_v_pos < total_v_offset:
new_total_v_offset = global_v_pos
# TODO: document where those +2 come from
elif global_v_pos > total_v_offset + visible_rows - 2:
new_total_v_offset = global_v_pos - visible_rows + 2
else:
# do not change offset
new_total_v_offset = total_v_offset
if global_h_pos < total_h_offset:
new_total_h_offset = global_h_pos
elif global_h_pos > total_h_offset + visible_cols - 2:
new_total_h_offset = global_h_pos - visible_cols + 2
else:
# do not change offset
new_total_h_offset = total_h_offset
# change visible scrollbars value
widget.vscrollbar.setValue(new_total_v_offset)
widget.hscrollbar.setValue(new_total_h_offset)
def autofit_columns(self):
"""Resize cells to contents"""
# print(f"{self.__class__.__name__}.autofit_columns()")
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
# for column in range(self.model_axes.columnCount()):
# self.resize_axes_column_to_contents(column)
self.resizeColumnsToContents()
# If the resized columns would make the whole view smaller or larger,
# the view size itself (not its columns) is changed. This allows,
# for example, other views (e.g. hlabels) to be moved accordingly.
self.updateGeometry()
QApplication.restoreOverrideCursor()
def updateGeometry(self):
# vpos = "TOP" if self.vpos == TOP else "BOTTOM"
# hpos = "LEFT" if self.hpos == LEFT else "RIGHT"
# print(f"{self.__class__.__name__}.updateGeometry() ({vpos=}, {hpos=})")
# Set total height (for the whole view, not a particular row)
if self.vpos == TOP:
total_height = self.horizontalHeader().height() + \
sum(self.rowHeight(r) for r in range(self.model().rowCount()))
# print(f" TOP => {total_height=}")
self.setFixedHeight(total_height)
# Set total width (for the whole view, not a particular column)
if self.hpos == LEFT:
total_width = self.verticalHeader().width() + \
sum(self.columnWidth(c) for c in range(self.model().columnCount()))
# print(f" LEFT => {total_width=}")
self.setFixedWidth(total_width)
# update geometry
super().updateGeometry()
class AxesView(AbstractView):
""""Axes view class"""
allSelected = Signal()
def __init__(self, parent, model):
# check model
if not isinstance(model, AxesArrayModel):
raise TypeError(f"Expected model of type {AxesArrayModel.__name__}. "
f"Received {type(model).__name__} instead")
AbstractView.__init__(self, parent, model, LEFT, TOP)
# FIXME: only have this if the adapter supports any extra action on axes
# self.clicked.connect(self.on_clicked)
def on_clicked(self, index: QModelIndex):
row_idx = index.row()
column_idx = index.column()
# FIXME: column_idx works fine for the unfiltered/initial array but on an already filtered
# array it breaks because column_idx is the idx of the *filtered* array which can
# contain less axes while change_filter (via create_filter_menu) want the index
# of the *unfiltered* array
try:
adapter = self.model().adapter
filtrable = adapter.can_filter_axis(column_idx)
sortable = adapter.can_sort_axis_labels(column_idx)
if sortable:
sort_direction = adapter.axis_sort_direction(column_idx)
else:
sort_direction = 'unsorted'
filter_labels = adapter.get_filter_options(column_idx)
except IndexError:
filtrable = False
filter_labels = []
sortable = False
sort_direction = 'unsorted'
if filtrable or sortable:
menu = self.create_filter_menu(column_idx,
filtrable,
filter_labels,
sortable,
sort_direction)
x = (self.columnViewportPosition(column_idx) +
self.verticalHeader().width())
y = (self.rowViewportPosition(row_idx) + self.rowHeight(row_idx) +
self.horizontalHeader().height())
menu.exec_(self.mapToGlobal(QPoint(x, y)))
def create_filter_menu(self,
axis_idx,
filtrable,
filter_labels,
sortable=False,
sort_direction='unsorted'):
def filter_changed(checked_items):
# print("filter_changed", axis_idx, checked_items)
array_widget = self.parent().parent()
array_widget.filter_bar.change_filter(axis_idx, checked_items)
def sort_changed(ascending):
array_widget = self.parent().parent()
array_widget.sort_axis_labels(axis_idx, ascending)
menu = CombinedSortFilterMenu(self,
filtrable=filtrable,
sortable=sortable,
sort_direction=sort_direction)
if filtrable:
menu.addItems([str(label) for label in filter_labels])
menu.checked_items_changed.connect(filter_changed)
if sortable:
menu.sort_signal.connect(sort_changed)
return menu
# override viewOptions so that cell decorations (ie axes names arrows) are
# drawn to the right of cells instead of to the left
def viewOptions(self):
option = QTableView.viewOptions(self)
option.decorationPosition = QStyleOptionViewItem.Right
return option
def selectAll(self):
self.allSelected.emit()
class LabelsView(AbstractView):
""""Labels view class"""
def __init__(self, parent, model, hpos, vpos):
# check model
if not isinstance(model, LabelsArrayModel):
raise TypeError(f"Expected model of type {LabelsArrayModel.__name__}. "
f"Received {type(model).__name__} instead")
AbstractView.__init__(self, parent, model, hpos, vpos)
# FIXME: only have this if the adapter supports any extra action on axes
if self.vpos == TOP:
self.clicked.connect(self.on_clicked)
def on_clicked(self, index: QModelIndex):
if not index.isValid():
return
row_idx = index.row()
local_col_idx = index.column()
model: LabelsArrayModel = self.model()
global_col_idx = model.h_offset + local_col_idx
assert self.vpos == TOP
# FIXME: global_col_idx works fine for the unfiltered/initial array but on
# an already filtered array it breaks because global_col_idx is the
# idx of the *filtered* array which can contain less axes while
# change_filter (via create_filter_menu) want the index of the
# *unfiltered* array
adapter = model.adapter
filtrable = adapter.can_filter_hlabel(1, global_col_idx)
sortable = adapter.can_sort_hlabel(row_idx, global_col_idx)
if sortable:
sort_direction = adapter.hlabel_sort_direction(row_idx, global_col_idx)
def sort_changed(ascending):
# TODO: the chain for this is kinda convoluted:
# local signal handler
# -> ArrayWidget method
# -> adapter method+model reset
array_widget = self.parent().parent()
array_widget.sort_hlabel(row_idx, global_col_idx, ascending)
else:
sort_direction = 'unsorted'
sort_changed = None
if filtrable:
filter_labels = adapter.get_filter_options(global_col_idx)
# TODO: mandate/assert that get_filter_options returns
# a sequence of strings instead of doing the conversion here.
# we use indices/positions to filter anyway
if isinstance(filter_labels, np.ndarray):
if filter_labels.dtype.kind == 'M':
# for datetime labels str(label) returns the integer
filter_labels = filter_labels.astype(str)
filter_labels = filter_labels.tolist()
if len(filter_labels) == MAX_FILTER_OPTIONS:
filter_labels[-1] = MORE_OPTIONS_NOT_SHOWN
filter_indices = adapter.get_current_filter_indices(global_col_idx)
def filter_changed(checked_items):
# TODO: the chain for this is kinda convoluted:
# local signal handler (this function)
# -> ArrayWidget method
# -> adapter method+model reset
array_widget = self.parent().parent()
assert isinstance(array_widget, ArrayEditorWidget)
array_widget.filter_bar.change_filter(global_col_idx, checked_items)
else:
filter_labels = []
filter_changed = None
filter_indices = None
if filtrable or sortable:
# because of the local vs global idx, we cannot cache/reuse the
# filter menu widget (we would need to remove the items and readd
# the correct ones) so it is easier to just recreate the whole
# widget. We need to take the already ticked indices into account
# though.
menu = self.create_filter_menu(global_col_idx,
filter_labels,
filter_indices,
filter_changed,
sort_changed,
sort_direction)
x = (self.columnViewportPosition(local_col_idx) +
self.verticalHeader().width())
y = (self.rowViewportPosition(row_idx) + self.rowHeight(row_idx) +
self.horizontalHeader().height())
menu.exec_(self.mapToGlobal(QPoint(x, y)))
def create_filter_menu(self,
filter_idx,
filter_labels,
filter_indices,
filter_changed,
sort_changed,
sort_direction):
filtrable = filter_changed is not None
sortable = sort_changed is not None
menu = CombinedSortFilterMenu(self,
filtrable=filtrable,
sortable=sortable,
sort_direction=sort_direction)
if filtrable:
menu.addItems([str(label) for label in filter_labels],
filter_indices)
# disable last item if there are too many options
if len(filter_labels) == MAX_FILTER_OPTIONS:
# this is correct (MAX - 1 to get the last item, + 1 because
# of the "Select all" item at the beginning)
last_item = menu._model[MAX_FILTER_OPTIONS - 1 + 1]
last_item.setFlags(QtCore.Qt.NoItemFlags)
menu.checked_items_changed.connect(filter_changed)
if sortable:
menu.sort_signal.connect(sort_changed)
return menu
# override viewOptions so that cell decorations (ie axes names arrows) are
# drawn to the right of cells instead of to the left
def viewOptions(self):
option = QTableView.viewOptions(self)
option.decorationPosition = QStyleOptionViewItem.Right
return option
class ArrayDelegate(QItemDelegate):
"""Array Editor Item Delegate"""
def __init__(self, parent=None, font=None, minvalue=None, maxvalue=None):
# parent is the DataView instance
QItemDelegate.__init__(self, parent)
if font is None:
font = get_default_font()
self.font = font
self.minvalue = minvalue
self.maxvalue = maxvalue
# keep track of whether there is already at least one editor already open (to properly
# open a new editor when pressing Enter in DataView only if one is not already open)
# We must keep a count instead of keeping a reference to the "current" one, because when switching
# from one cell to the next, the new editor is created before the old one is destroyed, which means
# it would be set to None when the old one is destroyed, instead of to the new current editor.
self.editor_count = 0
def createEditor(self, parent, option, index):
"""Create editor widget"""
model = index.model()
# TODO: dtype should be asked per cell. Only the adapter knows whether the dtype is per cell
# (e.g. list), per column (e.g. Dataframe) or homogenous for the whole table (e.g. la.Array)
# dtype = model.adapter.get_dtype(hpos, vpos)
dtype = model.adapter.dtype
value = model.get_value(index)
# this will return a string !
# value = model.data(index, Qt.DisplayRole)
if dtype.name == "bool":
# directly toggle value and do not actually create an editor
model.setData(index, not value)
return None
elif value is not np.ma.masked:
# Not using a QSpinBox for integer inputs because I could not find
# a way to prevent the spinbox/editor from closing if the value is
# invalid. Using the builtin minimum/maximum of the spinbox works
# but that provides no message so it is less clear.
editor = QLineEdit(parent)
if is_number_dtype(dtype):
# FIXME: get minvalue & maxvalue from somewhere... the adapter?
# or the model? another specific adapter for minvalue,
# one for maxvalue, one for bg_value, etc.?
minvalue, maxvalue = self.minvalue, self.maxvalue
validator = QDoubleValidator(editor) if is_float_dtype(dtype) else QIntValidator(editor)
if minvalue is not None:
validator.setBottom(minvalue)
if maxvalue is not None:
validator.setTop(maxvalue)
editor.setValidator(validator)
if minvalue is not None and maxvalue is not None:
msg = f"value must be between {minvalue} and {maxvalue}"
elif minvalue is not None:
msg = f"value must be >= {minvalue}"
elif maxvalue is not None:
msg = f"value must be <= {maxvalue}"
else:
msg = None
if msg is not None:
def on_editor_text_edited():
if not editor.hasAcceptableInput():
QToolTip.showText(editor.mapToGlobal(QPoint()), msg)
else:
QToolTip.hideText()
editor.textEdited.connect(on_editor_text_edited)
editor.setFont(self.font)
editor.setAlignment(Qt.AlignRight)
editor.destroyed.connect(self.on_editor_destroyed)
self.editor_count += 1
return editor
def on_editor_destroyed(self):
self.editor_count -= 1
assert self.editor_count >= 0
def setEditorData(self, editor, index):
"""Set editor widget's data"""
text = index.model().data(index, Qt.DisplayRole)
editor.setText(text)