forked from biolab/orange3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathowcsvimport.py
More file actions
1849 lines (1595 loc) · 62.5 KB
/
owcsvimport.py
File metadata and controls
1849 lines (1595 loc) · 62.5 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 -*-
"""
CSV File Import Widget
----------------------
"""
import sys
import types
import os
import csv
import enum
import io
import traceback
import warnings
import logging
import weakref
import json
import gzip
import lzma
import bz2
import zipfile
from xml.sax.saxutils import escape
from functools import singledispatch
from contextlib import ExitStack
import typing
from typing import (
List, Tuple, Dict, Optional, Any, Callable, Iterable,
Union, AnyStr, BinaryIO, Set, Type, Mapping, Sequence, NamedTuple
)
from AnyQt.QtCore import (
Qt, QFileInfo, QTimer, QSettings, QObject, QSize, QMimeDatabase, QMimeType
)
from AnyQt.QtGui import (
QStandardItem, QStandardItemModel, QPalette, QColor, QIcon
)
from AnyQt.QtWidgets import (
QLabel, QComboBox, QPushButton, QDialog, QDialogButtonBox, QGridLayout,
QVBoxLayout, QSizePolicy, QStyle, QFileIconProvider, QFileDialog,
QApplication, QMessageBox, QTextBrowser, QMenu
)
from AnyQt.QtCore import pyqtSlot as Slot, pyqtSignal as Signal
import numpy as np
import pandas.errors
import pandas as pd
from pandas.api import types as pdtypes
from orangewidget.utils import enum_as_int
import Orange.data
from Orange.misc.collections import natural_sorted
from Orange.widgets import widget, gui, settings
from Orange.widgets.utils.localization import pl
from Orange.widgets.utils.concurrent import PyOwned
from Orange.widgets.utils import (
textimport, concurrent as qconcurrent, unique_everseen, enum_get, qname
)
from Orange.widgets.utils.combobox import ItemStyledComboBox
from Orange.widgets.utils.pathutils import (
PathItem, VarPath, AbsPath, samepath, prettyfypath, isprefixed,
)
from Orange.widgets.utils.overlay import OverlayWidget
from Orange.widgets.utils.settings import (
QSettings_readArray, QSettings_writeArray
)
if typing.TYPE_CHECKING:
# pylint: disable=invalid-name
T = typing.TypeVar("T")
K = typing.TypeVar("K")
E = typing.TypeVar("E", bound=enum.Enum)
__all__ = ["OWCSVFileImport"]
_log = logging.getLogger(__name__)
ColumnType = textimport.ColumnType
RowSpec = textimport.RowSpec
def dialect_eq(lhs, rhs):
# type: (csv.Dialect, csv.Dialect) -> bool
"""Compare 2 `csv.Dialect` instances for equality."""
return (lhs.delimiter == rhs.delimiter and
lhs.quotechar == rhs.quotechar and
lhs.doublequote == rhs.doublequote and
lhs.escapechar == rhs.escapechar and
lhs.quoting == rhs.quoting and
lhs.skipinitialspace == rhs.skipinitialspace)
class Options:
"""
Stored options for loading CSV-like file.
Arguments
---------
encoding : str
A encoding to use for reading.
dialect : csv.Dialect
A csv.Dialect instance.
columntypes: Iterable[Tuple[range, ColumnType]]
A list of column type ranges specifying the types for columns.
Need not list all columns. Columns not listed are assumed to have auto
type inference.
rowspec : Iterable[Tuple[range, RowSpec]]
A list of row spec ranges.
decimal_separator : str
Decimal separator - a single character string; default: `"."`
group_separator : str
Thousands group separator - empty or a single character string;
default: empty string
"""
RowSpec = RowSpec
ColumnType = ColumnType
def __init__(self, encoding='utf-8', dialect=csv.excel(),
columntypes: Iterable[Tuple[range, 'ColumnType']] = (),
rowspec=((range(0, 1), RowSpec.Header),),
decimal_separator=".", group_separator="") -> None:
self.encoding = encoding
self.dialect = dialect
self.columntypes = list(columntypes) # type: List[Tuple[range, ColumnType]]
self.rowspec = list(rowspec) # type: List[Tuple[range, RowSpec]]
self.decimal_separator = decimal_separator
self.group_separator = group_separator
def __eq__(self, other):
"""
Compare this instance to `other` for equality.
"""
if isinstance(other, Options):
return (dialect_eq(self.dialect, other.dialect) and
self.encoding == other.encoding and
self.columntypes == other.columntypes and
self.rowspec == other.rowspec and
self.group_separator == other.group_separator and
self.decimal_separator == other.decimal_separator)
else:
return NotImplemented
def __repr__(self):
class_, args = self.__reduce__()
return "{}{!r}".format(class_.__name__, args)
__str__ = __repr__
def __reduce__(self):
return type(self), (self.encoding, self.dialect,
self.columntypes, self.rowspec)
def as_dict(self):
# type: () -> Dict[str, Any]
"""
Return return Option parameters as plain types suitable for
serialization (e.g JSON serializable).
"""
return {
"encoding": self.encoding,
"delimiter": self.dialect.delimiter,
"quotechar": self.dialect.quotechar,
"doublequote": self.dialect.doublequote,
"skipinitialspace": self.dialect.skipinitialspace,
"quoting": self.dialect.quoting,
"columntypes": Options.spec_as_encodable(self.columntypes),
"rowspec": Options.spec_as_encodable(self.rowspec),
"decimal_separator": self.decimal_separator,
"group_separator": self.group_separator,
}
@staticmethod
def from_dict(mapping):
# type: (Dict[str, Any]) -> Options
"""
Reconstruct a `Options` from a plain dictionary (see :func:`as_dict`).
"""
encoding = mapping["encoding"]
delimiter = mapping["delimiter"]
quotechar = mapping["quotechar"]
doublequote = mapping["doublequote"]
quoting = mapping["quoting"]
skipinitialspace = mapping["skipinitialspace"]
dialect = textimport.Dialect(
delimiter, quotechar, None, doublequote, skipinitialspace,
quoting=quoting)
colspec = mapping["columntypes"]
rowspec = mapping["rowspec"]
colspec = Options.spec_from_encodable(colspec, ColumnType)
rowspec = Options.spec_from_encodable(rowspec, RowSpec)
decimal = mapping.get("decimal_separator", ".")
group = mapping.get("group_separator", "")
return Options(encoding, dialect, colspec, rowspec,
decimal_separator=decimal,
group_separator=group)
@staticmethod
def spec_as_encodable(spec):
# type: (Iterable[Tuple[range, enum.Enum]]) -> List[Dict[str, Any]]
return [{"start": r.start, "stop": r.stop, "value": value.name}
for r, value in spec]
@staticmethod
def spec_from_encodable(spec, enumtype):
# type: (Iterable[Dict[str, Any]], Type[E]) -> List[Tuple[range, E]]
r = []
for v in spec:
try:
start, stop, name = v["start"], v["stop"], v["value"]
except (KeyError, ValueError):
pass
else:
r.append((range(start, stop), enum_get(enumtype, name, None)))
return r
class CSVImportDialog(QDialog):
"""
A dialog for selecting CSV file import options.
"""
def __init__(self, parent=None, flags=Qt.Dialog, **kwargs):
super().__init__(parent, flags, **kwargs)
self.setLayout(QVBoxLayout())
self._options = None
self._path = None
# Finalizer for opened file handle (in _update_preview)
self.__finalizer = None # type: Optional[Callable[[], None]]
self._optionswidget = textimport.CSVImportWidget()
self._optionswidget.previewReadErrorOccurred.connect(
self.__on_preview_error
)
self._optionswidget.previewModelReset.connect(
self.__on_preview_reset
)
self._buttons = buttons = QDialogButtonBox(
orientation=Qt.Horizontal,
standardButtons=(QDialogButtonBox.Ok | QDialogButtonBox.Cancel |
QDialogButtonBox.Reset |
QDialogButtonBox.RestoreDefaults),
objectName="dialog-button-box",
)
# TODO: Help button
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
b = buttons.button(QDialogButtonBox.Reset)
b.clicked.connect(self.reset)
b = buttons.button(QDialogButtonBox.RestoreDefaults)
b.clicked.connect(self.restoreDefaults)
self.layout().addWidget(self._optionswidget)
self.layout().addWidget(buttons)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self._overlay = OverlayWidget(self)
self._overlay.setWidget(self._optionswidget.dataview)
self._overlay.setLayout(QVBoxLayout())
self._overlay.layout().addWidget(QLabel(wordWrap=True))
self._overlay.hide()
def setOptions(self, options):
# type: (Options) -> None
self._options = options
self._optionswidget.setEncoding(options.encoding)
self._optionswidget.setDialect(options.dialect)
self._optionswidget.setNumbersFormat(
options.group_separator, options.decimal_separator)
self._optionswidget.setColumnTypeRanges(options.columntypes)
self._optionswidget.setRowStates(
{i: v for r, v in options.rowspec for i in r}
)
def options(self):
# type: () -> Options
rowspec_ = self._optionswidget.rowStates()
rowspec = [(range(i, i + 1), v) for i, v in rowspec_.items()]
numformat = self._optionswidget.numbersFormat()
return Options(
encoding=self._optionswidget.encoding(),
dialect=self._optionswidget.dialect(),
columntypes=self._optionswidget.columnTypeRanges(),
rowspec=rowspec,
decimal_separator=numformat["decimal"],
group_separator=numformat["group"],
)
def setPath(self, path):
"""
Set the preview path.
"""
if self._path != path:
self._path = path
self.__update_preview()
def path(self):
"""Return the preview path"""
return self._path
def reset(self):
"""
Reset the options to the state previously set with `setOptions`
effectively undoing any user modifications since then.
"""
self.setOptions(self._options)
def restoreDefaults(self):
"""
Restore the options to default state.
"""
# preserve `_options` if set by clients (for `reset`).
opts = self._options
self.setOptions(Options("utf-8", csv.excel()))
self._options = opts
def __update_preview(self):
if not self._path:
return
try:
f = _open(self._path, "rb")
except OSError as err:
traceback.print_exc(file=sys.stderr)
fmt = "".join(traceback.format_exception_only(type(err), err))
self.__set_error(fmt)
else:
self.__clear_error()
self._optionswidget.setSampleContents(f)
closeexisting = self.__finalizer
if closeexisting is not None:
self.destroyed.disconnect(closeexisting)
closeexisting()
self.__finalizer = weakref.finalize(self, f.close)
self.destroyed.connect(self.__finalizer)
def __set_error(self, text, format=Qt.PlainText):
self._optionswidget.setEnabled(False)
label = self._overlay.findChild(QLabel) # type: QLabel
label.setText(text)
label.setTextFormat(format)
self._overlay.show()
self._overlay.raise_()
dialog_button_box_set_enabled(self._buttons, False)
def __clear_error(self):
if self._overlay.isVisibleTo(self):
self._overlay.hide()
self._optionswidget.setEnabled(True)
# Enable/disable the accept buttons on the most egregious errors.
def __on_preview_error(self):
b = self._buttons.button(QDialogButtonBox.Ok)
b.setEnabled(False)
def __on_preview_reset(self):
b = self._buttons.button(QDialogButtonBox.Ok)
b.setEnabled(True)
def dialog_button_box_set_enabled(buttonbox, enabled):
# type: (QDialogButtonBox, bool) -> None
"""
Disable/enable buttons in a QDialogButtonBox based on their role.
All buttons except the ones with RejectRole or HelpRole are disabled.
"""
stashname = "__p_dialog_button_box_set_enabled"
for b in buttonbox.buttons():
role = buttonbox.buttonRole(b)
if not enabled:
if b.property(stashname) is None:
b.setProperty(stashname, b.isEnabledTo(buttonbox))
b.setEnabled(
role == QDialogButtonBox.RejectRole or
role == QDialogButtonBox.HelpRole
)
else:
stashed_state = b.property(stashname)
if isinstance(stashed_state, bool):
state = stashed_state
b.setProperty(stashname, None)
else:
state = True
b.setEnabled(state)
def icon_for_path(path: str) -> QIcon:
iconprovider = QFileIconProvider()
finfo = QFileInfo(path)
if finfo.exists():
return iconprovider.icon(finfo)
else:
return iconprovider.icon(QFileIconProvider.File)
class VarPathItem(QStandardItem):
PathRole = Qt.UserRole + 4502
VarPathRole = PathRole + 1
def path(self) -> str:
"""Return the resolved path or '' if unresolved or missing"""
path = self.data(VarPathItem.PathRole)
return path if isinstance(path, str) else ""
def setPath(self, path: str) -> None:
"""Set absolute path."""
self.setData(PathItem.AbsPath(path), VarPathItem.VarPathRole)
def varPath(self) -> Optional[PathItem]:
vpath = self.data(VarPathItem.VarPathRole)
return vpath if isinstance(vpath, PathItem) else None
def setVarPath(self, vpath: PathItem) -> None:
"""Set variable path item."""
self.setData(vpath, VarPathItem.VarPathRole)
def resolve(self, vpath: PathItem) -> Optional[str]:
"""
Resolve `vpath` item. This implementation dispatches to parent model's
(:func:`VarPathItemModel.resolve`)
"""
model = self.model()
if isinstance(model, VarPathItemModel):
return model.resolve(vpath)
else:
return vpath.resolve({})
def data(self, role=Qt.UserRole + 1) -> Any:
if role == Qt.DisplayRole:
value = super().data(role)
if value is not None:
return value
vpath = self.varPath()
if isinstance(vpath, PathItem.AbsPath):
return os.path.basename(vpath.path)
elif isinstance(vpath, PathItem.VarPath):
return os.path.basename(vpath.relpath)
else:
return None
elif role == Qt.DecorationRole:
return icon_for_path(self.path())
elif role == VarPathItem.PathRole:
vpath = self.data(VarPathItem.VarPathRole)
if isinstance(vpath, PathItem.AbsPath):
return vpath.path
elif isinstance(vpath, VarPath):
path = self.resolve(vpath)
if path is not None:
return path
return super().data(role)
elif role == Qt.ToolTipRole:
vpath = self.data(VarPathItem.VarPathRole)
if isinstance(vpath, VarPath.AbsPath):
return vpath.path
elif isinstance(vpath, VarPath):
text = f"${{{vpath.name}}}/{vpath.relpath}"
p = self.resolve(vpath)
if p is None or not os.path.exists(p):
text += " (missing)"
return text
elif role == Qt.ForegroundRole:
vpath = self.data(VarPathItem.VarPathRole)
if isinstance(vpath, PathItem):
p = self.resolve(vpath)
if p is None or not os.path.exists(p):
return QColor(Qt.red)
return super().data(role)
class ImportItem(VarPathItem):
"""
An item representing a file path and associated load options
"""
OptionsRole = Qt.UserRole + 14
IsSessionItemRole = Qt.UserRole + 15
def options(self) -> Optional[Options]:
options = self.data(ImportItem.OptionsRole)
return options if isinstance(options, Options) else None
def setOptions(self, options: Options) -> None:
self.setData(options, ImportItem.OptionsRole)
def setIsSessionItem(self, issession: bool) -> None:
self.setData(issession, ImportItem.IsSessionItemRole)
def isSessionItem(self) -> bool:
return bool(self.data(ImportItem.IsSessionItemRole))
@classmethod
def fromPath(cls, path: Union[str, PathItem]) -> 'ImportItem':
"""
Create a `ImportItem` from a local file system path.
"""
if isinstance(path, str):
path = PathItem.AbsPath(path)
if isinstance(path, PathItem.VarPath):
basename = os.path.basename(path.relpath)
text = f"${{{path.name}}}/{path.relpath}"
elif isinstance(path, PathItem.AbsPath):
basename = os.path.basename(path.path)
text = path.path
else:
raise TypeError
item = cls()
item.setText(basename)
item.setToolTip(text)
item.setData(path, ImportItem.VarPathRole)
return item
class VarPathItemModel(QStandardItemModel):
def __init__(self, *args, replacementEnv=types.MappingProxyType({}),
**kwargs):
self.__replacements = types.MappingProxyType(dict(replacementEnv))
super().__init__(*args, **kwargs)
def setReplacementEnv(self, env: Mapping[str, str]) -> None:
self.__replacements = types.MappingProxyType(dict(env))
self.dataChanged.emit(
self.index(0, 0),
self.index(self.rowCount() - 1, self.columnCount() - 1)
)
def replacementEnv(self) -> Mapping[str, str]:
return self.__replacements
def resolve(self, vpath: PathItem) -> Optional[str]:
return vpath.resolve(self.replacementEnv())
def move_item_to_index(model: QStandardItemModel, item: QStandardItem, index: int):
if item.row() == index:
return
assert item.model() is model
[item_] = model.takeRow(item.row())
assert item_ is item
model.insertRow(index, [item])
class FileFormat(NamedTuple):
mime_type: str
name: str
globs: Sequence[str]
FileFormats = [
FileFormat("text/csv", "Text - comma separated", ("*.csv", "*")),
FileFormat("text/tab-separated-values", "Text - tab separated", ("*.tsv", "*")),
FileFormat("text/plain", "Text - all files", ("*.txt", "*")),
]
class FileDialog(QFileDialog):
__formats: Sequence[FileFormat] = ()
@staticmethod
def filterStr(f: FileFormat) -> str:
return f"{f.name} ({', '.join(f.globs)})"
def setFileFormats(self, formats: Sequence[FileFormat]):
filters = [FileDialog.filterStr(f) for f in formats]
self.__formats = tuple(formats)
self.setNameFilters(filters)
def fileFormats(self) -> Sequence[FileFormat]:
return self.__formats
def selectedFileFormat(self) -> FileFormat:
filter_ = self.selectedNameFilter()
index = index_where(
self.__formats, lambda f: FileDialog.filterStr(f) == filter_
)
return self.__formats[index]
def default_options_for_mime_type(
path: str, mime_type: str
) -> Options:
defaults = {
"text/csv": (csv.excel(), True),
"text/tab-separated-values": (csv.excel_tab(), True)
}
dialect, header, encoding = csv.excel(), True, "utf-8"
delimiters = None
try_encodings = ["utf-8", "utf-16", "iso8859-1"]
if mime_type in defaults:
dialect, header = defaults[mime_type]
delimiters = [dialect.delimiter]
for encoding_ in try_encodings:
try:
dialect, header = sniff_csv_with_path(
path, encoding=encoding_, delimiters=delimiters)
encoding = encoding_
except (OSError, UnicodeError, csv.Error):
pass
else:
break
if header:
rowspec = [(range(0, 1), RowSpec.Header)]
else:
rowspec = []
return Options(dialect=dialect, encoding=encoding, rowspec=rowspec)
class OWCSVFileImport(widget.OWWidget):
name = "CSV File Import"
description = "Import a data table from a CSV formatted file."
icon = "icons/CSVFile.svg"
priority = 11
category = "Data"
keywords = "csv file import, file, load, read, open, csv"
class Outputs:
data = widget.Output(
name="Data",
type=Orange.data.Table,
doc="Loaded data set.")
data_frame = widget.Output(
name="Data Frame",
type=pd.DataFrame,
doc="",
auto_summary=False
)
class Error(widget.OWWidget.Error):
error = widget.Msg(
"Unexpected error"
)
encoding_error = widget.Msg(
"Encoding error\n"
"The file might be encoded in an unsupported encoding or it "
"might be binary"
)
#: Paths and options of files accessed in a 'session'
_session_items = settings.Setting(
[], schema_only=True) # type: List[Tuple[str, dict]]
_session_items_v2 = settings.Setting(
[], schema_only=True) # type: List[Tuple[Dict[str, str], dict]]
#: Saved dialog state (last directory and selected filter)
dialog_state = settings.Setting({
"directory": "",
"filter": ""
}) # type: Dict[str, str]
# we added column type guessing to this widget, which breaks compatibility
# with older saved workflows, where types not guessed differently, when
# compatibility_mode=True widget have older guessing behaviour
settings_version = 3
compatibility_mode = settings.Setting(False, schema_only=True)
MaxHistorySize = 50
want_main_area = False
buttons_area_orientation = None
resizing_enabled = False
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.settingsAboutToBePacked.connect(self._saveState)
self.__committimer = QTimer(self, singleShot=True)
self.__committimer.timeout.connect(self.commit)
self.__executor = qconcurrent.ThreadExecutor()
self.__watcher = None # type: Optional[qconcurrent.FutureWatcher]
self.controlArea.layout().setSpacing(-1) # reset spacing
grid = QGridLayout()
grid.addWidget(QLabel("File:", self), 0, 0, 1, 1)
self.import_items_model = VarPathItemModel(self)
self.import_items_model.setReplacementEnv(self._replacements())
self.recent_combo = ItemStyledComboBox(
self, objectName="recent-combo", toolTip="Recent files.",
sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
minimumContentsLength=16, placeholderText="Recent files…"
)
self.recent_combo.setModel(self.import_items_model)
self.recent_combo.activated.connect(self.activate_recent)
self.recent_combo.setSizePolicy(
QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
self.browse_button = QPushButton(
"…", icon=self.style().standardIcon(QStyle.SP_DirOpenIcon),
toolTip="Browse filesystem", autoDefault=False,
)
# A button drop down menu with selection of explicit workflow dir
# relative import. This is only enabled when 'basedir' workflow env
# is set. XXX: Always use menu, disable Import relative... action?
self.browse_menu = menu = QMenu(self.browse_button)
ac = menu.addAction("Import any file…")
ac.triggered.connect(self.browse)
ac = menu.addAction("Import relative to workflow file…")
ac.setToolTip("Import a file within the workflow file directory")
ac.triggered.connect(lambda: self.browse_relative("basedir"))
if "basedir" in self._replacements():
self.browse_button.setMenu(menu)
self.browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.browse_button.clicked.connect(self.browse)
grid.addWidget(self.recent_combo, 0, 1, 1, 1)
grid.addWidget(self.browse_button, 0, 2, 1, 1)
self.controlArea.layout().addLayout(grid)
###########
# Info text
###########
box = gui.widgetBox(self.controlArea, "Info")
self.summary_text = QTextBrowser(
verticalScrollBarPolicy=Qt.ScrollBarAsNeeded,
readOnly=True,
)
self.summary_text.viewport().setBackgroundRole(QPalette.NoRole)
self.summary_text.setFrameStyle(QTextBrowser.NoFrame)
self.summary_text.setMinimumHeight(self.fontMetrics().ascent() * 2 + 4)
self.summary_text.viewport().setAutoFillBackground(False)
box.layout().addWidget(self.summary_text)
button_box = QDialogButtonBox(
orientation=Qt.Horizontal,
standardButtons=QDialogButtonBox.Cancel | QDialogButtonBox.Retry
)
self.load_button = b = button_box.button(QDialogButtonBox.Retry)
b.setText("Load")
b.clicked.connect(self.__committimer.start)
b.setEnabled(False)
b.setDefault(True)
self.cancel_button = b = button_box.button(QDialogButtonBox.Cancel)
b.clicked.connect(self.cancel)
b.setEnabled(False)
b.setAutoDefault(False)
self.import_options_button = QPushButton(
"Import Options…", enabled=False, autoDefault=False,
clicked=self._activate_import_dialog
)
def update_buttons(cbindex):
self.import_options_button.setEnabled(cbindex != -1)
self.load_button.setEnabled(cbindex != -1)
self.recent_combo.currentIndexChanged.connect(update_buttons)
button_box.addButton(
self.import_options_button, QDialogButtonBox.ActionRole
)
button_box.setStyleSheet(
"button-layout: {:d};".format(enum_as_int(QDialogButtonBox.MacLayout))
)
self.controlArea.layout().addWidget(button_box)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
self._restoreState()
item = self.current_item()
if item is not None:
self._invalidate()
def workflowEnvChanged(self, key, value, oldvalue):
super().workflowEnvChanged(key, value, oldvalue)
if key == "basedir":
self.browse_button.setMenu(self.browse_menu)
self.import_items_model.setReplacementEnv(self._replacements())
@Slot(int)
def activate_recent(self, index):
"""
Activate an item from the recent list.
"""
model = self.import_items_model
cb = self.recent_combo
if 0 <= index < model.rowCount():
item = model.item(index)
assert isinstance(item, ImportItem)
path = item.path()
item.setData(True, ImportItem.IsSessionItemRole)
move_item_to_index(model, item, 0)
if not os.path.exists(path):
self._browse_for_missing(
item, onfinished=lambda status: self._invalidate()
)
else:
cb.setCurrentIndex(0)
self._invalidate()
else:
self.recent_combo.setCurrentIndex(-1)
def _browse_for_missing(
self, item: ImportItem, *, onfinished: Optional[Callable[[int], Any]] = None):
dlg = self._browse_dialog()
model = self.import_items_model
if onfinished is None:
onfinished = lambda status: None
vpath = item.varPath()
prefixpath = None
if isinstance(vpath, PathItem.VarPath):
prefixpath = self._replacements().get(vpath.name)
if prefixpath is not None:
dlg.setDirectory(prefixpath)
dlg.setAttribute(Qt.WA_DeleteOnClose)
def accepted():
path = dlg.selectedFiles()[0]
if isinstance(vpath, VarPath) and not isprefixed(prefixpath, path):
mb = self._path_must_be_relative_mb(prefixpath)
mb.show()
mb.finished.connect(lambda _: onfinished(QDialog.Rejected))
return
# pre-flight check; try to determine the nature of the file
mtype = _mime_type_for_path(path)
if not mtype.inherits("text/plain"):
mb = self._might_be_binary_mb(path)
if mb.exec() == QMessageBox.Cancel:
if onfinished:
onfinished(QDialog.Rejected)
return
if isinstance(vpath, VarPath):
vpath_ = VarPath(vpath.name, os.path.relpath(path, prefixpath))
else:
vpath_ = AbsPath(path)
item.setVarPath(vpath_)
if item.row() != 0:
move_item_to_index(model, item, 0)
item.setData(True, ImportItem.IsSessionItemRole)
self.set_selected_file(path, item.options())
self._note_recent(path, item.options())
onfinished(QDialog.Accepted)
dlg.accepted.connect(accepted)
dlg.open()
def _browse_dialog(self):
dlg = FileDialog(
self, windowTitle=self.tr("Open Data File"),
acceptMode=QFileDialog.AcceptOpen,
fileMode=QFileDialog.ExistingFile
)
dlg.setFileFormats(FileFormats)
state = self.dialog_state
lastdir = state.get("directory", "")
lastfilter = state.get("filter", "")
if lastdir and os.path.isdir(lastdir):
dlg.setDirectory(lastdir)
if lastfilter:
dlg.selectNameFilter(lastfilter)
def store_state():
state["directory"] = dlg.directory().absolutePath()
state["filter"] = dlg.selectedNameFilter()
dlg.accepted.connect(store_state)
return dlg
def _might_be_binary_mb(self, path) -> QMessageBox:
mb = QMessageBox(
parent=self,
windowTitle=self.tr(""),
icon=QMessageBox.Question,
text=self.tr("The '{basename}' may be a binary file.\n"
"Are you sure you want to continue?").format(
basename=os.path.basename(path)),
standardButtons=QMessageBox.Cancel | QMessageBox.Yes
)
mb.setWindowModality(Qt.WindowModal)
return mb
def _path_must_be_relative_mb(self, prefix: str) -> QMessageBox:
mb = QMessageBox(
parent=self, windowTitle=self.tr("Invalid path"),
icon=QMessageBox.Warning,
text=self.tr("Selected path is not within '{prefix}'").format(
prefix=prefix
),
)
mb.setAttribute(Qt.WA_DeleteOnClose)
return mb
@Slot(str)
def browse_relative(self, prefixname):
path = self._replacements().get(prefixname)
self.browse(prefixname=prefixname, directory=path)
@Slot()
def browse(self, prefixname=None, directory=None):
"""
Open a file dialog and select a user specified file.
"""
dlg = self._browse_dialog()
if directory is not None:
dlg.setDirectory(directory)
status = dlg.exec()
dlg.deleteLater()
if status == QFileDialog.Accepted:
selected_filter = dlg.selectedFileFormat()
path = dlg.selectedFiles()[0]
if prefixname:
_prefixpath = self._replacements().get(prefixname, "")
if not isprefixed(_prefixpath, path):
mb = self._path_must_be_relative_mb(_prefixpath)
mb.show()
return
varpath = VarPath(prefixname, os.path.relpath(path, _prefixpath))
else:
varpath = PathItem.AbsPath(path)
# pre-flight check; try to determine the nature of the file
mtype = _mime_type_for_path(path)
if not mtype.inherits("text/plain"):
mb = self._might_be_binary_mb(path)
if mb.exec() == QMessageBox.Cancel:
return
# initialize options based on selected format
options = default_options_for_mime_type(
path, selected_filter.mime_type,
)
# Search for path in history.
# If found use the stored params to initialize the import dialog
items = self.itemsFromSettings()
idx = index_where(items, lambda t: samepath(t[0], path))
if idx is not None:
_, options_ = items[idx]
if options_ is not None:
options = options_
dlg = CSVImportDialog(
self, windowTitle="Import Options", sizeGripEnabled=True)
dlg.setWindowModality(Qt.WindowModal)
dlg.setPath(path)
dlg.setOptions(options)
status = dlg.exec()
dlg.deleteLater()
if status == QDialog.Accepted:
self.set_selected_file(path, dlg.options())
self.current_item().setVarPath(varpath)
def current_item(self):
# type: () -> Optional[ImportItem]
"""
Return the current selected item (file) or None if there is no
current item.
"""
idx = self.recent_combo.currentIndex()
if idx == -1:
return None
item = self.recent_combo.model().item(idx) # type: QStandardItem
if isinstance(item, ImportItem):
return item
else:
return None
def _activate_import_dialog(self):
"""Activate the Import Options dialog for the current item."""
item = self.current_item()
assert item is not None
dlg = CSVImportDialog(
self, windowTitle="Import Options", sizeGripEnabled=True,
)
dlg.setWindowModality(Qt.WindowModal)
dlg.setAttribute(Qt.WA_DeleteOnClose)
settings = self._local_settings()
settings.beginGroup(qname(type(dlg)))
size = settings.value("size", QSize(), type=QSize) # type: QSize
if size.isValid():
dlg.resize(size)
path = item.data(ImportItem.PathRole)
options = item.data(ImportItem.OptionsRole)
dlg.setPath(path) # Set path before options so column types can
if isinstance(options, Options):
dlg.setOptions(options)
def update():
newoptions = dlg.options()
item.setData(newoptions, ImportItem.OptionsRole)
# update local recent paths list
self._note_recent(path, newoptions)
if newoptions != options:
self._invalidate()
dlg.accepted.connect(update)
def store_size():
settings.setValue("size", dlg.size())
dlg.finished.connect(store_size)
dlg.show()
def set_selected_file(self, filename, options=None):