-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils_ui.py
662 lines (515 loc) · 20.4 KB
/
utils_ui.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
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 29 08:09:12 2016
@author: giroux
Copyright 2017 Bernard Giroux, Jerome Simon
email: [email protected]
This file is part of BhTomoPy.
BhTomoPy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from PyQt5 import QtWidgets, QtCore
from database import BhTomoDb
class MyQLabel(QtWidgets.QLabel):
def __init__(self, label, ha='left', parent=None):
super(MyQLabel, self).__init__(label, parent)
if ha == 'center':
self.setAlignment(QtCore.Qt.AlignHCenter)
elif ha == 'right':
self.setAlignment(QtCore.Qt.AlignRight)
else:
self.setAlignment(QtCore.Qt.AlignLeft)
def choose_mog(_db=None, parent=None):
d = QtWidgets.QDialog(parent)
l0 = QtWidgets.QLabel(parent=d)
l0.setAlignment(QtCore.Qt.AlignCenter)
l0.setStyleSheet('background-color: white')
b0 = QtWidgets.QPushButton("Choose Database", d)
b1 = QtWidgets.QPushButton("Ok", d)
b2 = QtWidgets.QPushButton("Cancel", d)
b3 = QtWidgets.QComboBox(d)
l0.move(10, 10)
b0.move(10, 40)
b1.setMinimumWidth(b2.width())
b2.setMinimumWidth(b1.minimumWidth())
b0.setMinimumWidth(10 + 2 * b1.minimumWidth())
l0.setMinimumWidth(10 + 2 * b1.minimumWidth())
b3.setMinimumWidth(2 * b1.minimumWidth())
b3.move(15, 70)
b2.move(10, 100)
b1.move(20 + b1.minimumWidth(), 100)
if _db is None:
db = BhTomoDb()
else:
db = _db
def cancel():
nonlocal d
d.done(0)
def ok():
nonlocal d
d.done(1)
def choose_db():
nonlocal d
nonlocal l0
nonlocal b3
filename = QtWidgets.QFileDialog.getOpenFileName(d, 'Choose Database','','Database (*.h5)')[0]
if filename:
db.filename = filename
l0.setText(os.path.basename(filename))
else:
l0.setText('')
def load_mogs():
names = db.get_mog_names()
if len(names) > 0:
b3.addItems(names)
else:
QtWidgets.QMessageBox.warning(b3, '', 'File does not contain MOGS.',
QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.NoButton)
l0.setText('')
b1.setFocus()
if db.filename != '':
l0.setText(os.path.basename(db.filename))
load_mogs()
else:
l0.setText('')
b1.clicked.connect(ok)
b2.clicked.connect(cancel)
b0.clicked.connect(choose_db)
d.setWindowTitle("Choose MOG")
d.setWindowModality(QtCore.Qt.ApplicationModal)
isOk = d.exec_()
if isOk == 1:
mog_name = b3.currentText()
return db.get_mog(mog_name), db
def save_mog(mog, db):
# TODO: make sure all boreholes and air_shots held in Tx, Rx, av & ap are in db, raise ReferenceError if not
db.save_mog(mog)
def chooseModel(_db=None):
d = QtWidgets.QDialog()
l0 = QtWidgets.QLabel(parent=d)
l0.setAlignment(QtCore.Qt.AlignCenter)
l0.setStyleSheet('background-color: white')
b0 = QtWidgets.QPushButton("Choose Database", d)
b1 = QtWidgets.QPushButton("Ok", d)
b2 = QtWidgets.QPushButton("Cancel", d)
b3 = QtWidgets.QComboBox(d)
l0.move(10, 10)
b0.move(10, 40)
b1.setMinimumWidth(b2.width())
b2.setMinimumWidth(b1.minimumWidth())
b0.setMinimumWidth(10 + 2 * b1.minimumWidth())
l0.setMinimumWidth(10 + 2 * b1.minimumWidth())
b3.setMinimumWidth(2 * b1.minimumWidth())
b3.move(15, 70)
b2.move(10, 100)
b1.move(20 + b1.minimumWidth(), 100)
if _db is None:
db = BhTomoDb()
else:
db = _db
def cancel():
nonlocal d
d.done(0)
def ok():
nonlocal d
d.done(1)
def choose_db():
nonlocal d
nonlocal l0
nonlocal b3
filename = QtWidgets.QFileDialog.getOpenFileName(d, 'Choose Database','','Database (*.h5)')[0]
if filename:
db.filename = filename
l0.setText(os.path.basename(filename))
else:
l0.setText('')
def load_models():
nonlocal b3
nonlocal l0
b3.clear()
names = db.get_model_names()
if len(names) > 0:
b3.addItems(names)
else:
QtWidgets.QMessageBox.warning(b3, '', 'File does not contain Models.')
l0.setText('')
b1.setFocus()
if db.filename != '':
l0.setText(os.path.basename(db.filename))
load_models()
else:
l0.setText('')
b1.clicked.connect(ok)
b2.clicked.connect(cancel)
b0.clicked.connect(choose_db)
d.setWindowTitle("Choose Model")
d.setWindowModality(QtCore.Qt.ApplicationModal)
isOk = d.exec_()
if isOk == 1:
model_name = b3.currentText()
return db.get_model(model_name), db
def save_warning(db):
if db.modified: # if any data has been modified, warn the user. Otherwise, proceed.
d = QtWidgets.QDialog()
l0 = QtWidgets.QLabel(parent=d)
l0.setAlignment(QtCore.Qt.AlignCenter)
b0 = QtWidgets.QPushButton("Save", d)
b1 = QtWidgets.QPushButton("Save as", d)
b2 = QtWidgets.QPushButton("Discard changes", d)
b3 = QtWidgets.QPushButton("Cancel", d)
width = b2.sizeHint().width()
l0.move(10, 10)
b0.setMinimumWidth(width)
b1.setMinimumWidth(width)
b2.setMinimumWidth(width)
b3.setMinimumWidth(width)
b0.move(15, 40)
b1.move(15 + width, 40)
b2.move(15 + 2 * width, 40)
b3.move(15 + 3 * width, 40)
l0.setMinimumWidth(10 + 4 * width)
d.setMaximumWidth(10 * 3 + width * 4)
d.setMaximumHeight(10 * 2 + b2.sizeHint().height() * 2)
d.setMinimumWidth(10 * 3 + width * 4)
d.setMinimumHeight(10 * 2 + b2.sizeHint().height() * 2)
l0.setText("You must save your database before proceeding.")
d.setWindowTitle("Warning")
d.setWindowModality(QtCore.Qt.ApplicationModal)
def save():
nonlocal d
d.done(1)
def save_as():
nonlocal d
d.done(2)
def no_save():
nonlocal d
d.done(3)
def cancel():
nonlocal d
d.done(0)
b0.clicked.connect(save)
b1.clicked.connect(save_as)
b2.clicked.connect(no_save)
b3.clicked.connect(cancel)
ok = d.exec_()
if ok == 0:
ok = False
elif ok == 1:
ok = savefile(db)
elif ok == 2:
ok = saveasfile(db)
elif ok == 3:
ok = True
return ok # returns False if action has to be reverted. Returns True otherwise.
else:
return True
def savefile(db):
try:
if db.filename == '':
return saveasfile(db)
db.save()
QtWidgets.QMessageBox.information(None, 'Success', "Database was saved successfully",
buttons=QtWidgets.QMessageBox.Ok)
return True
except Exception as e:
QtWidgets.QMessageBox.warning(None, 'Warning', "Database could not be saved : " + str(e),
buttons=QtWidgets.QMessageBox.Ok)
return False
def saveasfile(db):
filename = QtWidgets.QFileDialog.getSaveFileName(None, 'Save Database as ...', filter='Database (*.h5)', )[0]
if filename:
db.filename = filename
db.save()
QtWidgets.QMessageBox.information(None, 'Success', "Database was saved successfully",
buttons=QtWidgets.QMessageBox.Ok)
return True
return False
def auto_create_scrollbar(widget):
"""
Adds a scrollbar to a widget. The scrollbar appears IF NEEDED. The returned scrollbar
object is the one that must then be manipulated (i.e. not the sent widget).
"""
scrollbar = QtWidgets.QScrollArea()
scrollbar.setWidget(widget)
scrollbar.setWidgetResizable(True)
desired_min_height = widget.sizeHint().height()
desired_min_width = widget.sizeHint().width()
screen_resolution = QtWidgets.QApplication.desktop().screenGeometry()
width, height = screen_resolution.width(), screen_resolution.height()
if desired_min_height > 4 / 5 * height: # sets a threshold that limits the size of the widget. 4 / 5 is an arbitrary
desired_min_height = 4 / 5 * height # number accounting for the menu bar and the scroll bar.
if desired_min_width > 4 / 5 * width:
desired_min_width = 4 / 5 * width
scrollbar.setMinimumWidth(desired_min_width)
scrollbar.setMinimumHeight(desired_min_height)
return scrollbar
def duplicate_verif(string, string_list): # deprecated
"""
Returns whether or not there is a duplicate in a list with some additional feedback.
"""
if not string:
QtWidgets.QMessageBox.warning(None, "Warning", "Could not rename: field must not be empty.")
return True
if string in string_list:
QtWidgets.QMessageBox.warning(None, "Warning", "Could not rename: this name already exists.")
return True
return False
def duplicate_new_name(string, string_list): # deprecated
"""
Verifies if a string has a duplicate in a list and returns a new string in such cases.
"""
if not string:
raise ValueError
recursion = 1
while string in string_list:
if recursion != 1:
string = string[:-2]
string += ' ' + str(recursion)
recursion += 1
return string
def lay(layout, *options, parent=None):
"""
An intuitive and auto-documentating way of creating a layout. Steps such as grid and widget initialization
are included in this function, accounting for an upgrade in readability. One should send a layout of the form:
[[model_label, '|', Upper_limit_checkbox, velocity_edit ],
[cells_no_label, cells_label, ellip_veloc_checkbox, '' ],
[rays_no_label, rays_label, tilted_ellip_veloc_checkbox, '' ],
[mogs_list, '|', include_checkbox, '' ],
['', '', T_and_A_combo, btn_Show_Stats ],
['_', '', Sub_Curved_Rays_Widget, '' ]]
In which every object is pre-existing. If a widget should take more than one square, one should indicate
the line and column at which the widget ends by an underscore ('_') and a vertical slash ('|'), respectively.
Every blank square should then be filled with an empty string ('').
Additional options may be sent in the form of a string, or a tuple if the option requires parameters. For instance,
'noMargins' would create a layout without margins and ('groupbox', "Grid") would make the parent widget a groupbox
with name "Grid". Adding non-existent options to the 'lay' function only requires one to define said function above
'opt_dict' and including the string corresponding to the function in 'opt_dict'.
If one wishes to make an outside widget the parent of the grid, the parent parameter should be set to the desired
widget. Such cases include associating a master grid to a form.
Tips:
* If a layout has only one line, a second pair of brackets is not necessary (for instance [w1, w2], rather than [[w1, w2]]).
* Some options have a custom way of managing paramaters (for instance 'setMinHei'). One should take a moment to look those up.
"""
import PyQt5.QtWidgets as wgt
from itertools import count
def getSpan(row_no, col_no):
"""
Gets the width and height in terms of squares for a widget at row 'row_no' and column 'col_no'.
"""
row_span = 1
col_span = 1
for row in count(row_no + 1):
try:
item = layout[row][col_no]
if not isinstance(item, str) or item == '|':
break
elif item == '_':
row_span = row - row_no + 1
except IndexError:
break
for col in count(col_no + 1):
try:
item = layout[row_no][col]
if not isinstance(item, str) or item == '_':
break
elif item == '|':
col_span = col - col_no + 1
except IndexError:
break
return row_no, col_no, row_span, col_span
# Widget initialization and grid filling #
if parent is None:
widget = None
grid = wgt.QGridLayout()
if not isinstance(layout[0], (list, tuple)):
layout = [layout]
verif_dims(layout)
for row, row_no in zip(layout, count()):
for item, col_no in zip(row, count()):
if item not in ('', '|', '_'):
grid.addWidget(item, *getSpan(row_no, col_no))
# Options definitions and dictionary #
def noMargins(*args):
nonlocal grid
grid.setContentsMargins(0, 0, 0, 0)
def scrollbar(*args): # Makes the layout a scrollbar instead of the default widget.
nonlocal widget
if parent is None:
if widget is None:
widget = wgt.QWidget()
widget.setLayout(grid)
widget = auto_create_scrollbar(widget)
else:
raise TypeError("A format has already been specified. Can't format " + str(type(widget)) + " into a scrollbar.")
else:
raise TypeError("A form can't be formatted into a scrollbar.")
def groupbox(*args): # Makes the layout a groupbox instead of the default widget.
nonlocal widget
if parent is None:
if widget is None:
widget = wgt.QGroupBox(*args) # Takes the same arguments as the standard QGroupBox
widget.setLayout(grid)
else:
raise TypeError("A format has already been specified. Can't format " + str(type(widget)) + " into a scrollbar.")
else:
raise TypeError("A form can't be formatted into a groupbox.")
def setRowStr(*args):
# Arguments can either be of the form ('setRowStr', row, stretch) or ('setRowStr', (row, str), (row, str), ...)
nonlocal grid
if isinstance(args[-1], (list, tuple)): # ('setRowStr', (row, str), (row, str), ...)
for i in args:
grid.setRowStretch(*i)
else: # ('setRowStr', row, stretch)
grid.setRowStretch(*i)
def setColStr(*args):
# Arguments can either be of the form ('setColStr', col, stretch) or ('setRowStr', (col, str), (col, str), ...)
nonlocal grid
if isinstance(args[-1], (list, tuple)): # ('setRowStr', (col, str), (col, str), ...)
for i in args:
grid.setColumnStretch(*i)
else: # ('setColStr', col, stretch)
grid.setColumnStretch(*i)
def setMinHei(*args):
# Arguments can either be of the form ('setMinHei', widget, height) or ('setMinHei', row, height) or
# ('setMinHei', (...), (...), (...), ...) or ('setMinHei', (widget, widget, ...), height)
nonlocal grid
if isinstance(args[-1], (list, tuple)): # ('setMinHei', (...), (...), (...), ...)
for i in args:
setMinHei(*i)
else:
if isinstance(args[0], int): # ('setMinHei', row, height)
grid.setRowMinimumHeight(*args)
elif isinstance(args[0], (list, tuple)): # ('setMinHei', (widget, widget, ...), height)
for item in args[0]:
item.setMinimumHeight(args[1])
else: # ('setMinHei', widget, height)
args[0].setMinimumHeight(args[1])
def setMaxHei(*args):
# Refer to 'SetMinHei'.
nonlocal grid
if isinstance(args[-1], (list, tuple)):
for i in args:
setMaxHei(*i)
else:
if isinstance(args[0], int):
raise AttributeError("Cannot operate 'setMaxHei' on a grid.")
elif isinstance(args[0], (list, tuple)):
for item in args[0]:
item.setMaximumHeight(args[1])
else:
args[0].setMaximumHeight(args[1])
def setFixHei(*args):
# The specified height can't be modified by the user.
nonlocal grid
setMinHei(*args)
setMaxHei(*args)
def setMinWid(*args):
# Refer to 'SetMinHei'.
nonlocal grid
if isinstance(args[-1], (list, tuple)):
for i in args:
setMinWid(*i)
else:
if isinstance(args[0], int):
grid.setColumnMinimumWidth(*args)
elif isinstance(args[0], (list, tuple)):
for item in args[0]:
item.setMinimumWidth(args[1])
else:
args[0].setMinimumWidth(args[1])
def setMaxWid(*args):
# Refer to 'SetMinHei'.
nonlocal grid
if isinstance(args[-1], (list, tuple)):
for i in args:
setMaxWid(*i)
else:
if isinstance(args[0], int):
raise AttributeError("Cannot operate 'setMaxWid' on a grid.")
elif isinstance(args[0], (list, tuple)):
for item in args[0]:
item.setMaximumWidth(args[1])
else:
args[0].setMaximumWidth(args[1])
def setFixWid(*args):
# The specified width can't be modified by the user.
nonlocal grid
setMinWid(*args)
setMaxWid(*args)
def setHorSpa(*args):
nonlocal grid
grid.setHorizontalSpacing(*args)
def setVerSpa(*args):
nonlocal grid
grid.setVerticalSpacing(*args)
opt_dict = {'noMargins': noMargins,
'scrollbar': scrollbar,
'groupbox' : groupbox,
'setRowStr': setRowStr,
'setColStr': setColStr,
'setMinHei': setMinHei,
'setMaxHei': setMaxHei,
'setFixHei': setFixHei,
'setMinWid': setMinWid,
'setMaxWid': setMaxWid,
'setFixWid': setFixWid,
'setHorSpa': setHorSpa,
'setVerSpa': setVerSpa}
# Applying the options and returning the results #
for option in options:
if isinstance(option, str): # An option can be sent as a plain string if it does not require parameters
opt_dict[option]()
else:
opt_dict[option[0]](*option[1:])
if parent is None:
if widget is None: # If a scrollbar or gridbox hasn't been selected, the returned widget is the default one
widget = wgt.QWidget()
widget.setLayout(grid)
return widget
else:
parent.setLayout(grid)
def inv_lay(layout, *options, parent=None):
"""
A way of sending the matrix transpose of 'layout' into 'lay'.
Columns of widgets take up less place in the code this way.
See 'lay'.
"""
from itertools import count
temp = []
if isinstance(layout[0], (list, tuple)):
verif_dims(layout)
for _ in range(len(layout[0])):
temp.append([])
for row in layout:
for item, col_no in zip(row, count()):
if item == '_':
item = '|'
elif item == '|':
item = '_'
temp[col_no].append(item)
else:
for item in layout:
if item == '_':
item = '|'
elif item == '|':
item = '_'
temp.append([item])
return lay(temp, *options, parent=parent)
def verif_dims(layout):
for row in layout[1:]:
if len(row) != len(layout[0]):
raise IndexError("Layout has wrong dimensions.")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mog, db = choose_mog()
sys.exit(app.exec_())