/
widgets.py
executable file
·242 lines (208 loc) · 9.21 KB
/
widgets.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
# -*- coding: utf-8 -*-
"""Creat File dialog boxes using the PyQt5 module.
Code based on the PyQt5 Tutorial code,
"""
__all__ = ["fileDialog"]
import pathlib
from typing import Any, Union, Optional, Dict, Type
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
from matplotlib.patches import Rectangle
from ..compat import mpl_version
try:
from PyQt5.QtWidgets import QWidget, QFileDialog, QApplication
except ImportError:
class App:
"""Mock App that raises an error when you try to call openDialog on it."""
modes: Dict = {}
def openDialog(
self,
title: Optional[str] = None,
start: Union[str, pathlib.Path] = "",
patterns: Optional[Dict] = None,
mode: str = "OpenFile",
) -> Optional[pathlib.Path]:
"""Raise and error because PyQT5 not present."""
raise ValueError("Cammpt open a dialog box because PqQt5 library missing!")
else:
class App(QApplication):
"""Placehold PyQT5 Application for producing filedialog boxes."""
modes = {
"OpenFile": {
"method": QFileDialog.getOpenFileName,
"caption": "Select file to open...",
"arg": ["parent", "caption", "directory", "filter", "options"],
},
"OpenFiles": {
"method": QFileDialog.getOpenFileNames,
"caption": "Select file(s_ to open...",
"arg": ["parent", "caption", "directory", "filter", "options"],
},
"SaveFile": {
"method": QFileDialog.getSaveFileName,
"caption": "Save file as...",
"arg": ["parent", "caption", "directory", "filter", "options"],
},
"SelectDirectory": {
"method": QFileDialog.getExistingDirectory,
"caption": "Select folder...",
"arg": ["parent", "caption", "directory", "options"],
},
}
def __init__(self, *args: Any, **kargs: Any) -> None:
super().__init__([""], *args, **kargs)
self.title = "PyQt5 file dialogs - pythonspot.com"
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self) -> None:
self.dialog = QWidget()
self.dialog.title = "PyQt5 file dialogs - pythonspot.com"
self.dialog.left = 10
self.dialog.top = 10
self.dialog.width = 640
self.dialog.height = 480
self.dialog.setWindowTitle(self.title)
self.dialog.setGeometry(self.left, self.top, self.width, self.height)
def openDialog(
self,
title: Optional[str] = None,
start: Union[str, pathlib.Path] = "",
patterns: Optional[Dict] = None,
mode: str = "OpenFile",
) -> Optional[pathlib.Path]:
"""Create a dialog box for selecting filenames or directories.
Keyword Arguments:
title (str, None):
Label of the dialog box, default None will select something depending on the mode.
start (str):
The starting directory for the dialog box.
patterns (dict):
Filename patterns - the keys of the dictionary are glob patterns, the values the corresponding
explanation of the file
type.
mode (str):
Determines the type of filedialog box used. Values are:
- "OpenFile" - get a single existing file
- "OpenFiles" - get one or more existing files
- "SaveFile" - get an existing or new file - warns about overwriting files
- "SelectDirectory" - gets the name of an existing (possibly newly created) directory.
Returns:
(str, None):
Either a string containing the absolute path to the file or directory, or None if the dialog
was cancelled.
"""
if mode not in self.modes:
raise ValueError(f"Unknown dialog mode {mode}")
method = self.modes[mode]["method"]
if title is None:
title = self.modes[mode]["caption"]
if patterns is None:
patterns = {"*.*": "All Files", "*.py": "Python Files"}
patterns = ";;".join([f"{v} ({k})" for k, v in patterns.items()])
options = QFileDialog.Options()
kwargs = {"caption": title, "directory": str(start), "filter": patterns, "options": options, "modal": True}
kwargs = {k: kwargs[k] for k in (set(kwargs.keys()) & set(self.modes[mode]["arg"]))}
ret = method(self.dialog, **kwargs)
if isinstance(ret, tuple):
ret = ret[0]
if isinstance(ret, (str, pathlib.PurePath)):
ret = pathlib.Path(ret)
elif isinstance(ret, list):
ret = [pathlib.Path(x) for x in ret]
elif not ret:
ret = None
else:
raise TypeError(f"Something when wrong here - can't handle {ret} as a {type(ret)}")
return ret
class RangeSelect:
"""A simple class to allow a matplotlib graph to be used to select data."""
def __init__(self):
"""Initialise the selector state."""
self.data = None
self.finished = False
self.selector = []
self.invert = False
self.xcol = None
self.ycol = None
self.selection = []
self.ax = None
def __call__(self, data, xcol, accuracy, invert=False):
"""Run the selector with the data."""
self.data = data
self.data._select = self # To allow for unit testing
self.xcol = xcol
self.invert = invert
col = "red" if self.invert else "green"
if len(self.data.setas.y) > 0:
self.ycol = self.data.setas.y
else:
self.ycol = list(range(self.data.shape[1]))
self.ycol.remove(self.xcol)
# Preserve figure settings before creating plot
fig_tmp = getattr(self.data, "fig", None), getattr(self.data, "axes", None)
fig = plt.figure()
self.data.plot(self.xcol, self.ycol, figure=fig)
self.data.title = "Select Data and press Enter to confirm\nEsc to cancel, i to invert selection."
self.ax = self.data.axes[-1]
if mpl_version.minor >= 5:
kargs = {"props": {"edgecolor": col, "facecolor": col, "alpha": 0.5}}
else:
kargs = {"rectprops": {"edgecolor": col, "facecolor": col, "alpha": 0.5}}
self.selector = SpanSelector(
self.ax,
self.onselect,
"horizontal",
useblit=True,
**kargs,
)
fig.canvas.mpl_connect("key_press_event", self.keypress)
while not self.finished:
plt.pause(0.1)
# Clean up and restore the figure settings
plt.close(self.data.fig.number)
if fig_tmp[0] is not None and fig_tmp[0] in plt.get_fignums():
self.data.fig = fig_tmp[0]
delattr(self.data, "_select")
idx = np.ones(len(self.data), dtype=bool)
for ix, selection in enumerate(self.selection):
if ix == 0:
idx = self.data._search_index(xcol, selection, accuracy, invert=self.invert)
else:
idx = np.logical_or(idx, self.data._search_index(xcol, selection, accuracy, invert=self.invert))
return idx
def onselect(self, xmin, xmax):
"""Add the selection limits to the selections list."""
self.selection.append((xmin, xmax))
ylim = self.ax.get_ylim()
col = "red" if self.invert else "green"
rect = Rectangle((xmin, ylim[0]), xmax - xmin, ylim[1] - ylim[0], edgecolor=col, facecolor=col, alpha=0.5)
self.ax.add_patch(rect)
def keypress(self, event):
"""Habndle key press events.
Args:
event (matplotlib event):
The matplotlib event object
Returns:
None.
Tracks the mode and adjusts the cursor display.
"""
if event.key.lower() == "enter": # Finish selection
self.finished = True
elif event.key.lower() == "escape": # Abandon selection
self.selection = []
self.finished = True
elif event.key.lower() == "backspace": # Delete last selection
if len(self.selection) > 0:
del self.selection[-1]
self.ax.patches[-1].remove()
self.data.fig.canvas.draw()
elif event.key.lower() == "i": # Invert selection
self.invert = ~self.invert
col = "red" if self.invert else "green"
for p in self.ax.patches:
p.update({"color": col, "facecolor": col})
fileDialog: Type[App] = App()